[jit] Use mini_emit_memory_load for ldind, ldobj and ldfld
[mono.git] / mono / mini / method-to-ir.c
1 /**
2  * \file
3  * Convert CIL to the JIT internal representation
4  *
5  * Author:
6  *   Paolo Molaro (lupus@ximian.com)
7  *   Dietmar Maurer (dietmar@ximian.com)
8  *
9  * (C) 2002 Ximian, Inc.
10  * Copyright 2003-2010 Novell, Inc (http://www.novell.com)
11  * Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
12  * Licensed under the MIT license. See LICENSE file in the project root for full license information.
13  */
14
15 #include <config.h>
16 #include <mono/utils/mono-compiler.h>
17 #include "mini.h"
18
19 #ifndef DISABLE_JIT
20
21 #include <signal.h>
22
23 #ifdef HAVE_UNISTD_H
24 #include <unistd.h>
25 #endif
26
27 #include <math.h>
28 #include <string.h>
29 #include <ctype.h>
30
31 #ifdef HAVE_SYS_TIME_H
32 #include <sys/time.h>
33 #endif
34
35 #ifdef HAVE_ALLOCA_H
36 #include <alloca.h>
37 #endif
38
39 #include <mono/utils/memcheck.h>
40 #include <mono/metadata/abi-details.h>
41 #include <mono/metadata/assembly.h>
42 #include <mono/metadata/attrdefs.h>
43 #include <mono/metadata/loader.h>
44 #include <mono/metadata/tabledefs.h>
45 #include <mono/metadata/class.h>
46 #include <mono/metadata/object.h>
47 #include <mono/metadata/exception.h>
48 #include <mono/metadata/opcodes.h>
49 #include <mono/metadata/mono-endian.h>
50 #include <mono/metadata/tokentype.h>
51 #include <mono/metadata/tabledefs.h>
52 #include <mono/metadata/marshal.h>
53 #include <mono/metadata/debug-helpers.h>
54 #include <mono/metadata/debug-internals.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/utils/mono-memory-model.h>
63 #include <mono/utils/mono-error-internals.h>
64 #include <mono/metadata/mono-basic-block.h>
65 #include <mono/metadata/reflection-internals.h>
66 #include <mono/utils/mono-threads-coop.h>
67
68 #include "trace.h"
69
70 #include "ir-emit.h"
71
72 #include "jit-icalls.h"
73 #include "jit.h"
74 #include "debugger-agent.h"
75 #include "seq-points.h"
76 #include "aot-compiler.h"
77 #include "mini-llvm.h"
78
79 #define BRANCH_COST 10
80 #define INLINE_LENGTH_LIMIT 20
81
82 /* These have 'cfg' as an implicit argument */
83 #define INLINE_FAILURE(msg) do {                                                                        \
84         if ((cfg->method != cfg->current_method) && (cfg->current_method->wrapper_type == MONO_WRAPPER_NONE)) { \
85                 inline_failure (cfg, msg);                                                                              \
86                 goto exception_exit;                                                                                    \
87         } \
88         } while (0)
89 #define CHECK_CFG_EXCEPTION do {\
90                 if (cfg->exception_type != MONO_EXCEPTION_NONE) \
91                         goto exception_exit;                                            \
92         } while (0)
93 #define FIELD_ACCESS_FAILURE(method, field) do {                                        \
94                 field_access_failure ((cfg), (method), (field));                        \
95                 goto exception_exit;    \
96         } while (0)
97 #define GENERIC_SHARING_FAILURE(opcode) do {            \
98                 if (cfg->gshared) {                                                                     \
99                         gshared_failure (cfg, opcode, __FILE__, __LINE__);      \
100                         goto exception_exit;    \
101                 }                       \
102         } while (0)
103 #define GSHAREDVT_FAILURE(opcode) do {          \
104         if (cfg->gsharedvt) {                                                                                           \
105                 gsharedvt_failure (cfg, opcode, __FILE__, __LINE__);                    \
106                 goto exception_exit;                                                                                    \
107         }                                                                                                                                       \
108         } while (0)
109 #define OUT_OF_MEMORY_FAILURE do {      \
110                 mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);                \
111                 mono_error_set_out_of_memory (&cfg->error, "");                                 \
112                 goto exception_exit;    \
113         } while (0)
114 #define DISABLE_AOT(cfg) do { \
115                 if ((cfg)->verbose_level >= 2)                                            \
116                         printf ("AOT disabled: %s:%d\n", __FILE__, __LINE__);   \
117                 (cfg)->disable_aot = TRUE;                                                        \
118         } while (0)
119 #define LOAD_ERROR do { \
120                 break_on_unverified ();                                                         \
121                 mono_cfg_set_exception (cfg, MONO_EXCEPTION_TYPE_LOAD); \
122                 goto exception_exit;                                                                    \
123         } while (0)
124
125 #define TYPE_LOAD_ERROR(klass) do { \
126                 cfg->exception_ptr = klass; \
127                 LOAD_ERROR;                                     \
128         } while (0)
129
130 #define CHECK_CFG_ERROR do {\
131                 if (!mono_error_ok (&cfg->error)) { \
132                         mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);        \
133                         goto mono_error_exit; \
134                 } \
135         } while (0)
136
137 /* Determine whenever 'ins' represents a load of the 'this' argument */
138 #define MONO_CHECK_THIS(ins) (mono_method_signature (cfg->method)->hasthis && ((ins)->opcode == OP_MOVE) && ((ins)->sreg1 == cfg->args [0]->dreg))
139
140 static int ldind_to_load_membase (int opcode);
141 static int stind_to_store_membase (int opcode);
142
143 int mono_op_to_op_imm (int opcode);
144 int mono_op_to_op_imm_noemul (int opcode);
145
146 static int inline_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **sp,
147                                                   guchar *ip, guint real_offset, gboolean inline_always);
148 static MonoInst*
149 emit_llvmonly_virtual_call (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, int context_used, MonoInst **sp);
150
151 /* helper methods signatures */
152 static MonoMethodSignature *helper_sig_domain_get;
153 static MonoMethodSignature *helper_sig_rgctx_lazy_fetch_trampoline;
154 static MonoMethodSignature *helper_sig_llvmonly_imt_trampoline;
155 static MonoMethodSignature *helper_sig_jit_thread_attach;
156 static MonoMethodSignature *helper_sig_get_tls_tramp;
157 static MonoMethodSignature *helper_sig_set_tls_tramp;
158
159 /* type loading helpers */
160 static GENERATE_GET_CLASS_WITH_CACHE (runtime_helpers, "System.Runtime.CompilerServices", "RuntimeHelpers")
161 static GENERATE_TRY_GET_CLASS_WITH_CACHE (debuggable_attribute, "System.Diagnostics", "DebuggableAttribute")
162
163 /*
164  * Instruction metadata
165  */
166 #ifdef MINI_OP
167 #undef MINI_OP
168 #endif
169 #ifdef MINI_OP3
170 #undef MINI_OP3
171 #endif
172 #define MINI_OP(a,b,dest,src1,src2) dest, src1, src2, ' ',
173 #define MINI_OP3(a,b,dest,src1,src2,src3) dest, src1, src2, src3,
174 #define NONE ' '
175 #define IREG 'i'
176 #define FREG 'f'
177 #define VREG 'v'
178 #define XREG 'x'
179 #if SIZEOF_REGISTER == 8 && SIZEOF_REGISTER == SIZEOF_VOID_P
180 #define LREG IREG
181 #else
182 #define LREG 'l'
183 #endif
184 /* keep in sync with the enum in mini.h */
185 const char
186 ins_info[] = {
187 #include "mini-ops.h"
188 };
189 #undef MINI_OP
190 #undef MINI_OP3
191
192 #define MINI_OP(a,b,dest,src1,src2) ((src2) != NONE ? 2 : ((src1) != NONE ? 1 : 0)),
193 #define MINI_OP3(a,b,dest,src1,src2,src3) ((src3) != NONE ? 3 : ((src2) != NONE ? 2 : ((src1) != NONE ? 1 : 0))),
194 /* 
195  * This should contain the index of the last sreg + 1. This is not the same
196  * as the number of sregs for opcodes like IA64_CMP_EQ_IMM.
197  */
198 const gint8 ins_sreg_counts[] = {
199 #include "mini-ops.h"
200 };
201 #undef MINI_OP
202 #undef MINI_OP3
203
204 guint32
205 mono_alloc_ireg (MonoCompile *cfg)
206 {
207         return alloc_ireg (cfg);
208 }
209
210 guint32
211 mono_alloc_lreg (MonoCompile *cfg)
212 {
213         return alloc_lreg (cfg);
214 }
215
216 guint32
217 mono_alloc_freg (MonoCompile *cfg)
218 {
219         return alloc_freg (cfg);
220 }
221
222 guint32
223 mono_alloc_preg (MonoCompile *cfg)
224 {
225         return alloc_preg (cfg);
226 }
227
228 guint32
229 mono_alloc_dreg (MonoCompile *cfg, MonoStackType stack_type)
230 {
231         return alloc_dreg (cfg, stack_type);
232 }
233
234 /*
235  * mono_alloc_ireg_ref:
236  *
237  *   Allocate an IREG, and mark it as holding a GC ref.
238  */
239 guint32
240 mono_alloc_ireg_ref (MonoCompile *cfg)
241 {
242         return alloc_ireg_ref (cfg);
243 }
244
245 /*
246  * mono_alloc_ireg_mp:
247  *
248  *   Allocate an IREG, and mark it as holding a managed pointer.
249  */
250 guint32
251 mono_alloc_ireg_mp (MonoCompile *cfg)
252 {
253         return alloc_ireg_mp (cfg);
254 }
255
256 /*
257  * mono_alloc_ireg_copy:
258  *
259  *   Allocate an IREG with the same GC type as VREG.
260  */
261 guint32
262 mono_alloc_ireg_copy (MonoCompile *cfg, guint32 vreg)
263 {
264         if (vreg_is_ref (cfg, vreg))
265                 return alloc_ireg_ref (cfg);
266         else if (vreg_is_mp (cfg, vreg))
267                 return alloc_ireg_mp (cfg);
268         else
269                 return alloc_ireg (cfg);
270 }
271
272 guint
273 mono_type_to_regmove (MonoCompile *cfg, MonoType *type)
274 {
275         if (type->byref)
276                 return OP_MOVE;
277
278         type = mini_get_underlying_type (type);
279 handle_enum:
280         switch (type->type) {
281         case MONO_TYPE_I1:
282         case MONO_TYPE_U1:
283                 return OP_MOVE;
284         case MONO_TYPE_I2:
285         case MONO_TYPE_U2:
286                 return OP_MOVE;
287         case MONO_TYPE_I4:
288         case MONO_TYPE_U4:
289                 return OP_MOVE;
290         case MONO_TYPE_I:
291         case MONO_TYPE_U:
292         case MONO_TYPE_PTR:
293         case MONO_TYPE_FNPTR:
294                 return OP_MOVE;
295         case MONO_TYPE_CLASS:
296         case MONO_TYPE_STRING:
297         case MONO_TYPE_OBJECT:
298         case MONO_TYPE_SZARRAY:
299         case MONO_TYPE_ARRAY:    
300                 return OP_MOVE;
301         case MONO_TYPE_I8:
302         case MONO_TYPE_U8:
303 #if SIZEOF_REGISTER == 8
304                 return OP_MOVE;
305 #else
306                 return OP_LMOVE;
307 #endif
308         case MONO_TYPE_R4:
309                 return cfg->r4fp ? OP_RMOVE : OP_FMOVE;
310         case MONO_TYPE_R8:
311                 return OP_FMOVE;
312         case MONO_TYPE_VALUETYPE:
313                 if (type->data.klass->enumtype) {
314                         type = mono_class_enum_basetype (type->data.klass);
315                         goto handle_enum;
316                 }
317                 if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type (type)))
318                         return OP_XMOVE;
319                 return OP_VMOVE;
320         case MONO_TYPE_TYPEDBYREF:
321                 return OP_VMOVE;
322         case MONO_TYPE_GENERICINST:
323                 if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type (type)))
324                         return OP_XMOVE;
325                 type = &type->data.generic_class->container_class->byval_arg;
326                 goto handle_enum;
327         case MONO_TYPE_VAR:
328         case MONO_TYPE_MVAR:
329                 g_assert (cfg->gshared);
330                 if (mini_type_var_is_vt (type))
331                         return OP_VMOVE;
332                 else
333                         return mono_type_to_regmove (cfg, mini_get_underlying_type (type));
334         default:
335                 g_error ("unknown type 0x%02x in type_to_regstore", type->type);
336         }
337         return -1;
338 }
339
340 void
341 mono_print_bb (MonoBasicBlock *bb, const char *msg)
342 {
343         int i;
344         MonoInst *tree;
345         GString *str = g_string_new ("");
346
347         g_string_append_printf (str, "%s %d: [IN: ", msg, bb->block_num);
348         for (i = 0; i < bb->in_count; ++i)
349                 g_string_append_printf (str, " BB%d(%d)", bb->in_bb [i]->block_num, bb->in_bb [i]->dfn);
350         g_string_append_printf (str, ", OUT: ");
351         for (i = 0; i < bb->out_count; ++i)
352                 g_string_append_printf (str, " BB%d(%d)", bb->out_bb [i]->block_num, bb->out_bb [i]->dfn);
353         g_string_append_printf (str, " ]\n");
354
355         g_print ("%s", str->str);
356         g_string_free (str, TRUE);
357
358         for (tree = bb->code; tree; tree = tree->next)
359                 mono_print_ins_index (-1, tree);
360 }
361
362 void
363 mono_create_helper_signatures (void)
364 {
365         helper_sig_domain_get = mono_create_icall_signature ("ptr");
366         helper_sig_rgctx_lazy_fetch_trampoline = mono_create_icall_signature ("ptr ptr");
367         helper_sig_llvmonly_imt_trampoline = mono_create_icall_signature ("ptr ptr ptr");
368         helper_sig_jit_thread_attach = mono_create_icall_signature ("ptr ptr");
369         helper_sig_get_tls_tramp = mono_create_icall_signature ("ptr");
370         helper_sig_set_tls_tramp = mono_create_icall_signature ("void ptr");
371 }
372
373 static MONO_NEVER_INLINE void
374 break_on_unverified (void)
375 {
376         if (mini_get_debug_options ()->break_on_unverified)
377                 G_BREAKPOINT ();
378 }
379
380 static MONO_NEVER_INLINE void
381 field_access_failure (MonoCompile *cfg, MonoMethod *method, MonoClassField *field)
382 {
383         char *method_fname = mono_method_full_name (method, TRUE);
384         char *field_fname = mono_field_full_name (field);
385         mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
386         mono_error_set_generic_error (&cfg->error, "System", "FieldAccessException", "Field `%s' is inaccessible from method `%s'\n", field_fname, method_fname);
387         g_free (method_fname);
388         g_free (field_fname);
389 }
390
391 static MONO_NEVER_INLINE void
392 inline_failure (MonoCompile *cfg, const char *msg)
393 {
394         if (cfg->verbose_level >= 2)
395                 printf ("inline failed: %s\n", msg);
396         mono_cfg_set_exception (cfg, MONO_EXCEPTION_INLINE_FAILED);
397 }
398
399 static MONO_NEVER_INLINE void
400 gshared_failure (MonoCompile *cfg, int opcode, const char *file, int line)
401 {
402         if (cfg->verbose_level > 2)                                                                                     \
403                 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);
404         mono_cfg_set_exception (cfg, MONO_EXCEPTION_GENERIC_SHARING_FAILED);
405 }
406
407 static MONO_NEVER_INLINE void
408 gsharedvt_failure (MonoCompile *cfg, int opcode, const char *file, int line)
409 {
410         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);
411         if (cfg->verbose_level >= 2)
412                 printf ("%s\n", cfg->exception_message);
413         mono_cfg_set_exception (cfg, MONO_EXCEPTION_GENERIC_SHARING_FAILED);
414 }
415
416 /*
417  * When using gsharedvt, some instatiations might be verifiable, and some might be not. i.e. 
418  * foo<T> (int i) { ldarg.0; box T; }
419  */
420 #define UNVERIFIED do { \
421         if (cfg->gsharedvt) { \
422                 if (cfg->verbose_level > 2)                                                                     \
423                         printf ("gsharedvt method failed to verify, falling back to instantiation.\n"); \
424                 mono_cfg_set_exception (cfg, MONO_EXCEPTION_GENERIC_SHARING_FAILED); \
425                 goto exception_exit;                                                                                    \
426         }                                                                                                                                       \
427         break_on_unverified ();                                                                                         \
428         goto unverified;                                                                                                        \
429 } while (0)
430
431 #define GET_BBLOCK(cfg,tblock,ip) do {  \
432                 (tblock) = cfg->cil_offset_to_bb [(ip) - cfg->cil_start]; \
433                 if (!(tblock)) {        \
434                         if ((ip) >= end || (ip) < header->code) UNVERIFIED; \
435             NEW_BBLOCK (cfg, (tblock)); \
436                         (tblock)->cil_code = (ip);      \
437                         ADD_BBLOCK (cfg, (tblock));     \
438                 } \
439         } while (0)
440
441 #if defined(TARGET_X86) || defined(TARGET_AMD64)
442 #define EMIT_NEW_X86_LEA(cfg,dest,sr1,sr2,shift,imm) do { \
443                 MONO_INST_NEW (cfg, dest, OP_X86_LEA); \
444                 (dest)->dreg = alloc_ireg_mp ((cfg)); \
445                 (dest)->sreg1 = (sr1); \
446                 (dest)->sreg2 = (sr2); \
447                 (dest)->inst_imm = (imm); \
448                 (dest)->backend.shift_amount = (shift); \
449                 MONO_ADD_INS ((cfg)->cbb, (dest)); \
450         } while (0)
451 #endif
452
453 /* Emit conversions so both operands of a binary opcode are of the same type */
454 static void
455 add_widen_op (MonoCompile *cfg, MonoInst *ins, MonoInst **arg1_ref, MonoInst **arg2_ref)
456 {
457         MonoInst *arg1 = *arg1_ref;
458         MonoInst *arg2 = *arg2_ref;
459
460         if (cfg->r4fp &&
461                 ((arg1->type == STACK_R4 && arg2->type == STACK_R8) ||
462                  (arg1->type == STACK_R8 && arg2->type == STACK_R4))) {
463                 MonoInst *conv;
464
465                 /* Mixing r4/r8 is allowed by the spec */
466                 if (arg1->type == STACK_R4) {
467                         int dreg = alloc_freg (cfg);
468
469                         EMIT_NEW_UNALU (cfg, conv, OP_RCONV_TO_R8, dreg, arg1->dreg);
470                         conv->type = STACK_R8;
471                         ins->sreg1 = dreg;
472                         *arg1_ref = conv;
473                 }
474                 if (arg2->type == STACK_R4) {
475                         int dreg = alloc_freg (cfg);
476
477                         EMIT_NEW_UNALU (cfg, conv, OP_RCONV_TO_R8, dreg, arg2->dreg);
478                         conv->type = STACK_R8;
479                         ins->sreg2 = dreg;
480                         *arg2_ref = conv;
481                 }
482         }
483
484 #if SIZEOF_REGISTER == 8
485         /* FIXME: Need to add many more cases */
486         if ((arg1)->type == STACK_PTR && (arg2)->type == STACK_I4) {
487                 MonoInst *widen;
488
489                 int dr = alloc_preg (cfg);
490                 EMIT_NEW_UNALU (cfg, widen, OP_SEXT_I4, dr, (arg2)->dreg);
491                 (ins)->sreg2 = widen->dreg;
492         }
493 #endif
494 }
495
496 #define ADD_BINOP(op) do {      \
497                 MONO_INST_NEW (cfg, ins, (op)); \
498                 sp -= 2;        \
499                 ins->sreg1 = sp [0]->dreg;      \
500                 ins->sreg2 = sp [1]->dreg;      \
501                 type_from_op (cfg, ins, sp [0], sp [1]);        \
502                 CHECK_TYPE (ins);       \
503                 /* Have to insert a widening op */               \
504         add_widen_op (cfg, ins, &sp [0], &sp [1]);               \
505         ins->dreg = alloc_dreg ((cfg), (MonoStackType)(ins)->type); \
506         MONO_ADD_INS ((cfg)->cbb, (ins)); \
507         *sp++ = mono_decompose_opcode ((cfg), (ins));   \
508         } while (0)
509
510 #define ADD_UNOP(op) do {       \
511                 MONO_INST_NEW (cfg, ins, (op)); \
512                 sp--;   \
513                 ins->sreg1 = sp [0]->dreg;      \
514                 type_from_op (cfg, ins, sp [0], NULL);  \
515                 CHECK_TYPE (ins);       \
516         (ins)->dreg = alloc_dreg ((cfg), (MonoStackType)(ins)->type); \
517         MONO_ADD_INS ((cfg)->cbb, (ins)); \
518                 *sp++ = mono_decompose_opcode (cfg, ins);       \
519         } while (0)
520
521 #define ADD_BINCOND(next_block) do {    \
522                 MonoInst *cmp;  \
523                 sp -= 2; \
524                 MONO_INST_NEW(cfg, cmp, OP_COMPARE);    \
525                 cmp->sreg1 = sp [0]->dreg;      \
526                 cmp->sreg2 = sp [1]->dreg;      \
527                 type_from_op (cfg, cmp, sp [0], sp [1]);        \
528                 CHECK_TYPE (cmp);       \
529                 add_widen_op (cfg, cmp, &sp [0], &sp [1]);                                              \
530                 type_from_op (cfg, ins, sp [0], sp [1]);                                                        \
531                 ins->inst_many_bb = (MonoBasicBlock **)mono_mempool_alloc (cfg->mempool, sizeof(gpointer)*2);   \
532                 GET_BBLOCK (cfg, tblock, target);               \
533                 link_bblock (cfg, cfg->cbb, tblock);    \
534                 ins->inst_true_bb = tblock;     \
535                 if ((next_block)) {     \
536                         link_bblock (cfg, cfg->cbb, (next_block));      \
537                         ins->inst_false_bb = (next_block);      \
538                         start_new_bblock = 1;   \
539                 } else {        \
540                         GET_BBLOCK (cfg, tblock, ip);           \
541                         link_bblock (cfg, cfg->cbb, tblock);    \
542                         ins->inst_false_bb = tblock;    \
543                         start_new_bblock = 2;   \
544                 }       \
545                 if (sp != stack_start) {                                                                        \
546                     handle_stack_args (cfg, stack_start, sp - stack_start); \
547                         CHECK_UNVERIFIABLE (cfg); \
548                 } \
549         MONO_ADD_INS (cfg->cbb, cmp); \
550                 MONO_ADD_INS (cfg->cbb, ins);   \
551         } while (0)
552
553 /* *
554  * link_bblock: Links two basic blocks
555  *
556  * links two basic blocks in the control flow graph, the 'from'
557  * argument is the starting block and the 'to' argument is the block
558  * the control flow ends to after 'from'.
559  */
560 static void
561 link_bblock (MonoCompile *cfg, MonoBasicBlock *from, MonoBasicBlock* to)
562 {
563         MonoBasicBlock **newa;
564         int i, found;
565
566 #if 0
567         if (from->cil_code) {
568                 if (to->cil_code)
569                         printf ("edge from IL%04x to IL_%04x\n", from->cil_code - cfg->cil_code, to->cil_code - cfg->cil_code);
570                 else
571                         printf ("edge from IL%04x to exit\n", from->cil_code - cfg->cil_code);
572         } else {
573                 if (to->cil_code)
574                         printf ("edge from entry to IL_%04x\n", to->cil_code - cfg->cil_code);
575                 else
576                         printf ("edge from entry to exit\n");
577         }
578 #endif
579
580         found = FALSE;
581         for (i = 0; i < from->out_count; ++i) {
582                 if (to == from->out_bb [i]) {
583                         found = TRUE;
584                         break;
585                 }
586         }
587         if (!found) {
588                 newa = (MonoBasicBlock **)mono_mempool_alloc (cfg->mempool, sizeof (gpointer) * (from->out_count + 1));
589                 for (i = 0; i < from->out_count; ++i) {
590                         newa [i] = from->out_bb [i];
591                 }
592                 newa [i] = to;
593                 from->out_count++;
594                 from->out_bb = newa;
595         }
596
597         found = FALSE;
598         for (i = 0; i < to->in_count; ++i) {
599                 if (from == to->in_bb [i]) {
600                         found = TRUE;
601                         break;
602                 }
603         }
604         if (!found) {
605                 newa = (MonoBasicBlock **)mono_mempool_alloc (cfg->mempool, sizeof (gpointer) * (to->in_count + 1));
606                 for (i = 0; i < to->in_count; ++i) {
607                         newa [i] = to->in_bb [i];
608                 }
609                 newa [i] = from;
610                 to->in_count++;
611                 to->in_bb = newa;
612         }
613 }
614
615 void
616 mono_link_bblock (MonoCompile *cfg, MonoBasicBlock *from, MonoBasicBlock* to)
617 {
618         link_bblock (cfg, from, to);
619 }
620
621 /**
622  * mono_find_block_region:
623  *
624  *   We mark each basic block with a region ID. We use that to avoid BB
625  *   optimizations when blocks are in different regions.
626  *
627  * Returns:
628  *   A region token that encodes where this region is, and information
629  *   about the clause owner for this block.
630  *
631  *   The region encodes the try/catch/filter clause that owns this block
632  *   as well as the type.  -1 is a special value that represents a block
633  *   that is in none of try/catch/filter.
634  */
635 static int
636 mono_find_block_region (MonoCompile *cfg, int offset)
637 {
638         MonoMethodHeader *header = cfg->header;
639         MonoExceptionClause *clause;
640         int i;
641
642         for (i = 0; i < header->num_clauses; ++i) {
643                 clause = &header->clauses [i];
644                 if ((clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) && (offset >= clause->data.filter_offset) &&
645                     (offset < (clause->handler_offset)))
646                         return ((i + 1) << 8) | MONO_REGION_FILTER | clause->flags;
647                            
648                 if (MONO_OFFSET_IN_HANDLER (clause, offset)) {
649                         if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
650                                 return ((i + 1) << 8) | MONO_REGION_FINALLY | clause->flags;
651                         else if (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT)
652                                 return ((i + 1) << 8) | MONO_REGION_FAULT | clause->flags;
653                         else
654                                 return ((i + 1) << 8) | MONO_REGION_CATCH | clause->flags;
655                 }
656         }
657         for (i = 0; i < header->num_clauses; ++i) {
658                 clause = &header->clauses [i];
659
660                 if (MONO_OFFSET_IN_CLAUSE (clause, offset))
661                         return ((i + 1) << 8) | clause->flags;
662         }
663
664         return -1;
665 }
666
667 static gboolean
668 ip_in_finally_clause (MonoCompile *cfg, int offset)
669 {
670         MonoMethodHeader *header = cfg->header;
671         MonoExceptionClause *clause;
672         int i;
673
674         for (i = 0; i < header->num_clauses; ++i) {
675                 clause = &header->clauses [i];
676                 if (clause->flags != MONO_EXCEPTION_CLAUSE_FINALLY && clause->flags != MONO_EXCEPTION_CLAUSE_FAULT)
677                         continue;
678
679                 if (MONO_OFFSET_IN_HANDLER (clause, offset))
680                         return TRUE;
681         }
682         return FALSE;
683 }
684
685 static GList*
686 mono_find_final_block (MonoCompile *cfg, unsigned char *ip, unsigned char *target, int type)
687 {
688         MonoMethodHeader *header = cfg->header;
689         MonoExceptionClause *clause;
690         int i;
691         GList *res = NULL;
692
693         for (i = 0; i < header->num_clauses; ++i) {
694                 clause = &header->clauses [i];
695                 if (MONO_OFFSET_IN_CLAUSE (clause, (ip - header->code)) && 
696                     (!MONO_OFFSET_IN_CLAUSE (clause, (target - header->code)))) {
697                         if (clause->flags == type)
698                                 res = g_list_append (res, clause);
699                 }
700         }
701         return res;
702 }
703
704 static void
705 mono_create_spvar_for_region (MonoCompile *cfg, int region)
706 {
707         MonoInst *var;
708
709         var = (MonoInst *)g_hash_table_lookup (cfg->spvars, GINT_TO_POINTER (region));
710         if (var)
711                 return;
712
713         var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
714         /* prevent it from being register allocated */
715         var->flags |= MONO_INST_VOLATILE;
716
717         g_hash_table_insert (cfg->spvars, GINT_TO_POINTER (region), var);
718 }
719
720 MonoInst *
721 mono_find_exvar_for_offset (MonoCompile *cfg, int offset)
722 {
723         return (MonoInst *)g_hash_table_lookup (cfg->exvars, GINT_TO_POINTER (offset));
724 }
725
726 static MonoInst*
727 mono_create_exvar_for_offset (MonoCompile *cfg, int offset)
728 {
729         MonoInst *var;
730
731         var = (MonoInst *)g_hash_table_lookup (cfg->exvars, GINT_TO_POINTER (offset));
732         if (var)
733                 return var;
734
735         var = mono_compile_create_var (cfg, &mono_defaults.object_class->byval_arg, OP_LOCAL);
736         /* prevent it from being register allocated */
737         var->flags |= MONO_INST_VOLATILE;
738
739         g_hash_table_insert (cfg->exvars, GINT_TO_POINTER (offset), var);
740
741         return var;
742 }
743
744 /*
745  * Returns the type used in the eval stack when @type is loaded.
746  * FIXME: return a MonoType/MonoClass for the byref and VALUETYPE cases.
747  */
748 void
749 type_to_eval_stack_type (MonoCompile *cfg, MonoType *type, MonoInst *inst)
750 {
751         MonoClass *klass;
752
753         type = mini_get_underlying_type (type);
754         inst->klass = klass = mono_class_from_mono_type (type);
755         if (type->byref) {
756                 inst->type = STACK_MP;
757                 return;
758         }
759
760 handle_enum:
761         switch (type->type) {
762         case MONO_TYPE_VOID:
763                 inst->type = STACK_INV;
764                 return;
765         case MONO_TYPE_I1:
766         case MONO_TYPE_U1:
767         case MONO_TYPE_I2:
768         case MONO_TYPE_U2:
769         case MONO_TYPE_I4:
770         case MONO_TYPE_U4:
771                 inst->type = STACK_I4;
772                 return;
773         case MONO_TYPE_I:
774         case MONO_TYPE_U:
775         case MONO_TYPE_PTR:
776         case MONO_TYPE_FNPTR:
777                 inst->type = STACK_PTR;
778                 return;
779         case MONO_TYPE_CLASS:
780         case MONO_TYPE_STRING:
781         case MONO_TYPE_OBJECT:
782         case MONO_TYPE_SZARRAY:
783         case MONO_TYPE_ARRAY:    
784                 inst->type = STACK_OBJ;
785                 return;
786         case MONO_TYPE_I8:
787         case MONO_TYPE_U8:
788                 inst->type = STACK_I8;
789                 return;
790         case MONO_TYPE_R4:
791                 inst->type = cfg->r4_stack_type;
792                 break;
793         case MONO_TYPE_R8:
794                 inst->type = STACK_R8;
795                 return;
796         case MONO_TYPE_VALUETYPE:
797                 if (type->data.klass->enumtype) {
798                         type = mono_class_enum_basetype (type->data.klass);
799                         goto handle_enum;
800                 } else {
801                         inst->klass = klass;
802                         inst->type = STACK_VTYPE;
803                         return;
804                 }
805         case MONO_TYPE_TYPEDBYREF:
806                 inst->klass = mono_defaults.typed_reference_class;
807                 inst->type = STACK_VTYPE;
808                 return;
809         case MONO_TYPE_GENERICINST:
810                 type = &type->data.generic_class->container_class->byval_arg;
811                 goto handle_enum;
812         case MONO_TYPE_VAR:
813         case MONO_TYPE_MVAR:
814                 g_assert (cfg->gshared);
815                 if (mini_is_gsharedvt_type (type)) {
816                         g_assert (cfg->gsharedvt);
817                         inst->type = STACK_VTYPE;
818                 } else {
819                         type_to_eval_stack_type (cfg, mini_get_underlying_type (type), inst);
820                 }
821                 return;
822         default:
823                 g_error ("unknown type 0x%02x in eval stack type", type->type);
824         }
825 }
826
827 /*
828  * The following tables are used to quickly validate the IL code in type_from_op ().
829  */
830 static const char
831 bin_num_table [STACK_MAX] [STACK_MAX] = {
832         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
833         {STACK_INV, STACK_I4,  STACK_INV, STACK_PTR, STACK_INV, STACK_MP,  STACK_INV, STACK_INV},
834         {STACK_INV, STACK_INV, STACK_I8,  STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
835         {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_MP,  STACK_INV, STACK_INV},
836         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_R8,  STACK_INV, STACK_INV, STACK_INV, STACK_R8},
837         {STACK_INV, STACK_MP,  STACK_INV, STACK_MP,  STACK_INV, STACK_PTR, STACK_INV, STACK_INV},
838         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, 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_R8, STACK_INV, STACK_INV, STACK_INV, STACK_R4}
841 };
842
843 static const char 
844 neg_table [] = {
845         STACK_INV, STACK_I4, STACK_I8, STACK_PTR, STACK_R8, STACK_INV, STACK_INV, STACK_INV, STACK_R4
846 };
847
848 /* reduce the size of this table */
849 static const char
850 bin_int_table [STACK_MAX] [STACK_MAX] = {
851         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
852         {STACK_INV, STACK_I4,  STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
853         {STACK_INV, STACK_INV, STACK_I8,  STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
854         {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
855         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, 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 };
860
861 static const char
862 bin_comp_table [STACK_MAX] [STACK_MAX] = {
863 /*      Inv i  L  p  F  &  O  vt r4 */
864         {0},
865         {0, 1, 0, 1, 0, 0, 0, 0}, /* i, int32 */
866         {0, 0, 1, 0, 0, 0, 0, 0}, /* L, int64 */
867         {0, 1, 0, 1, 0, 2, 4, 0}, /* p, ptr */
868         {0, 0, 0, 0, 1, 0, 0, 0, 1}, /* F, R8 */
869         {0, 0, 0, 2, 0, 1, 0, 0}, /* &, managed pointer */
870         {0, 0, 0, 4, 0, 0, 3, 0}, /* O, reference */
871         {0, 0, 0, 0, 0, 0, 0, 0}, /* vt value type */
872         {0, 0, 0, 0, 1, 0, 0, 0, 1}, /* r, r4 */
873 };
874
875 /* reduce the size of this table */
876 static const char
877 shift_table [STACK_MAX] [STACK_MAX] = {
878         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
879         {STACK_INV, STACK_I4,  STACK_INV, STACK_I4,  STACK_INV, STACK_INV, STACK_INV, STACK_INV},
880         {STACK_INV, STACK_I8,  STACK_INV, STACK_I8,  STACK_INV, STACK_INV, STACK_INV, STACK_INV},
881         {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
882         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, 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 };
887
888 /*
889  * Tables to map from the non-specific opcode to the matching
890  * type-specific opcode.
891  */
892 /* handles from CEE_ADD to CEE_SHR_UN (CEE_REM_UN for floats) */
893 static const guint16
894 binops_op_map [STACK_MAX] = {
895         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
896 };
897
898 /* handles from CEE_NEG to CEE_CONV_U8 */
899 static const guint16
900 unops_op_map [STACK_MAX] = {
901         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
902 };
903
904 /* handles from CEE_CONV_U2 to CEE_SUB_OVF_UN */
905 static const guint16
906 ovfops_op_map [STACK_MAX] = {
907         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
908 };
909
910 /* handles from CEE_CONV_OVF_I1_UN to CEE_CONV_OVF_U_UN */
911 static const guint16
912 ovf2ops_op_map [STACK_MAX] = {
913         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
914 };
915
916 /* handles from CEE_CONV_OVF_I1 to CEE_CONV_OVF_U8 */
917 static const guint16
918 ovf3ops_op_map [STACK_MAX] = {
919         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
920 };
921
922 /* handles from CEE_BEQ to CEE_BLT_UN */
923 static const guint16
924 beqops_op_map [STACK_MAX] = {
925         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
926 };
927
928 /* handles from CEE_CEQ to CEE_CLT_UN */
929 static const guint16
930 ceqops_op_map [STACK_MAX] = {
931         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
932 };
933
934 /*
935  * Sets ins->type (the type on the eval stack) according to the
936  * type of the opcode and the arguments to it.
937  * Invalid IL code is marked by setting ins->type to the invalid value STACK_INV.
938  *
939  * FIXME: this function sets ins->type unconditionally in some cases, but
940  * it should set it to invalid for some types (a conv.x on an object)
941  */
942 static void
943 type_from_op (MonoCompile *cfg, MonoInst *ins, MonoInst *src1, MonoInst *src2)
944 {
945         switch (ins->opcode) {
946         /* binops */
947         case CEE_ADD:
948         case CEE_SUB:
949         case CEE_MUL:
950         case CEE_DIV:
951         case CEE_REM:
952                 /* FIXME: check unverifiable args for STACK_MP */
953                 ins->type = bin_num_table [src1->type] [src2->type];
954                 ins->opcode += binops_op_map [ins->type];
955                 break;
956         case CEE_DIV_UN:
957         case CEE_REM_UN:
958         case CEE_AND:
959         case CEE_OR:
960         case CEE_XOR:
961                 ins->type = bin_int_table [src1->type] [src2->type];
962                 ins->opcode += binops_op_map [ins->type];
963                 break;
964         case CEE_SHL:
965         case CEE_SHR:
966         case CEE_SHR_UN:
967                 ins->type = shift_table [src1->type] [src2->type];
968                 ins->opcode += binops_op_map [ins->type];
969                 break;
970         case OP_COMPARE:
971         case OP_LCOMPARE:
972         case OP_ICOMPARE:
973                 ins->type = bin_comp_table [src1->type] [src2->type] ? STACK_I4: STACK_INV;
974                 if ((src1->type == STACK_I8) || ((SIZEOF_VOID_P == 8) && ((src1->type == STACK_PTR) || (src1->type == STACK_OBJ) || (src1->type == STACK_MP))))
975                         ins->opcode = OP_LCOMPARE;
976                 else if (src1->type == STACK_R4)
977                         ins->opcode = OP_RCOMPARE;
978                 else if (src1->type == STACK_R8)
979                         ins->opcode = OP_FCOMPARE;
980                 else
981                         ins->opcode = OP_ICOMPARE;
982                 break;
983         case OP_ICOMPARE_IMM:
984                 ins->type = bin_comp_table [src1->type] [src1->type] ? STACK_I4 : STACK_INV;
985                 if ((src1->type == STACK_I8) || ((SIZEOF_VOID_P == 8) && ((src1->type == STACK_PTR) || (src1->type == STACK_OBJ) || (src1->type == STACK_MP))))
986                         ins->opcode = OP_LCOMPARE_IMM;          
987                 break;
988         case CEE_BEQ:
989         case CEE_BGE:
990         case CEE_BGT:
991         case CEE_BLE:
992         case CEE_BLT:
993         case CEE_BNE_UN:
994         case CEE_BGE_UN:
995         case CEE_BGT_UN:
996         case CEE_BLE_UN:
997         case CEE_BLT_UN:
998                 ins->opcode += beqops_op_map [src1->type];
999                 break;
1000         case OP_CEQ:
1001                 ins->type = bin_comp_table [src1->type] [src2->type] ? STACK_I4: STACK_INV;
1002                 ins->opcode += ceqops_op_map [src1->type];
1003                 break;
1004         case OP_CGT:
1005         case OP_CGT_UN:
1006         case OP_CLT:
1007         case OP_CLT_UN:
1008                 ins->type = (bin_comp_table [src1->type] [src2->type] & 1) ? STACK_I4: STACK_INV;
1009                 ins->opcode += ceqops_op_map [src1->type];
1010                 break;
1011         /* unops */
1012         case CEE_NEG:
1013                 ins->type = neg_table [src1->type];
1014                 ins->opcode += unops_op_map [ins->type];
1015                 break;
1016         case CEE_NOT:
1017                 if (src1->type >= STACK_I4 && src1->type <= STACK_PTR)
1018                         ins->type = src1->type;
1019                 else
1020                         ins->type = STACK_INV;
1021                 ins->opcode += unops_op_map [ins->type];
1022                 break;
1023         case CEE_CONV_I1:
1024         case CEE_CONV_I2:
1025         case CEE_CONV_I4:
1026         case CEE_CONV_U4:
1027                 ins->type = STACK_I4;
1028                 ins->opcode += unops_op_map [src1->type];
1029                 break;
1030         case CEE_CONV_R_UN:
1031                 ins->type = STACK_R8;
1032                 switch (src1->type) {
1033                 case STACK_I4:
1034                 case STACK_PTR:
1035                         ins->opcode = OP_ICONV_TO_R_UN;
1036                         break;
1037                 case STACK_I8:
1038                         ins->opcode = OP_LCONV_TO_R_UN; 
1039                         break;
1040                 }
1041                 break;
1042         case CEE_CONV_OVF_I1:
1043         case CEE_CONV_OVF_U1:
1044         case CEE_CONV_OVF_I2:
1045         case CEE_CONV_OVF_U2:
1046         case CEE_CONV_OVF_I4:
1047         case CEE_CONV_OVF_U4:
1048                 ins->type = STACK_I4;
1049                 ins->opcode += ovf3ops_op_map [src1->type];
1050                 break;
1051         case CEE_CONV_OVF_I_UN:
1052         case CEE_CONV_OVF_U_UN:
1053                 ins->type = STACK_PTR;
1054                 ins->opcode += ovf2ops_op_map [src1->type];
1055                 break;
1056         case CEE_CONV_OVF_I1_UN:
1057         case CEE_CONV_OVF_I2_UN:
1058         case CEE_CONV_OVF_I4_UN:
1059         case CEE_CONV_OVF_U1_UN:
1060         case CEE_CONV_OVF_U2_UN:
1061         case CEE_CONV_OVF_U4_UN:
1062                 ins->type = STACK_I4;
1063                 ins->opcode += ovf2ops_op_map [src1->type];
1064                 break;
1065         case CEE_CONV_U:
1066                 ins->type = STACK_PTR;
1067                 switch (src1->type) {
1068                 case STACK_I4:
1069                         ins->opcode = OP_ICONV_TO_U;
1070                         break;
1071                 case STACK_PTR:
1072                 case STACK_MP:
1073 #if SIZEOF_VOID_P == 8
1074                         ins->opcode = OP_LCONV_TO_U;
1075 #else
1076                         ins->opcode = OP_MOVE;
1077 #endif
1078                         break;
1079                 case STACK_I8:
1080                         ins->opcode = OP_LCONV_TO_U;
1081                         break;
1082                 case STACK_R8:
1083                         ins->opcode = OP_FCONV_TO_U;
1084                         break;
1085                 }
1086                 break;
1087         case CEE_CONV_I8:
1088         case CEE_CONV_U8:
1089                 ins->type = STACK_I8;
1090                 ins->opcode += unops_op_map [src1->type];
1091                 break;
1092         case CEE_CONV_OVF_I8:
1093         case CEE_CONV_OVF_U8:
1094                 ins->type = STACK_I8;
1095                 ins->opcode += ovf3ops_op_map [src1->type];
1096                 break;
1097         case CEE_CONV_OVF_U8_UN:
1098         case CEE_CONV_OVF_I8_UN:
1099                 ins->type = STACK_I8;
1100                 ins->opcode += ovf2ops_op_map [src1->type];
1101                 break;
1102         case CEE_CONV_R4:
1103                 ins->type = cfg->r4_stack_type;
1104                 ins->opcode += unops_op_map [src1->type];
1105                 break;
1106         case CEE_CONV_R8:
1107                 ins->type = STACK_R8;
1108                 ins->opcode += unops_op_map [src1->type];
1109                 break;
1110         case OP_CKFINITE:
1111                 ins->type = STACK_R8;           
1112                 break;
1113         case CEE_CONV_U2:
1114         case CEE_CONV_U1:
1115                 ins->type = STACK_I4;
1116                 ins->opcode += ovfops_op_map [src1->type];
1117                 break;
1118         case CEE_CONV_I:
1119         case CEE_CONV_OVF_I:
1120         case CEE_CONV_OVF_U:
1121                 ins->type = STACK_PTR;
1122                 ins->opcode += ovfops_op_map [src1->type];
1123                 break;
1124         case CEE_ADD_OVF:
1125         case CEE_ADD_OVF_UN:
1126         case CEE_MUL_OVF:
1127         case CEE_MUL_OVF_UN:
1128         case CEE_SUB_OVF:
1129         case CEE_SUB_OVF_UN:
1130                 ins->type = bin_num_table [src1->type] [src2->type];
1131                 ins->opcode += ovfops_op_map [src1->type];
1132                 if (ins->type == STACK_R8)
1133                         ins->type = STACK_INV;
1134                 break;
1135         case OP_LOAD_MEMBASE:
1136                 ins->type = STACK_PTR;
1137                 break;
1138         case OP_LOADI1_MEMBASE:
1139         case OP_LOADU1_MEMBASE:
1140         case OP_LOADI2_MEMBASE:
1141         case OP_LOADU2_MEMBASE:
1142         case OP_LOADI4_MEMBASE:
1143         case OP_LOADU4_MEMBASE:
1144                 ins->type = STACK_PTR;
1145                 break;
1146         case OP_LOADI8_MEMBASE:
1147                 ins->type = STACK_I8;
1148                 break;
1149         case OP_LOADR4_MEMBASE:
1150                 ins->type = cfg->r4_stack_type;
1151                 break;
1152         case OP_LOADR8_MEMBASE:
1153                 ins->type = STACK_R8;
1154                 break;
1155         default:
1156                 g_error ("opcode 0x%04x not handled in type from op", ins->opcode);
1157                 break;
1158         }
1159
1160         if (ins->type == STACK_MP)
1161                 ins->klass = mono_defaults.object_class;
1162 }
1163
1164 static MonoClass*
1165 ldind_to_type (int op)
1166 {
1167         switch (op) {
1168         case CEE_LDIND_I1: return mono_defaults.sbyte_class;
1169         case CEE_LDIND_U1: return mono_defaults.byte_class;
1170         case CEE_LDIND_I2: return mono_defaults.int16_class;
1171         case CEE_LDIND_U2: return mono_defaults.uint16_class;
1172         case CEE_LDIND_I4: return mono_defaults.int32_class;
1173         case CEE_LDIND_U4: return mono_defaults.uint32_class;
1174         case CEE_LDIND_I8: return mono_defaults.int64_class;
1175         case CEE_LDIND_I: return mono_defaults.int_class;
1176         case CEE_LDIND_R4: return mono_defaults.single_class;
1177         case CEE_LDIND_R8: return mono_defaults.double_class;
1178         case CEE_LDIND_REF:return mono_defaults.object_class; //FIXME we should try to return a more specific type
1179         default: g_error ("Unknown ldind type %d", op);
1180         }
1181 }
1182
1183 #if 0
1184
1185 static const char
1186 param_table [STACK_MAX] [STACK_MAX] = {
1187         {0},
1188 };
1189
1190 static int
1191 check_values_to_signature (MonoInst *args, MonoType *this_ins, MonoMethodSignature *sig)
1192 {
1193         int i;
1194
1195         if (sig->hasthis) {
1196                 switch (args->type) {
1197                 case STACK_I4:
1198                 case STACK_I8:
1199                 case STACK_R8:
1200                 case STACK_VTYPE:
1201                 case STACK_INV:
1202                         return 0;
1203                 }
1204                 args++;
1205         }
1206         for (i = 0; i < sig->param_count; ++i) {
1207                 switch (args [i].type) {
1208                 case STACK_INV:
1209                         return 0;
1210                 case STACK_MP:
1211                         if (!sig->params [i]->byref)
1212                                 return 0;
1213                         continue;
1214                 case STACK_OBJ:
1215                         if (sig->params [i]->byref)
1216                                 return 0;
1217                         switch (sig->params [i]->type) {
1218                         case MONO_TYPE_CLASS:
1219                         case MONO_TYPE_STRING:
1220                         case MONO_TYPE_OBJECT:
1221                         case MONO_TYPE_SZARRAY:
1222                         case MONO_TYPE_ARRAY:
1223                                 break;
1224                         default:
1225                                 return 0;
1226                         }
1227                         continue;
1228                 case STACK_R8:
1229                         if (sig->params [i]->byref)
1230                                 return 0;
1231                         if (sig->params [i]->type != MONO_TYPE_R4 && sig->params [i]->type != MONO_TYPE_R8)
1232                                 return 0;
1233                         continue;
1234                 case STACK_PTR:
1235                 case STACK_I4:
1236                 case STACK_I8:
1237                 case STACK_VTYPE:
1238                         break;
1239                 }
1240                 /*if (!param_table [args [i].type] [sig->params [i]->type])
1241                         return 0;*/
1242         }
1243         return 1;
1244 }
1245 #endif
1246
1247 /*
1248  * When we need a pointer to the current domain many times in a method, we
1249  * call mono_domain_get() once and we store the result in a local variable.
1250  * This function returns the variable that represents the MonoDomain*.
1251  */
1252 inline static MonoInst *
1253 mono_get_domainvar (MonoCompile *cfg)
1254 {
1255         if (!cfg->domainvar)
1256                 cfg->domainvar = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1257         return cfg->domainvar;
1258 }
1259
1260 /*
1261  * The got_var contains the address of the Global Offset Table when AOT 
1262  * compiling.
1263  */
1264 MonoInst *
1265 mono_get_got_var (MonoCompile *cfg)
1266 {
1267         if (!cfg->compile_aot || !cfg->backend->need_got_var)
1268                 return NULL;
1269         if (!cfg->got_var) {
1270                 cfg->got_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1271         }
1272         return cfg->got_var;
1273 }
1274
1275 static void
1276 mono_create_rgctx_var (MonoCompile *cfg)
1277 {
1278         if (!cfg->rgctx_var) {
1279                 cfg->rgctx_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1280                 /* force the var to be stack allocated */
1281                 cfg->rgctx_var->flags |= MONO_INST_VOLATILE;
1282         }
1283 }
1284
1285 static MonoInst *
1286 mono_get_vtable_var (MonoCompile *cfg)
1287 {
1288         g_assert (cfg->gshared);
1289
1290         mono_create_rgctx_var (cfg);
1291
1292         return cfg->rgctx_var;
1293 }
1294
1295 static MonoType*
1296 type_from_stack_type (MonoInst *ins) {
1297         switch (ins->type) {
1298         case STACK_I4: return &mono_defaults.int32_class->byval_arg;
1299         case STACK_I8: return &mono_defaults.int64_class->byval_arg;
1300         case STACK_PTR: return &mono_defaults.int_class->byval_arg;
1301         case STACK_R4: return &mono_defaults.single_class->byval_arg;
1302         case STACK_R8: return &mono_defaults.double_class->byval_arg;
1303         case STACK_MP:
1304                 return &ins->klass->this_arg;
1305         case STACK_OBJ: return &mono_defaults.object_class->byval_arg;
1306         case STACK_VTYPE: return &ins->klass->byval_arg;
1307         default:
1308                 g_error ("stack type %d to monotype not handled\n", ins->type);
1309         }
1310         return NULL;
1311 }
1312
1313 static G_GNUC_UNUSED int
1314 type_to_stack_type (MonoCompile *cfg, MonoType *t)
1315 {
1316         t = mono_type_get_underlying_type (t);
1317         switch (t->type) {
1318         case MONO_TYPE_I1:
1319         case MONO_TYPE_U1:
1320         case MONO_TYPE_I2:
1321         case MONO_TYPE_U2:
1322         case MONO_TYPE_I4:
1323         case MONO_TYPE_U4:
1324                 return STACK_I4;
1325         case MONO_TYPE_I:
1326         case MONO_TYPE_U:
1327         case MONO_TYPE_PTR:
1328         case MONO_TYPE_FNPTR:
1329                 return STACK_PTR;
1330         case MONO_TYPE_CLASS:
1331         case MONO_TYPE_STRING:
1332         case MONO_TYPE_OBJECT:
1333         case MONO_TYPE_SZARRAY:
1334         case MONO_TYPE_ARRAY:    
1335                 return STACK_OBJ;
1336         case MONO_TYPE_I8:
1337         case MONO_TYPE_U8:
1338                 return STACK_I8;
1339         case MONO_TYPE_R4:
1340                 return cfg->r4_stack_type;
1341         case MONO_TYPE_R8:
1342                 return STACK_R8;
1343         case MONO_TYPE_VALUETYPE:
1344         case MONO_TYPE_TYPEDBYREF:
1345                 return STACK_VTYPE;
1346         case MONO_TYPE_GENERICINST:
1347                 if (mono_type_generic_inst_is_valuetype (t))
1348                         return STACK_VTYPE;
1349                 else
1350                         return STACK_OBJ;
1351                 break;
1352         default:
1353                 g_assert_not_reached ();
1354         }
1355
1356         return -1;
1357 }
1358
1359 static MonoClass*
1360 array_access_to_klass (int opcode)
1361 {
1362         switch (opcode) {
1363         case CEE_LDELEM_U1:
1364                 return mono_defaults.byte_class;
1365         case CEE_LDELEM_U2:
1366                 return mono_defaults.uint16_class;
1367         case CEE_LDELEM_I:
1368         case CEE_STELEM_I:
1369                 return mono_defaults.int_class;
1370         case CEE_LDELEM_I1:
1371         case CEE_STELEM_I1:
1372                 return mono_defaults.sbyte_class;
1373         case CEE_LDELEM_I2:
1374         case CEE_STELEM_I2:
1375                 return mono_defaults.int16_class;
1376         case CEE_LDELEM_I4:
1377         case CEE_STELEM_I4:
1378                 return mono_defaults.int32_class;
1379         case CEE_LDELEM_U4:
1380                 return mono_defaults.uint32_class;
1381         case CEE_LDELEM_I8:
1382         case CEE_STELEM_I8:
1383                 return mono_defaults.int64_class;
1384         case CEE_LDELEM_R4:
1385         case CEE_STELEM_R4:
1386                 return mono_defaults.single_class;
1387         case CEE_LDELEM_R8:
1388         case CEE_STELEM_R8:
1389                 return mono_defaults.double_class;
1390         case CEE_LDELEM_REF:
1391         case CEE_STELEM_REF:
1392                 return mono_defaults.object_class;
1393         default:
1394                 g_assert_not_reached ();
1395         }
1396         return NULL;
1397 }
1398
1399 /*
1400  * We try to share variables when possible
1401  */
1402 static MonoInst *
1403 mono_compile_get_interface_var (MonoCompile *cfg, int slot, MonoInst *ins)
1404 {
1405         MonoInst *res;
1406         int pos, vnum;
1407
1408         /* inlining can result in deeper stacks */ 
1409         if (slot >= cfg->header->max_stack)
1410                 return mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
1411
1412         pos = ins->type - 1 + slot * STACK_MAX;
1413
1414         switch (ins->type) {
1415         case STACK_I4:
1416         case STACK_I8:
1417         case STACK_R8:
1418         case STACK_PTR:
1419         case STACK_MP:
1420         case STACK_OBJ:
1421                 if ((vnum = cfg->intvars [pos]))
1422                         return cfg->varinfo [vnum];
1423                 res = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
1424                 cfg->intvars [pos] = res->inst_c0;
1425                 break;
1426         default:
1427                 res = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
1428         }
1429         return res;
1430 }
1431
1432 static void
1433 mono_save_token_info (MonoCompile *cfg, MonoImage *image, guint32 token, gpointer key)
1434 {
1435         /* 
1436          * Don't use this if a generic_context is set, since that means AOT can't
1437          * look up the method using just the image+token.
1438          * table == 0 means this is a reference made from a wrapper.
1439          */
1440         if (cfg->compile_aot && !cfg->generic_context && (mono_metadata_token_table (token) > 0)) {
1441                 MonoJumpInfoToken *jump_info_token = (MonoJumpInfoToken *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoJumpInfoToken));
1442                 jump_info_token->image = image;
1443                 jump_info_token->token = token;
1444                 g_hash_table_insert (cfg->token_info_hash, key, jump_info_token);
1445         }
1446 }
1447
1448 /*
1449  * This function is called to handle items that are left on the evaluation stack
1450  * at basic block boundaries. What happens is that we save the values to local variables
1451  * and we reload them later when first entering the target basic block (with the
1452  * handle_loaded_temps () function).
1453  * A single joint point will use the same variables (stored in the array bb->out_stack or
1454  * bb->in_stack, if the basic block is before or after the joint point).
1455  *
1456  * This function needs to be called _before_ emitting the last instruction of
1457  * the bb (i.e. before emitting a branch).
1458  * If the stack merge fails at a join point, cfg->unverifiable is set.
1459  */
1460 static void
1461 handle_stack_args (MonoCompile *cfg, MonoInst **sp, int count)
1462 {
1463         int i, bindex;
1464         MonoBasicBlock *bb = cfg->cbb;
1465         MonoBasicBlock *outb;
1466         MonoInst *inst, **locals;
1467         gboolean found;
1468
1469         if (!count)
1470                 return;
1471         if (cfg->verbose_level > 3)
1472                 printf ("%d item(s) on exit from B%d\n", count, bb->block_num);
1473         if (!bb->out_scount) {
1474                 bb->out_scount = count;
1475                 //printf ("bblock %d has out:", bb->block_num);
1476                 found = FALSE;
1477                 for (i = 0; i < bb->out_count; ++i) {
1478                         outb = bb->out_bb [i];
1479                         /* exception handlers are linked, but they should not be considered for stack args */
1480                         if (outb->flags & BB_EXCEPTION_HANDLER)
1481                                 continue;
1482                         //printf (" %d", outb->block_num);
1483                         if (outb->in_stack) {
1484                                 found = TRUE;
1485                                 bb->out_stack = outb->in_stack;
1486                                 break;
1487                         }
1488                 }
1489                 //printf ("\n");
1490                 if (!found) {
1491                         bb->out_stack = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * count);
1492                         for (i = 0; i < count; ++i) {
1493                                 /* 
1494                                  * try to reuse temps already allocated for this purpouse, if they occupy the same
1495                                  * stack slot and if they are of the same type.
1496                                  * This won't cause conflicts since if 'local' is used to 
1497                                  * store one of the values in the in_stack of a bblock, then
1498                                  * the same variable will be used for the same outgoing stack 
1499                                  * slot as well. 
1500                                  * This doesn't work when inlining methods, since the bblocks
1501                                  * in the inlined methods do not inherit their in_stack from
1502                                  * the bblock they are inlined to. See bug #58863 for an
1503                                  * example.
1504                                  */
1505                                 if (cfg->inlined_method)
1506                                         bb->out_stack [i] = mono_compile_create_var (cfg, type_from_stack_type (sp [i]), OP_LOCAL);
1507                                 else
1508                                         bb->out_stack [i] = mono_compile_get_interface_var (cfg, i, sp [i]);
1509                         }
1510                 }
1511         }
1512
1513         for (i = 0; i < bb->out_count; ++i) {
1514                 outb = bb->out_bb [i];
1515                 /* exception handlers are linked, but they should not be considered for stack args */
1516                 if (outb->flags & BB_EXCEPTION_HANDLER)
1517                         continue;
1518                 if (outb->in_scount) {
1519                         if (outb->in_scount != bb->out_scount) {
1520                                 cfg->unverifiable = TRUE;
1521                                 return;
1522                         }
1523                         continue; /* check they are the same locals */
1524                 }
1525                 outb->in_scount = count;
1526                 outb->in_stack = bb->out_stack;
1527         }
1528
1529         locals = bb->out_stack;
1530         cfg->cbb = bb;
1531         for (i = 0; i < count; ++i) {
1532                 EMIT_NEW_TEMPSTORE (cfg, inst, locals [i]->inst_c0, sp [i]);
1533                 inst->cil_code = sp [i]->cil_code;
1534                 sp [i] = locals [i];
1535                 if (cfg->verbose_level > 3)
1536                         printf ("storing %d to temp %d\n", i, (int)locals [i]->inst_c0);
1537         }
1538
1539         /*
1540          * It is possible that the out bblocks already have in_stack assigned, and
1541          * the in_stacks differ. In this case, we will store to all the different 
1542          * in_stacks.
1543          */
1544
1545         found = TRUE;
1546         bindex = 0;
1547         while (found) {
1548                 /* Find a bblock which has a different in_stack */
1549                 found = FALSE;
1550                 while (bindex < bb->out_count) {
1551                         outb = bb->out_bb [bindex];
1552                         /* exception handlers are linked, but they should not be considered for stack args */
1553                         if (outb->flags & BB_EXCEPTION_HANDLER) {
1554                                 bindex++;
1555                                 continue;
1556                         }
1557                         if (outb->in_stack != locals) {
1558                                 for (i = 0; i < count; ++i) {
1559                                         EMIT_NEW_TEMPSTORE (cfg, inst, outb->in_stack [i]->inst_c0, sp [i]);
1560                                         inst->cil_code = sp [i]->cil_code;
1561                                         sp [i] = locals [i];
1562                                         if (cfg->verbose_level > 3)
1563                                                 printf ("storing %d to temp %d\n", i, (int)outb->in_stack [i]->inst_c0);
1564                                 }
1565                                 locals = outb->in_stack;
1566                                 found = TRUE;
1567                                 break;
1568                         }
1569                         bindex ++;
1570                 }
1571         }
1572 }
1573
1574 MonoInst*
1575 mini_emit_runtime_constant (MonoCompile *cfg, MonoJumpInfoType patch_type, gpointer data)
1576 {
1577         MonoInst *ins;
1578
1579         if (cfg->compile_aot) {
1580                 EMIT_NEW_AOTCONST (cfg, ins, patch_type, data);
1581         } else {
1582                 MonoJumpInfo ji;
1583                 gpointer target;
1584                 MonoError error;
1585
1586                 ji.type = patch_type;
1587                 ji.data.target = data;
1588                 target = mono_resolve_patch_target (NULL, cfg->domain, NULL, &ji, FALSE, &error);
1589                 mono_error_assert_ok (&error);
1590
1591                 EMIT_NEW_PCONST (cfg, ins, target);
1592         }
1593         return ins;
1594 }
1595
1596 static MonoInst*
1597 mono_create_fast_tls_getter (MonoCompile *cfg, MonoTlsKey key)
1598 {
1599         int tls_offset = mono_tls_get_tls_offset (key);
1600
1601         if (cfg->compile_aot)
1602                 return NULL;
1603
1604         if (tls_offset != -1 && mono_arch_have_fast_tls ()) {
1605                 MonoInst *ins;
1606                 MONO_INST_NEW (cfg, ins, OP_TLS_GET);
1607                 ins->dreg = mono_alloc_preg (cfg);
1608                 ins->inst_offset = tls_offset;
1609                 return ins;
1610         }
1611         return NULL;
1612 }
1613
1614 static MonoInst*
1615 mono_create_fast_tls_setter (MonoCompile *cfg, MonoInst* value, MonoTlsKey key)
1616 {
1617         int tls_offset = mono_tls_get_tls_offset (key);
1618
1619         if (cfg->compile_aot)
1620                 return NULL;
1621
1622         if (tls_offset != -1 && mono_arch_have_fast_tls ()) {
1623                 MonoInst *ins;
1624                 MONO_INST_NEW (cfg, ins, OP_TLS_SET);
1625                 ins->sreg1 = value->dreg;
1626                 ins->inst_offset = tls_offset;
1627                 return ins;
1628         }
1629         return NULL;
1630 }
1631
1632
1633 MonoInst*
1634 mono_create_tls_get (MonoCompile *cfg, MonoTlsKey key)
1635 {
1636         MonoInst *fast_tls = NULL;
1637
1638         if (!mini_get_debug_options ()->use_fallback_tls)
1639                 fast_tls = mono_create_fast_tls_getter (cfg, key);
1640
1641         if (fast_tls) {
1642                 MONO_ADD_INS (cfg->cbb, fast_tls);
1643                 return fast_tls;
1644         }
1645
1646         if (cfg->compile_aot) {
1647                 MonoInst *addr;
1648                 /*
1649                  * tls getters are critical pieces of code and we don't want to resolve them
1650                  * through the standard plt/tramp mechanism since we might expose ourselves
1651                  * to crashes and infinite recursions.
1652                  */
1653                 EMIT_NEW_AOTCONST (cfg, addr, MONO_PATCH_INFO_GET_TLS_TRAMP, (void*)key);
1654                 return mini_emit_calli (cfg, helper_sig_get_tls_tramp, NULL, addr, NULL, NULL);
1655         } else {
1656                 gpointer getter = mono_tls_get_tls_getter (key, FALSE);
1657                 return mono_emit_jit_icall (cfg, getter, NULL);
1658         }
1659 }
1660
1661 static MonoInst*
1662 mono_create_tls_set (MonoCompile *cfg, MonoInst *value, MonoTlsKey key)
1663 {
1664         MonoInst *fast_tls = NULL;
1665
1666         if (!mini_get_debug_options ()->use_fallback_tls)
1667                 fast_tls = mono_create_fast_tls_setter (cfg, value, key);
1668
1669         if (fast_tls) {
1670                 MONO_ADD_INS (cfg->cbb, fast_tls);
1671                 return fast_tls;
1672         }
1673
1674         if (cfg->compile_aot) {
1675                 MonoInst *addr;
1676                 EMIT_NEW_AOTCONST (cfg, addr, MONO_PATCH_INFO_SET_TLS_TRAMP, (void*)key);
1677                 return mini_emit_calli (cfg, helper_sig_set_tls_tramp, &value, addr, NULL, NULL);
1678         } else {
1679                 gpointer setter = mono_tls_get_tls_setter (key, FALSE);
1680                 return mono_emit_jit_icall (cfg, setter, &value);
1681         }
1682 }
1683
1684 /*
1685  * emit_push_lmf:
1686  *
1687  *   Emit IR to push the current LMF onto the LMF stack.
1688  */
1689 static void
1690 emit_push_lmf (MonoCompile *cfg)
1691 {
1692         /*
1693          * Emit IR to push the LMF:
1694          * lmf_addr = <lmf_addr from tls>
1695          * lmf->lmf_addr = lmf_addr
1696          * lmf->prev_lmf = *lmf_addr
1697          * *lmf_addr = lmf
1698          */
1699         MonoInst *ins, *lmf_ins;
1700
1701         if (!cfg->lmf_ir)
1702                 return;
1703
1704         int lmf_reg, prev_lmf_reg;
1705         /*
1706          * Store lmf_addr in a variable, so it can be allocated to a global register.
1707          */
1708         if (!cfg->lmf_addr_var)
1709                 cfg->lmf_addr_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1710
1711 #ifdef HOST_WIN32
1712         ins = mono_create_tls_get (cfg, TLS_KEY_JIT_TLS);
1713         g_assert (ins);
1714         int jit_tls_dreg = ins->dreg;
1715
1716         lmf_reg = alloc_preg (cfg);
1717         EMIT_NEW_BIALU_IMM (cfg, lmf_ins, OP_PADD_IMM, lmf_reg, jit_tls_dreg, MONO_STRUCT_OFFSET (MonoJitTlsData, lmf));
1718 #else
1719         lmf_ins = mono_create_tls_get (cfg, TLS_KEY_LMF_ADDR);
1720         g_assert (lmf_ins);
1721 #endif
1722         lmf_ins->dreg = cfg->lmf_addr_var->dreg;
1723
1724         EMIT_NEW_VARLOADA (cfg, ins, cfg->lmf_var, NULL);
1725         lmf_reg = ins->dreg;
1726
1727         prev_lmf_reg = alloc_preg (cfg);
1728         /* Save previous_lmf */
1729         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, prev_lmf_reg, cfg->lmf_addr_var->dreg, 0);
1730         EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STORE_MEMBASE_REG, lmf_reg, MONO_STRUCT_OFFSET (MonoLMF, previous_lmf), prev_lmf_reg);
1731         /* Set new lmf */
1732         EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STORE_MEMBASE_REG, cfg->lmf_addr_var->dreg, 0, lmf_reg);
1733 }
1734
1735 /*
1736  * emit_pop_lmf:
1737  *
1738  *   Emit IR to pop the current LMF from the LMF stack.
1739  */
1740 static void
1741 emit_pop_lmf (MonoCompile *cfg)
1742 {
1743         int lmf_reg, lmf_addr_reg;
1744         MonoInst *ins;
1745
1746         if (!cfg->lmf_ir)
1747                 return;
1748
1749         EMIT_NEW_VARLOADA (cfg, ins, cfg->lmf_var, NULL);
1750         lmf_reg = ins->dreg;
1751
1752         int prev_lmf_reg;
1753         /*
1754          * Emit IR to pop the LMF:
1755          * *(lmf->lmf_addr) = lmf->prev_lmf
1756          */
1757         /* This could be called before emit_push_lmf () */
1758         if (!cfg->lmf_addr_var)
1759                 cfg->lmf_addr_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1760         lmf_addr_reg = cfg->lmf_addr_var->dreg;
1761
1762         prev_lmf_reg = alloc_preg (cfg);
1763         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, prev_lmf_reg, lmf_reg, MONO_STRUCT_OFFSET (MonoLMF, previous_lmf));
1764         EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STORE_MEMBASE_REG, lmf_addr_reg, 0, prev_lmf_reg);
1765 }
1766
1767 static void
1768 emit_instrumentation_call (MonoCompile *cfg, void *func)
1769 {
1770         MonoInst *iargs [1];
1771
1772         /*
1773          * Avoid instrumenting inlined methods since it can
1774          * distort profiling results.
1775          */
1776         if (cfg->method != cfg->current_method)
1777                 return;
1778
1779         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE) {
1780                 EMIT_NEW_METHODCONST (cfg, iargs [0], cfg->method);
1781                 mono_emit_jit_icall (cfg, func, iargs);
1782         }
1783 }
1784
1785 static int
1786 ret_type_to_call_opcode (MonoCompile *cfg, MonoType *type, int calli, int virt)
1787 {
1788 handle_enum:
1789         type = mini_get_underlying_type (type);
1790         switch (type->type) {
1791         case MONO_TYPE_VOID:
1792                 return calli? OP_VOIDCALL_REG: virt? OP_VOIDCALL_MEMBASE: OP_VOIDCALL;
1793         case MONO_TYPE_I1:
1794         case MONO_TYPE_U1:
1795         case MONO_TYPE_I2:
1796         case MONO_TYPE_U2:
1797         case MONO_TYPE_I4:
1798         case MONO_TYPE_U4:
1799                 return calli? OP_CALL_REG: virt? OP_CALL_MEMBASE: OP_CALL;
1800         case MONO_TYPE_I:
1801         case MONO_TYPE_U:
1802         case MONO_TYPE_PTR:
1803         case MONO_TYPE_FNPTR:
1804                 return calli? OP_CALL_REG: virt? OP_CALL_MEMBASE: OP_CALL;
1805         case MONO_TYPE_CLASS:
1806         case MONO_TYPE_STRING:
1807         case MONO_TYPE_OBJECT:
1808         case MONO_TYPE_SZARRAY:
1809         case MONO_TYPE_ARRAY:    
1810                 return calli? OP_CALL_REG: virt? OP_CALL_MEMBASE: OP_CALL;
1811         case MONO_TYPE_I8:
1812         case MONO_TYPE_U8:
1813                 return calli? OP_LCALL_REG: virt? OP_LCALL_MEMBASE: OP_LCALL;
1814         case MONO_TYPE_R4:
1815                 if (cfg->r4fp)
1816                         return calli? OP_RCALL_REG: virt? OP_RCALL_MEMBASE: OP_RCALL;
1817                 else
1818                         return calli? OP_FCALL_REG: virt? OP_FCALL_MEMBASE: OP_FCALL;
1819         case MONO_TYPE_R8:
1820                 return calli? OP_FCALL_REG: virt? OP_FCALL_MEMBASE: OP_FCALL;
1821         case MONO_TYPE_VALUETYPE:
1822                 if (type->data.klass->enumtype) {
1823                         type = mono_class_enum_basetype (type->data.klass);
1824                         goto handle_enum;
1825                 } else
1826                         return calli? OP_VCALL_REG: virt? OP_VCALL_MEMBASE: OP_VCALL;
1827         case MONO_TYPE_TYPEDBYREF:
1828                 return calli? OP_VCALL_REG: virt? OP_VCALL_MEMBASE: OP_VCALL;
1829         case MONO_TYPE_GENERICINST:
1830                 type = &type->data.generic_class->container_class->byval_arg;
1831                 goto handle_enum;
1832         case MONO_TYPE_VAR:
1833         case MONO_TYPE_MVAR:
1834                 /* gsharedvt */
1835                 return calli? OP_VCALL_REG: virt? OP_VCALL_MEMBASE: OP_VCALL;
1836         default:
1837                 g_error ("unknown type 0x%02x in ret_type_to_call_opcode", type->type);
1838         }
1839         return -1;
1840 }
1841
1842 //XXX this ignores if t is byref
1843 #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)))))
1844
1845 /*
1846  * target_type_is_incompatible:
1847  * @cfg: MonoCompile context
1848  *
1849  * Check that the item @arg on the evaluation stack can be stored
1850  * in the target type (can be a local, or field, etc).
1851  * The cfg arg can be used to check if we need verification or just
1852  * validity checks.
1853  *
1854  * Returns: non-0 value if arg can't be stored on a target.
1855  */
1856 static int
1857 target_type_is_incompatible (MonoCompile *cfg, MonoType *target, MonoInst *arg)
1858 {
1859         MonoType *simple_type;
1860         MonoClass *klass;
1861
1862         if (target->byref) {
1863                 /* FIXME: check that the pointed to types match */
1864                 if (arg->type == STACK_MP) {
1865                         /* This is needed to handle gshared types + ldaddr. We lower the types so we can handle enums and other typedef-like types. */
1866                         MonoClass *target_class_lowered = mono_class_from_mono_type (mini_get_underlying_type (&mono_class_from_mono_type (target)->byval_arg));
1867                         MonoClass *source_class_lowered = mono_class_from_mono_type (mini_get_underlying_type (&arg->klass->byval_arg));
1868
1869                         /* if the target is native int& or same type */
1870                         if (target->type == MONO_TYPE_I || target_class_lowered == source_class_lowered)
1871                                 return 0;
1872
1873                         /* Both are primitive type byrefs and the source points to a larger type that the destination */
1874                         if (MONO_TYPE_IS_PRIMITIVE_SCALAR (&target_class_lowered->byval_arg) && MONO_TYPE_IS_PRIMITIVE_SCALAR (&source_class_lowered->byval_arg) &&
1875                                 mono_class_instance_size (target_class_lowered) <= mono_class_instance_size (source_class_lowered))
1876                                 return 0;
1877                         return 1;
1878                 }
1879                 if (arg->type == STACK_PTR)
1880                         return 0;
1881                 return 1;
1882         }
1883
1884         simple_type = mini_get_underlying_type (target);
1885         switch (simple_type->type) {
1886         case MONO_TYPE_VOID:
1887                 return 1;
1888         case MONO_TYPE_I1:
1889         case MONO_TYPE_U1:
1890         case MONO_TYPE_I2:
1891         case MONO_TYPE_U2:
1892         case MONO_TYPE_I4:
1893         case MONO_TYPE_U4:
1894                 if (arg->type != STACK_I4 && arg->type != STACK_PTR)
1895                         return 1;
1896                 return 0;
1897         case MONO_TYPE_PTR:
1898                 /* STACK_MP is needed when setting pinned locals */
1899                 if (arg->type != STACK_I4 && arg->type != STACK_PTR && arg->type != STACK_MP)
1900                         return 1;
1901                 return 0;
1902         case MONO_TYPE_I:
1903         case MONO_TYPE_U:
1904         case MONO_TYPE_FNPTR:
1905                 /* 
1906                  * Some opcodes like ldloca returns 'transient pointers' which can be stored in
1907                  * in native int. (#688008).
1908                  */
1909                 if (arg->type != STACK_I4 && arg->type != STACK_PTR && arg->type != STACK_MP)
1910                         return 1;
1911                 return 0;
1912         case MONO_TYPE_CLASS:
1913         case MONO_TYPE_STRING:
1914         case MONO_TYPE_OBJECT:
1915         case MONO_TYPE_SZARRAY:
1916         case MONO_TYPE_ARRAY:    
1917                 if (arg->type != STACK_OBJ)
1918                         return 1;
1919                 /* FIXME: check type compatibility */
1920                 return 0;
1921         case MONO_TYPE_I8:
1922         case MONO_TYPE_U8:
1923                 if (arg->type != STACK_I8)
1924                         return 1;
1925                 return 0;
1926         case MONO_TYPE_R4:
1927                 if (arg->type != cfg->r4_stack_type)
1928                         return 1;
1929                 return 0;
1930         case MONO_TYPE_R8:
1931                 if (arg->type != STACK_R8)
1932                         return 1;
1933                 return 0;
1934         case MONO_TYPE_VALUETYPE:
1935                 if (arg->type != STACK_VTYPE)
1936                         return 1;
1937                 klass = mono_class_from_mono_type (simple_type);
1938                 if (klass != arg->klass)
1939                         return 1;
1940                 return 0;
1941         case MONO_TYPE_TYPEDBYREF:
1942                 if (arg->type != STACK_VTYPE)
1943                         return 1;
1944                 klass = mono_class_from_mono_type (simple_type);
1945                 if (klass != arg->klass)
1946                         return 1;
1947                 return 0;
1948         case MONO_TYPE_GENERICINST:
1949                 if (mono_type_generic_inst_is_valuetype (simple_type)) {
1950                         MonoClass *target_class;
1951                         if (arg->type != STACK_VTYPE)
1952                                 return 1;
1953                         klass = mono_class_from_mono_type (simple_type);
1954                         target_class = mono_class_from_mono_type (target);
1955                         /* The second cases is needed when doing partial sharing */
1956                         if (klass != arg->klass && target_class != arg->klass && target_class != mono_class_from_mono_type (mini_get_underlying_type (&arg->klass->byval_arg)))
1957                                 return 1;
1958                         return 0;
1959                 } else {
1960                         if (arg->type != STACK_OBJ)
1961                                 return 1;
1962                         /* FIXME: check type compatibility */
1963                         return 0;
1964                 }
1965         case MONO_TYPE_VAR:
1966         case MONO_TYPE_MVAR:
1967                 g_assert (cfg->gshared);
1968                 if (mini_type_var_is_vt (simple_type)) {
1969                         if (arg->type != STACK_VTYPE)
1970                                 return 1;
1971                 } else {
1972                         if (arg->type != STACK_OBJ)
1973                                 return 1;
1974                 }
1975                 return 0;
1976         default:
1977                 g_error ("unknown type 0x%02x in target_type_is_incompatible", simple_type->type);
1978         }
1979         return 1;
1980 }
1981
1982 /*
1983  * Prepare arguments for passing to a function call.
1984  * Return a non-zero value if the arguments can't be passed to the given
1985  * signature.
1986  * The type checks are not yet complete and some conversions may need
1987  * casts on 32 or 64 bit architectures.
1988  *
1989  * FIXME: implement this using target_type_is_incompatible ()
1990  */
1991 static int
1992 check_call_signature (MonoCompile *cfg, MonoMethodSignature *sig, MonoInst **args)
1993 {
1994         MonoType *simple_type;
1995         int i;
1996
1997         if (sig->hasthis) {
1998                 if (args [0]->type != STACK_OBJ && args [0]->type != STACK_MP && args [0]->type != STACK_PTR)
1999                         return 1;
2000                 args++;
2001         }
2002         for (i = 0; i < sig->param_count; ++i) {
2003                 if (sig->params [i]->byref) {
2004                         if (args [i]->type != STACK_MP && args [i]->type != STACK_PTR)
2005                                 return 1;
2006                         continue;
2007                 }
2008                 simple_type = mini_get_underlying_type (sig->params [i]);
2009 handle_enum:
2010                 switch (simple_type->type) {
2011                 case MONO_TYPE_VOID:
2012                         return 1;
2013                         continue;
2014                 case MONO_TYPE_I1:
2015                 case MONO_TYPE_U1:
2016                 case MONO_TYPE_I2:
2017                 case MONO_TYPE_U2:
2018                 case MONO_TYPE_I4:
2019                 case MONO_TYPE_U4:
2020                         if (args [i]->type != STACK_I4 && args [i]->type != STACK_PTR)
2021                                 return 1;
2022                         continue;
2023                 case MONO_TYPE_I:
2024                 case MONO_TYPE_U:
2025                 case MONO_TYPE_PTR:
2026                 case MONO_TYPE_FNPTR:
2027                         if (args [i]->type != STACK_I4 && args [i]->type != STACK_PTR && args [i]->type != STACK_MP && args [i]->type != STACK_OBJ)
2028                                 return 1;
2029                         continue;
2030                 case MONO_TYPE_CLASS:
2031                 case MONO_TYPE_STRING:
2032                 case MONO_TYPE_OBJECT:
2033                 case MONO_TYPE_SZARRAY:
2034                 case MONO_TYPE_ARRAY:    
2035                         if (args [i]->type != STACK_OBJ)
2036                                 return 1;
2037                         continue;
2038                 case MONO_TYPE_I8:
2039                 case MONO_TYPE_U8:
2040                         if (args [i]->type != STACK_I8)
2041                                 return 1;
2042                         continue;
2043                 case MONO_TYPE_R4:
2044                         if (args [i]->type != cfg->r4_stack_type)
2045                                 return 1;
2046                         continue;
2047                 case MONO_TYPE_R8:
2048                         if (args [i]->type != STACK_R8)
2049                                 return 1;
2050                         continue;
2051                 case MONO_TYPE_VALUETYPE:
2052                         if (simple_type->data.klass->enumtype) {
2053                                 simple_type = mono_class_enum_basetype (simple_type->data.klass);
2054                                 goto handle_enum;
2055                         }
2056                         if (args [i]->type != STACK_VTYPE)
2057                                 return 1;
2058                         continue;
2059                 case MONO_TYPE_TYPEDBYREF:
2060                         if (args [i]->type != STACK_VTYPE)
2061                                 return 1;
2062                         continue;
2063                 case MONO_TYPE_GENERICINST:
2064                         simple_type = &simple_type->data.generic_class->container_class->byval_arg;
2065                         goto handle_enum;
2066                 case MONO_TYPE_VAR:
2067                 case MONO_TYPE_MVAR:
2068                         /* gsharedvt */
2069                         if (args [i]->type != STACK_VTYPE)
2070                                 return 1;
2071                         continue;
2072                 default:
2073                         g_error ("unknown type 0x%02x in check_call_signature",
2074                                  simple_type->type);
2075                 }
2076         }
2077         return 0;
2078 }
2079
2080 static int
2081 callvirt_to_call (int opcode)
2082 {
2083         switch (opcode) {
2084         case OP_CALL_MEMBASE:
2085                 return OP_CALL;
2086         case OP_VOIDCALL_MEMBASE:
2087                 return OP_VOIDCALL;
2088         case OP_FCALL_MEMBASE:
2089                 return OP_FCALL;
2090         case OP_RCALL_MEMBASE:
2091                 return OP_RCALL;
2092         case OP_VCALL_MEMBASE:
2093                 return OP_VCALL;
2094         case OP_LCALL_MEMBASE:
2095                 return OP_LCALL;
2096         default:
2097                 g_assert_not_reached ();
2098         }
2099
2100         return -1;
2101 }
2102
2103 static int
2104 callvirt_to_call_reg (int opcode)
2105 {
2106         switch (opcode) {
2107         case OP_CALL_MEMBASE:
2108                 return OP_CALL_REG;
2109         case OP_VOIDCALL_MEMBASE:
2110                 return OP_VOIDCALL_REG;
2111         case OP_FCALL_MEMBASE:
2112                 return OP_FCALL_REG;
2113         case OP_RCALL_MEMBASE:
2114                 return OP_RCALL_REG;
2115         case OP_VCALL_MEMBASE:
2116                 return OP_VCALL_REG;
2117         case OP_LCALL_MEMBASE:
2118                 return OP_LCALL_REG;
2119         default:
2120                 g_assert_not_reached ();
2121         }
2122
2123         return -1;
2124 }
2125
2126 /* Either METHOD or IMT_ARG needs to be set */
2127 static void
2128 emit_imt_argument (MonoCompile *cfg, MonoCallInst *call, MonoMethod *method, MonoInst *imt_arg)
2129 {
2130         int method_reg;
2131
2132         if (COMPILE_LLVM (cfg)) {
2133                 if (imt_arg) {
2134                         method_reg = alloc_preg (cfg);
2135                         MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, method_reg, imt_arg->dreg);
2136                 } else {
2137                         MonoInst *ins = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_METHODCONST, method);
2138                         method_reg = ins->dreg;
2139                 }
2140
2141 #ifdef ENABLE_LLVM
2142                 call->imt_arg_reg = method_reg;
2143 #endif
2144                 mono_call_inst_add_outarg_reg (cfg, call, method_reg, MONO_ARCH_IMT_REG, FALSE);
2145                 return;
2146         }
2147
2148         if (imt_arg) {
2149                 method_reg = alloc_preg (cfg);
2150                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, method_reg, imt_arg->dreg);
2151         } else {
2152                 MonoInst *ins = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_METHODCONST, method);
2153                 method_reg = ins->dreg;
2154         }
2155
2156         mono_call_inst_add_outarg_reg (cfg, call, method_reg, MONO_ARCH_IMT_REG, FALSE);
2157 }
2158
2159 static MonoJumpInfo *
2160 mono_patch_info_new (MonoMemPool *mp, int ip, MonoJumpInfoType type, gconstpointer target)
2161 {
2162         MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc (mp, sizeof (MonoJumpInfo));
2163
2164         ji->ip.i = ip;
2165         ji->type = type;
2166         ji->data.target = target;
2167
2168         return ji;
2169 }
2170
2171 int
2172 mini_class_check_context_used (MonoCompile *cfg, MonoClass *klass)
2173 {
2174         if (cfg->gshared)
2175                 return mono_class_check_context_used (klass);
2176         else
2177                 return 0;
2178 }
2179
2180 static int
2181 mini_method_check_context_used (MonoCompile *cfg, MonoMethod *method)
2182 {
2183         if (cfg->gshared)
2184                 return mono_method_check_context_used (method);
2185         else
2186                 return 0;
2187 }
2188
2189 /*
2190  * check_method_sharing:
2191  *
2192  *   Check whenever the vtable or an mrgctx needs to be passed when calling CMETHOD.
2193  */
2194 static void
2195 check_method_sharing (MonoCompile *cfg, MonoMethod *cmethod, gboolean *out_pass_vtable, gboolean *out_pass_mrgctx)
2196 {
2197         gboolean pass_vtable = FALSE;
2198         gboolean pass_mrgctx = FALSE;
2199
2200         if (((cmethod->flags & METHOD_ATTRIBUTE_STATIC) || cmethod->klass->valuetype) &&
2201                 (mono_class_is_ginst (cmethod->klass) || mono_class_is_gtd (cmethod->klass))) {
2202                 gboolean sharable = FALSE;
2203
2204                 if (mono_method_is_generic_sharable_full (cmethod, TRUE, TRUE, TRUE))
2205                         sharable = TRUE;
2206
2207                 /*
2208                  * Pass vtable iff target method might
2209                  * be shared, which means that sharing
2210                  * is enabled for its class and its
2211                  * context is sharable (and it's not a
2212                  * generic method).
2213                  */
2214                 if (sharable && !(mini_method_get_context (cmethod) && mini_method_get_context (cmethod)->method_inst))
2215                         pass_vtable = TRUE;
2216         }
2217
2218         if (mini_method_get_context (cmethod) &&
2219                 mini_method_get_context (cmethod)->method_inst) {
2220                 g_assert (!pass_vtable);
2221
2222                 if (mono_method_is_generic_sharable_full (cmethod, TRUE, TRUE, TRUE)) {
2223                         pass_mrgctx = TRUE;
2224                 } else {
2225                         if (cfg->gsharedvt && mini_is_gsharedvt_signature (mono_method_signature (cmethod)))
2226                                 pass_mrgctx = TRUE;
2227                 }
2228         }
2229
2230         if (out_pass_vtable)
2231                 *out_pass_vtable = pass_vtable;
2232         if (out_pass_mrgctx)
2233                 *out_pass_mrgctx = pass_mrgctx;
2234 }
2235
2236 inline static MonoCallInst *
2237 mono_emit_call_args (MonoCompile *cfg, MonoMethodSignature *sig, 
2238                                          MonoInst **args, int calli, int virtual_, int tail, int rgctx, int unbox_trampoline)
2239 {
2240         MonoType *sig_ret;
2241         MonoCallInst *call;
2242 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
2243         int i;
2244 #endif
2245
2246         if (cfg->llvm_only)
2247                 tail = FALSE;
2248
2249         if (tail) {
2250                 emit_instrumentation_call (cfg, mono_profiler_method_leave);
2251
2252                 MONO_INST_NEW_CALL (cfg, call, OP_TAILCALL);
2253         } else
2254                 MONO_INST_NEW_CALL (cfg, call, ret_type_to_call_opcode (cfg, sig->ret, calli, virtual_));
2255
2256         call->args = args;
2257         call->signature = sig;
2258         call->rgctx_reg = rgctx;
2259         sig_ret = mini_get_underlying_type (sig->ret);
2260
2261         type_to_eval_stack_type ((cfg), sig_ret, &call->inst);
2262
2263         if (tail) {
2264                 if (mini_type_is_vtype (sig_ret)) {
2265                         call->vret_var = cfg->vret_addr;
2266                         //g_assert_not_reached ();
2267                 }
2268         } else if (mini_type_is_vtype (sig_ret)) {
2269                 MonoInst *temp = mono_compile_create_var (cfg, sig_ret, OP_LOCAL);
2270                 MonoInst *loada;
2271
2272                 temp->backend.is_pinvoke = sig->pinvoke;
2273
2274                 /*
2275                  * We use a new opcode OP_OUTARG_VTRETADDR instead of LDADDR for emitting the
2276                  * address of return value to increase optimization opportunities.
2277                  * Before vtype decomposition, the dreg of the call ins itself represents the
2278                  * fact the call modifies the return value. After decomposition, the call will
2279                  * be transformed into one of the OP_VOIDCALL opcodes, and the VTRETADDR opcode
2280                  * will be transformed into an LDADDR.
2281                  */
2282                 MONO_INST_NEW (cfg, loada, OP_OUTARG_VTRETADDR);
2283                 loada->dreg = alloc_preg (cfg);
2284                 loada->inst_p0 = temp;
2285                 /* We reference the call too since call->dreg could change during optimization */
2286                 loada->inst_p1 = call;
2287                 MONO_ADD_INS (cfg->cbb, loada);
2288
2289                 call->inst.dreg = temp->dreg;
2290
2291                 call->vret_var = loada;
2292         } else if (!MONO_TYPE_IS_VOID (sig_ret))
2293                 call->inst.dreg = alloc_dreg (cfg, (MonoStackType)call->inst.type);
2294
2295 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
2296         if (COMPILE_SOFT_FLOAT (cfg)) {
2297                 /* 
2298                  * If the call has a float argument, we would need to do an r8->r4 conversion using 
2299                  * an icall, but that cannot be done during the call sequence since it would clobber
2300                  * the call registers + the stack. So we do it before emitting the call.
2301                  */
2302                 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
2303                         MonoType *t;
2304                         MonoInst *in = call->args [i];
2305
2306                         if (i >= sig->hasthis)
2307                                 t = sig->params [i - sig->hasthis];
2308                         else
2309                                 t = &mono_defaults.int_class->byval_arg;
2310                         t = mono_type_get_underlying_type (t);
2311
2312                         if (!t->byref && t->type == MONO_TYPE_R4) {
2313                                 MonoInst *iargs [1];
2314                                 MonoInst *conv;
2315
2316                                 iargs [0] = in;
2317                                 conv = mono_emit_jit_icall (cfg, mono_fload_r4_arg, iargs);
2318
2319                                 /* The result will be in an int vreg */
2320                                 call->args [i] = conv;
2321                         }
2322                 }
2323         }
2324 #endif
2325
2326         call->need_unbox_trampoline = unbox_trampoline;
2327
2328 #ifdef ENABLE_LLVM
2329         if (COMPILE_LLVM (cfg))
2330                 mono_llvm_emit_call (cfg, call);
2331         else
2332                 mono_arch_emit_call (cfg, call);
2333 #else
2334         mono_arch_emit_call (cfg, call);
2335 #endif
2336
2337         cfg->param_area = MAX (cfg->param_area, call->stack_usage);
2338         cfg->flags |= MONO_CFG_HAS_CALLS;
2339         
2340         return call;
2341 }
2342
2343 static void
2344 set_rgctx_arg (MonoCompile *cfg, MonoCallInst *call, int rgctx_reg, MonoInst *rgctx_arg)
2345 {
2346         mono_call_inst_add_outarg_reg (cfg, call, rgctx_reg, MONO_ARCH_RGCTX_REG, FALSE);
2347         cfg->uses_rgctx_reg = TRUE;
2348         call->rgctx_reg = TRUE;
2349 #ifdef ENABLE_LLVM
2350         call->rgctx_arg_reg = rgctx_reg;
2351 #endif
2352 }       
2353
2354 MonoInst*
2355 mini_emit_calli (MonoCompile *cfg, MonoMethodSignature *sig, MonoInst **args, MonoInst *addr, MonoInst *imt_arg, MonoInst *rgctx_arg)
2356 {
2357         MonoCallInst *call;
2358         MonoInst *ins;
2359         int rgctx_reg = -1;
2360         gboolean check_sp = FALSE;
2361
2362         if (cfg->check_pinvoke_callconv && cfg->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
2363                 WrapperInfo *info = mono_marshal_get_wrapper_info (cfg->method);
2364
2365                 if (info && info->subtype == WRAPPER_SUBTYPE_PINVOKE)
2366                         check_sp = TRUE;
2367         }
2368
2369         if (rgctx_arg) {
2370                 rgctx_reg = mono_alloc_preg (cfg);
2371                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, rgctx_reg, rgctx_arg->dreg);
2372         }
2373
2374         if (check_sp) {
2375                 if (!cfg->stack_inbalance_var)
2376                         cfg->stack_inbalance_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
2377
2378                 MONO_INST_NEW (cfg, ins, OP_GET_SP);
2379                 ins->dreg = cfg->stack_inbalance_var->dreg;
2380                 MONO_ADD_INS (cfg->cbb, ins);
2381         }
2382
2383         call = mono_emit_call_args (cfg, sig, args, TRUE, FALSE, FALSE, rgctx_arg ? TRUE : FALSE, FALSE);
2384
2385         call->inst.sreg1 = addr->dreg;
2386
2387         if (imt_arg)
2388                 emit_imt_argument (cfg, call, NULL, imt_arg);
2389
2390         MONO_ADD_INS (cfg->cbb, (MonoInst*)call);
2391
2392         if (check_sp) {
2393                 int sp_reg;
2394
2395                 sp_reg = mono_alloc_preg (cfg);
2396
2397                 MONO_INST_NEW (cfg, ins, OP_GET_SP);
2398                 ins->dreg = sp_reg;
2399                 MONO_ADD_INS (cfg->cbb, ins);
2400
2401                 /* Restore the stack so we don't crash when throwing the exception */
2402                 MONO_INST_NEW (cfg, ins, OP_SET_SP);
2403                 ins->sreg1 = cfg->stack_inbalance_var->dreg;
2404                 MONO_ADD_INS (cfg->cbb, ins);
2405
2406                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, cfg->stack_inbalance_var->dreg, sp_reg);
2407                 MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "ExecutionEngineException");
2408         }
2409
2410         if (rgctx_arg)
2411                 set_rgctx_arg (cfg, call, rgctx_reg, rgctx_arg);
2412
2413         return (MonoInst*)call;
2414 }
2415
2416 static MonoInst*
2417 emit_get_rgctx_method (MonoCompile *cfg, int context_used, MonoMethod *cmethod, MonoRgctxInfoType rgctx_type);
2418
2419 static MonoInst*
2420 mono_emit_method_call_full (MonoCompile *cfg, MonoMethod *method, MonoMethodSignature *sig, gboolean tail,
2421                                                         MonoInst **args, MonoInst *this_ins, MonoInst *imt_arg, MonoInst *rgctx_arg)
2422 {
2423 #ifndef DISABLE_REMOTING
2424         gboolean might_be_remote = FALSE;
2425 #endif
2426         gboolean virtual_ = this_ins != NULL;
2427         gboolean enable_for_aot = TRUE;
2428         int context_used;
2429         MonoCallInst *call;
2430         MonoInst *call_target = NULL;
2431         int rgctx_reg = 0;
2432         gboolean need_unbox_trampoline;
2433
2434         if (!sig)
2435                 sig = mono_method_signature (method);
2436
2437         if (cfg->llvm_only && (mono_class_is_interface (method->klass)))
2438                 g_assert_not_reached ();
2439
2440         if (rgctx_arg) {
2441                 rgctx_reg = mono_alloc_preg (cfg);
2442                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, rgctx_reg, rgctx_arg->dreg);
2443         }
2444
2445         if (method->string_ctor) {
2446                 /* Create the real signature */
2447                 /* FIXME: Cache these */
2448                 MonoMethodSignature *ctor_sig = mono_metadata_signature_dup_mempool (cfg->mempool, sig);
2449                 ctor_sig->ret = &mono_defaults.string_class->byval_arg;
2450
2451                 sig = ctor_sig;
2452         }
2453
2454         context_used = mini_method_check_context_used (cfg, method);
2455
2456 #ifndef DISABLE_REMOTING
2457         might_be_remote = this_ins && sig->hasthis &&
2458                 (mono_class_is_marshalbyref (method->klass) || method->klass == mono_defaults.object_class) &&
2459                 !(method->flags & METHOD_ATTRIBUTE_VIRTUAL) && (!MONO_CHECK_THIS (this_ins) || context_used);
2460
2461         if (might_be_remote && context_used) {
2462                 MonoInst *addr;
2463
2464                 g_assert (cfg->gshared);
2465
2466                 addr = emit_get_rgctx_method (cfg, context_used, method, MONO_RGCTX_INFO_REMOTING_INVOKE_WITH_CHECK);
2467
2468                 return mini_emit_calli (cfg, sig, args, addr, NULL, NULL);
2469         }
2470 #endif
2471
2472         if (cfg->llvm_only && !call_target && virtual_ && (method->flags & METHOD_ATTRIBUTE_VIRTUAL))
2473                 return emit_llvmonly_virtual_call (cfg, method, sig, 0, args);
2474
2475         need_unbox_trampoline = method->klass == mono_defaults.object_class || mono_class_is_interface (method->klass);
2476
2477         call = mono_emit_call_args (cfg, sig, args, FALSE, virtual_, tail, rgctx_arg ? TRUE : FALSE, need_unbox_trampoline);
2478
2479 #ifndef DISABLE_REMOTING
2480         if (might_be_remote)
2481                 call->method = mono_marshal_get_remoting_invoke_with_check (method);
2482         else
2483 #endif
2484                 call->method = method;
2485         call->inst.flags |= MONO_INST_HAS_METHOD;
2486         call->inst.inst_left = this_ins;
2487         call->tail_call = tail;
2488
2489         if (virtual_) {
2490                 int vtable_reg, slot_reg, this_reg;
2491                 int offset;
2492
2493                 this_reg = this_ins->dreg;
2494
2495                 if (!cfg->llvm_only && (method->klass->parent == mono_defaults.multicastdelegate_class) && !strcmp (method->name, "Invoke")) {
2496                         MonoInst *dummy_use;
2497
2498                         MONO_EMIT_NULL_CHECK (cfg, this_reg);
2499
2500                         /* Make a call to delegate->invoke_impl */
2501                         call->inst.inst_basereg = this_reg;
2502                         call->inst.inst_offset = MONO_STRUCT_OFFSET (MonoDelegate, invoke_impl);
2503                         MONO_ADD_INS (cfg->cbb, (MonoInst*)call);
2504
2505                         /* We must emit a dummy use here because the delegate trampoline will
2506                         replace the 'this' argument with the delegate target making this activation
2507                         no longer a root for the delegate.
2508                         This is an issue for delegates that target collectible code such as dynamic
2509                         methods of GC'able assemblies.
2510
2511                         For a test case look into #667921.
2512
2513                         FIXME: a dummy use is not the best way to do it as the local register allocator
2514                         will put it on a caller save register and spil it around the call. 
2515                         Ideally, we would either put it on a callee save register or only do the store part.  
2516                          */
2517                         EMIT_NEW_DUMMY_USE (cfg, dummy_use, args [0]);
2518
2519                         return (MonoInst*)call;
2520                 }
2521
2522                 if ((!cfg->compile_aot || enable_for_aot) && 
2523                         (!(method->flags & METHOD_ATTRIBUTE_VIRTUAL) || 
2524                          (MONO_METHOD_IS_FINAL (method) &&
2525                           method->wrapper_type != MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)) &&
2526                         !(mono_class_is_marshalbyref (method->klass) && context_used)) {
2527                         /* 
2528                          * the method is not virtual, we just need to ensure this is not null
2529                          * and then we can call the method directly.
2530                          */
2531 #ifndef DISABLE_REMOTING
2532                         if (mono_class_is_marshalbyref (method->klass) || method->klass == mono_defaults.object_class) {
2533                                 /* 
2534                                  * The check above ensures method is not gshared, this is needed since
2535                                  * gshared methods can't have wrappers.
2536                                  */
2537                                 method = call->method = mono_marshal_get_remoting_invoke_with_check (method);
2538                         }
2539 #endif
2540
2541                         if (!method->string_ctor)
2542                                 MONO_EMIT_NEW_CHECK_THIS (cfg, this_reg);
2543
2544                         call->inst.opcode = callvirt_to_call (call->inst.opcode);
2545                 } else if ((method->flags & METHOD_ATTRIBUTE_VIRTUAL) && MONO_METHOD_IS_FINAL (method)) {
2546                         /*
2547                          * the method is virtual, but we can statically dispatch since either
2548                          * it's class or the method itself are sealed.
2549                          * But first we need to ensure it's not a null reference.
2550                          */
2551                         MONO_EMIT_NEW_CHECK_THIS (cfg, this_reg);
2552
2553                         call->inst.opcode = callvirt_to_call (call->inst.opcode);
2554                 } else if (call_target) {
2555                         vtable_reg = alloc_preg (cfg);
2556                         MONO_EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, vtable_reg, this_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
2557
2558                         call->inst.opcode = callvirt_to_call_reg (call->inst.opcode);
2559                         call->inst.sreg1 = call_target->dreg;
2560                         call->inst.flags &= !MONO_INST_HAS_METHOD;
2561                 } else {
2562                         vtable_reg = alloc_preg (cfg);
2563                         MONO_EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, vtable_reg, this_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
2564                         if (mono_class_is_interface (method->klass)) {
2565                                 guint32 imt_slot = mono_method_get_imt_slot (method);
2566                                 emit_imt_argument (cfg, call, call->method, imt_arg);
2567                                 slot_reg = vtable_reg;
2568                                 offset = ((gint32)imt_slot - MONO_IMT_SIZE) * SIZEOF_VOID_P;
2569                         } else {
2570                                 slot_reg = vtable_reg;
2571                                 offset = MONO_STRUCT_OFFSET (MonoVTable, vtable) +
2572                                         ((mono_method_get_vtable_index (method)) * (SIZEOF_VOID_P));
2573                                 if (imt_arg) {
2574                                         g_assert (mono_method_signature (method)->generic_param_count);
2575                                         emit_imt_argument (cfg, call, call->method, imt_arg);
2576                                 }
2577                         }
2578
2579                         call->inst.sreg1 = slot_reg;
2580                         call->inst.inst_offset = offset;
2581                         call->is_virtual = TRUE;
2582                 }
2583         }
2584
2585         MONO_ADD_INS (cfg->cbb, (MonoInst*)call);
2586
2587         if (rgctx_arg)
2588                 set_rgctx_arg (cfg, call, rgctx_reg, rgctx_arg);
2589
2590         return (MonoInst*)call;
2591 }
2592
2593 MonoInst*
2594 mono_emit_method_call (MonoCompile *cfg, MonoMethod *method, MonoInst **args, MonoInst *this_ins)
2595 {
2596         return mono_emit_method_call_full (cfg, method, mono_method_signature (method), FALSE, args, this_ins, NULL, NULL);
2597 }
2598
2599 MonoInst*
2600 mono_emit_native_call (MonoCompile *cfg, gconstpointer func, MonoMethodSignature *sig,
2601                                            MonoInst **args)
2602 {
2603         MonoCallInst *call;
2604
2605         g_assert (sig);
2606
2607         call = mono_emit_call_args (cfg, sig, args, FALSE, FALSE, FALSE, FALSE, FALSE);
2608         call->fptr = func;
2609
2610         MONO_ADD_INS (cfg->cbb, (MonoInst*)call);
2611
2612         return (MonoInst*)call;
2613 }
2614
2615 MonoInst*
2616 mono_emit_jit_icall (MonoCompile *cfg, gconstpointer func, MonoInst **args)
2617 {
2618         MonoJitICallInfo *info = mono_find_jit_icall_by_addr (func);
2619
2620         g_assert (info);
2621
2622         return mono_emit_native_call (cfg, mono_icall_get_wrapper (info), info->sig, args);
2623 }
2624
2625 /*
2626  * mono_emit_abs_call:
2627  *
2628  *   Emit a call to the runtime function described by PATCH_TYPE and DATA.
2629  */
2630 inline static MonoInst*
2631 mono_emit_abs_call (MonoCompile *cfg, MonoJumpInfoType patch_type, gconstpointer data, 
2632                                         MonoMethodSignature *sig, MonoInst **args)
2633 {
2634         MonoJumpInfo *ji = mono_patch_info_new (cfg->mempool, 0, patch_type, data);
2635         MonoInst *ins;
2636
2637         /* 
2638          * We pass ji as the call address, the PATCH_INFO_ABS resolving code will
2639          * handle it.
2640          */
2641         if (cfg->abs_patches == NULL)
2642                 cfg->abs_patches = g_hash_table_new (NULL, NULL);
2643         g_hash_table_insert (cfg->abs_patches, ji, ji);
2644         ins = mono_emit_native_call (cfg, ji, sig, args);
2645         ((MonoCallInst*)ins)->fptr_is_patch = TRUE;
2646         return ins;
2647 }
2648
2649 static MonoMethodSignature*
2650 sig_to_rgctx_sig (MonoMethodSignature *sig)
2651 {
2652         // FIXME: memory allocation
2653         MonoMethodSignature *res;
2654         int i;
2655
2656         res = (MonoMethodSignature *)g_malloc (MONO_SIZEOF_METHOD_SIGNATURE + (sig->param_count + 1) * sizeof (MonoType*));
2657         memcpy (res, sig, MONO_SIZEOF_METHOD_SIGNATURE);
2658         res->param_count = sig->param_count + 1;
2659         for (i = 0; i < sig->param_count; ++i)
2660                 res->params [i] = sig->params [i];
2661         res->params [sig->param_count] = &mono_defaults.int_class->this_arg;
2662         return res;
2663 }
2664
2665 /* Make an indirect call to FSIG passing an additional argument */
2666 static MonoInst*
2667 emit_extra_arg_calli (MonoCompile *cfg, MonoMethodSignature *fsig, MonoInst **orig_args, int arg_reg, MonoInst *call_target)
2668 {
2669         MonoMethodSignature *csig;
2670         MonoInst *args_buf [16];
2671         MonoInst **args;
2672         int i, pindex, tmp_reg;
2673
2674         /* Make a call with an rgctx/extra arg */
2675         if (fsig->param_count + 2 < 16)
2676                 args = args_buf;
2677         else
2678                 args = (MonoInst **)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst*) * (fsig->param_count + 2));
2679         pindex = 0;
2680         if (fsig->hasthis)
2681                 args [pindex ++] = orig_args [0];
2682         for (i = 0; i < fsig->param_count; ++i)
2683                 args [pindex ++] = orig_args [fsig->hasthis + i];
2684         tmp_reg = alloc_preg (cfg);
2685         EMIT_NEW_UNALU (cfg, args [pindex], OP_MOVE, tmp_reg, arg_reg);
2686         csig = sig_to_rgctx_sig (fsig);
2687         return mini_emit_calli (cfg, csig, args, call_target, NULL, NULL);
2688 }
2689
2690 /* Emit an indirect call to the function descriptor ADDR */
2691 static MonoInst*
2692 emit_llvmonly_calli (MonoCompile *cfg, MonoMethodSignature *fsig, MonoInst **args, MonoInst *addr)
2693 {
2694         int addr_reg, arg_reg;
2695         MonoInst *call_target;
2696
2697         g_assert (cfg->llvm_only);
2698
2699         /*
2700          * addr points to a <addr, arg> pair, load both of them, and
2701          * make a call to addr, passing arg as an extra arg.
2702          */
2703         addr_reg = alloc_preg (cfg);
2704         EMIT_NEW_LOAD_MEMBASE (cfg, call_target, OP_LOAD_MEMBASE, addr_reg, addr->dreg, 0);
2705         arg_reg = alloc_preg (cfg);
2706         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, arg_reg, addr->dreg, sizeof (gpointer));
2707
2708         return emit_extra_arg_calli (cfg, fsig, args, arg_reg, call_target);
2709 }
2710
2711 static gboolean
2712 direct_icalls_enabled (MonoCompile *cfg)
2713 {
2714         return FALSE;
2715
2716         /* LLVM on amd64 can't handle calls to non-32 bit addresses */
2717 #ifdef TARGET_AMD64
2718         if (cfg->compile_llvm && !cfg->llvm_only)
2719                 return FALSE;
2720 #endif
2721         if (cfg->gen_sdb_seq_points || cfg->disable_direct_icalls)
2722                 return FALSE;
2723         return TRUE;
2724 }
2725
2726 MonoInst*
2727 mono_emit_jit_icall_by_info (MonoCompile *cfg, int il_offset, MonoJitICallInfo *info, MonoInst **args)
2728 {
2729         /*
2730          * Call the jit icall without a wrapper if possible.
2731          * The wrapper is needed for the following reasons:
2732          * - to handle exceptions thrown using mono_raise_exceptions () from the
2733          *   icall function. The EH code needs the lmf frame pushed by the
2734          *   wrapper to be able to unwind back to managed code.
2735          * - to be able to do stack walks for asynchronously suspended
2736          *   threads when debugging.
2737          */
2738         if (info->no_raise && direct_icalls_enabled (cfg)) {
2739                 char *name;
2740                 int costs;
2741
2742                 if (!info->wrapper_method) {
2743                         name = g_strdup_printf ("__icall_wrapper_%s", info->name);
2744                         info->wrapper_method = mono_marshal_get_icall_wrapper (info->sig, name, info->func, TRUE);
2745                         g_free (name);
2746                         mono_memory_barrier ();
2747                 }
2748
2749                 /*
2750                  * Inline the wrapper method, which is basically a call to the C icall, and
2751                  * an exception check.
2752                  */
2753                 costs = inline_method (cfg, info->wrapper_method, NULL,
2754                                                            args, NULL, il_offset, TRUE);
2755                 g_assert (costs > 0);
2756                 g_assert (!MONO_TYPE_IS_VOID (info->sig->ret));
2757
2758                 return args [0];
2759         } else {
2760                 return mono_emit_native_call (cfg, mono_icall_get_wrapper (info), info->sig, args);
2761         }
2762 }
2763  
2764 static MonoInst*
2765 mono_emit_widen_call_res (MonoCompile *cfg, MonoInst *ins, MonoMethodSignature *fsig)
2766 {
2767         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
2768                 if ((fsig->pinvoke || LLVM_ENABLED) && !fsig->ret->byref) {
2769                         int widen_op = -1;
2770
2771                         /* 
2772                          * Native code might return non register sized integers 
2773                          * without initializing the upper bits.
2774                          */
2775                         switch (mono_type_to_load_membase (cfg, fsig->ret)) {
2776                         case OP_LOADI1_MEMBASE:
2777                                 widen_op = OP_ICONV_TO_I1;
2778                                 break;
2779                         case OP_LOADU1_MEMBASE:
2780                                 widen_op = OP_ICONV_TO_U1;
2781                                 break;
2782                         case OP_LOADI2_MEMBASE:
2783                                 widen_op = OP_ICONV_TO_I2;
2784                                 break;
2785                         case OP_LOADU2_MEMBASE:
2786                                 widen_op = OP_ICONV_TO_U2;
2787                                 break;
2788                         default:
2789                                 break;
2790                         }
2791
2792                         if (widen_op != -1) {
2793                                 int dreg = alloc_preg (cfg);
2794                                 MonoInst *widen;
2795
2796                                 EMIT_NEW_UNALU (cfg, widen, widen_op, dreg, ins->dreg);
2797                                 widen->type = ins->type;
2798                                 ins = widen;
2799                         }
2800                 }
2801         }
2802
2803         return ins;
2804 }
2805
2806
2807 static void
2808 emit_method_access_failure (MonoCompile *cfg, MonoMethod *caller, MonoMethod *callee)
2809 {
2810         MonoInst *args [16];
2811
2812         args [0] = emit_get_rgctx_method (cfg, mono_method_check_context_used (caller), caller, MONO_RGCTX_INFO_METHOD);
2813         args [1] = emit_get_rgctx_method (cfg, mono_method_check_context_used (callee), callee, MONO_RGCTX_INFO_METHOD);
2814
2815         mono_emit_jit_icall (cfg, mono_throw_method_access, args);
2816 }
2817
2818 MonoMethod*
2819 mini_get_memcpy_method (void)
2820 {
2821         static MonoMethod *memcpy_method = NULL;
2822         if (!memcpy_method) {
2823                 memcpy_method = mono_class_get_method_from_name (mono_defaults.string_class, "memcpy", 3);
2824                 if (!memcpy_method)
2825                         g_error ("Old corlib found. Install a new one");
2826         }
2827         return memcpy_method;
2828 }
2829
2830 static void
2831 create_write_barrier_bitmap (MonoCompile *cfg, MonoClass *klass, unsigned *wb_bitmap, int offset)
2832 {
2833         MonoClassField *field;
2834         gpointer iter = NULL;
2835
2836         while ((field = mono_class_get_fields (klass, &iter))) {
2837                 int foffset;
2838
2839                 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
2840                         continue;
2841                 foffset = klass->valuetype ? field->offset - sizeof (MonoObject): field->offset;
2842                 if (mini_type_is_reference (mono_field_get_type (field))) {
2843                         g_assert ((foffset % SIZEOF_VOID_P) == 0);
2844                         *wb_bitmap |= 1 << ((offset + foffset) / SIZEOF_VOID_P);
2845                 } else {
2846                         MonoClass *field_class = mono_class_from_mono_type (field->type);
2847                         if (field_class->has_references)
2848                                 create_write_barrier_bitmap (cfg, field_class, wb_bitmap, offset + foffset);
2849                 }
2850         }
2851 }
2852
2853 void
2854 mini_emit_write_barrier (MonoCompile *cfg, MonoInst *ptr, MonoInst *value)
2855 {
2856         int card_table_shift_bits;
2857         gpointer card_table_mask;
2858         guint8 *card_table;
2859         MonoInst *dummy_use;
2860         int nursery_shift_bits;
2861         size_t nursery_size;
2862
2863         if (!cfg->gen_write_barriers)
2864                 return;
2865
2866         card_table = mono_gc_get_card_table (&card_table_shift_bits, &card_table_mask);
2867
2868         mono_gc_get_nursery (&nursery_shift_bits, &nursery_size);
2869
2870         if (cfg->backend->have_card_table_wb && !cfg->compile_aot && card_table && nursery_shift_bits > 0 && !COMPILE_LLVM (cfg)) {
2871                 MonoInst *wbarrier;
2872
2873                 MONO_INST_NEW (cfg, wbarrier, OP_CARD_TABLE_WBARRIER);
2874                 wbarrier->sreg1 = ptr->dreg;
2875                 wbarrier->sreg2 = value->dreg;
2876                 MONO_ADD_INS (cfg->cbb, wbarrier);
2877         } else if (card_table) {
2878                 int offset_reg = alloc_preg (cfg);
2879                 int card_reg;
2880                 MonoInst *ins;
2881
2882                 /*
2883                  * We emit a fast light weight write barrier. This always marks cards as in the concurrent
2884                  * collector case, so, for the serial collector, it might slightly slow down nursery
2885                  * collections. We also expect that the host system and the target system have the same card
2886                  * table configuration, which is the case if they have the same pointer size.
2887                  */
2888
2889                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHR_UN_IMM, offset_reg, ptr->dreg, card_table_shift_bits);
2890                 if (card_table_mask)
2891                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PAND_IMM, offset_reg, offset_reg, card_table_mask);
2892
2893                 /*We can't use PADD_IMM since the cardtable might end up in high addresses and amd64 doesn't support
2894                  * IMM's larger than 32bits.
2895                  */
2896                 ins = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_GC_CARD_TABLE_ADDR, NULL);
2897                 card_reg = ins->dreg;
2898
2899                 MONO_EMIT_NEW_BIALU (cfg, OP_PADD, offset_reg, offset_reg, card_reg);
2900                 MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STOREI1_MEMBASE_IMM, offset_reg, 0, 1);
2901         } else {
2902                 MonoMethod *write_barrier = mono_gc_get_write_barrier ();
2903                 mono_emit_method_call (cfg, write_barrier, &ptr, NULL);
2904         }
2905
2906         EMIT_NEW_DUMMY_USE (cfg, dummy_use, value);
2907 }
2908
2909 gboolean
2910 mini_emit_wb_aware_memcpy (MonoCompile *cfg, MonoClass *klass, MonoInst *iargs[4], int size, int align)
2911 {
2912         int dest_ptr_reg, tmp_reg, destreg, srcreg, offset;
2913         unsigned need_wb = 0;
2914
2915         if (align == 0)
2916                 align = 4;
2917
2918         /*types with references can't have alignment smaller than sizeof(void*) */
2919         if (align < SIZEOF_VOID_P)
2920                 return FALSE;
2921
2922         if (size > 5 * SIZEOF_VOID_P)
2923                 return FALSE;
2924
2925         create_write_barrier_bitmap (cfg, klass, &need_wb, 0);
2926
2927         destreg = iargs [0]->dreg;
2928         srcreg = iargs [1]->dreg;
2929         offset = 0;
2930
2931         dest_ptr_reg = alloc_preg (cfg);
2932         tmp_reg = alloc_preg (cfg);
2933
2934         /*tmp = dreg*/
2935         EMIT_NEW_UNALU (cfg, iargs [0], OP_MOVE, dest_ptr_reg, destreg);
2936
2937         while (size >= SIZEOF_VOID_P) {
2938                 MonoInst *load_inst;
2939                 MONO_INST_NEW (cfg, load_inst, OP_LOAD_MEMBASE);
2940                 load_inst->dreg = tmp_reg;
2941                 load_inst->inst_basereg = srcreg;
2942                 load_inst->inst_offset = offset;
2943                 MONO_ADD_INS (cfg->cbb, load_inst);
2944
2945                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, dest_ptr_reg, 0, tmp_reg);
2946
2947                 if (need_wb & 0x1)
2948                         mini_emit_write_barrier (cfg, iargs [0], load_inst);
2949
2950                 offset += SIZEOF_VOID_P;
2951                 size -= SIZEOF_VOID_P;
2952                 need_wb >>= 1;
2953
2954                 /*tmp += sizeof (void*)*/
2955                 if (size >= SIZEOF_VOID_P) {
2956                         NEW_BIALU_IMM (cfg, iargs [0], OP_PADD_IMM, dest_ptr_reg, dest_ptr_reg, SIZEOF_VOID_P);
2957                         MONO_ADD_INS (cfg->cbb, iargs [0]);
2958                 }
2959         }
2960
2961         /* Those cannot be references since size < sizeof (void*) */
2962         while (size >= 4) {
2963                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, tmp_reg, srcreg, offset);
2964                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI4_MEMBASE_REG, destreg, offset, tmp_reg);
2965                 offset += 4;
2966                 size -= 4;
2967         }
2968
2969         while (size >= 2) {
2970                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI2_MEMBASE, tmp_reg, srcreg, offset);
2971                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI2_MEMBASE_REG, destreg, offset, tmp_reg);
2972                 offset += 2;
2973                 size -= 2;
2974         }
2975
2976         while (size >= 1) {
2977                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI1_MEMBASE, tmp_reg, srcreg, offset);
2978                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI1_MEMBASE_REG, destreg, offset, tmp_reg);
2979                 offset += 1;
2980                 size -= 1;
2981         }
2982
2983         return TRUE;
2984 }
2985
2986 /*
2987  * Emit code to copy a valuetype of type @klass whose address is stored in
2988  * @src->dreg to memory whose address is stored at @dest->dreg.
2989  */
2990 void
2991 mini_emit_stobj (MonoCompile *cfg, MonoInst *dest, MonoInst *src, MonoClass *klass, gboolean native)
2992 {
2993         MonoInst *iargs [4];
2994         int n;
2995         guint32 align = 0;
2996         MonoMethod *memcpy_method;
2997         MonoInst *size_ins = NULL;
2998         MonoInst *memcpy_ins = NULL;
2999
3000         g_assert (klass);
3001         if (cfg->gshared)
3002                 klass = mono_class_from_mono_type (mini_get_underlying_type (&klass->byval_arg));
3003
3004         /*
3005          * This check breaks with spilled vars... need to handle it during verification anyway.
3006          * g_assert (klass && klass == src->klass && klass == dest->klass);
3007          */
3008
3009         if (mini_is_gsharedvt_klass (klass)) {
3010                 g_assert (!native);
3011                 size_ins = mini_emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_VALUE_SIZE);
3012                 memcpy_ins = mini_emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_MEMCPY);
3013         }
3014
3015         if (native)
3016                 n = mono_class_native_size (klass, &align);
3017         else
3018                 n = mono_class_value_size (klass, &align);
3019
3020         if (!align)
3021                 align = SIZEOF_VOID_P;
3022         /* if native is true there should be no references in the struct */
3023         if (cfg->gen_write_barriers && (klass->has_references || size_ins) && !native) {
3024                 /* Avoid barriers when storing to the stack */
3025                 if (!((dest->opcode == OP_ADD_IMM && dest->sreg1 == cfg->frame_reg) ||
3026                           (dest->opcode == OP_LDADDR))) {
3027                         int context_used;
3028
3029                         iargs [0] = dest;
3030                         iargs [1] = src;
3031
3032                         context_used = mini_class_check_context_used (cfg, klass);
3033
3034                         /* It's ok to intrinsify under gsharing since shared code types are layout stable. */
3035                         if (!size_ins && (cfg->opt & MONO_OPT_INTRINS) && mini_emit_wb_aware_memcpy (cfg, klass, iargs, n, align)) {
3036                                 return;
3037                         } else if (size_ins || align < SIZEOF_VOID_P) {
3038                                 if (context_used) {
3039                                         iargs [2] = mini_emit_get_rgctx_klass (cfg, context_used, klass, MONO_RGCTX_INFO_KLASS);
3040                                 }  else {
3041                                         iargs [2] = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_CLASS, klass);
3042                                         if (!cfg->compile_aot)
3043                                                 mono_class_compute_gc_descriptor (klass);
3044                                 }
3045                                 if (size_ins)
3046                                         mono_emit_jit_icall (cfg, mono_gsharedvt_value_copy, iargs);
3047                                 else
3048                                         mono_emit_jit_icall (cfg, mono_value_copy, iargs);
3049                         } else {
3050                                 /* We don't unroll more than 5 stores to avoid code bloat. */
3051                                 /*This is harmless and simplify mono_gc_get_range_copy_func */
3052                                 n += (SIZEOF_VOID_P - 1);
3053                                 n &= ~(SIZEOF_VOID_P - 1);
3054
3055                                 EMIT_NEW_ICONST (cfg, iargs [2], n);
3056                                 mono_emit_jit_icall (cfg, mono_gc_get_range_copy_func (), iargs);
3057                         }
3058                 }
3059         }
3060
3061         if (!size_ins && (cfg->opt & MONO_OPT_INTRINS) && n <= sizeof (gpointer) * 8) {
3062                 /* FIXME: Optimize the case when src/dest is OP_LDADDR */
3063                 mini_emit_memcpy (cfg, dest->dreg, 0, src->dreg, 0, n, align);
3064         } else {
3065                 iargs [0] = dest;
3066                 iargs [1] = src;
3067                 if (size_ins)
3068                         iargs [2] = size_ins;
3069                 else
3070                         EMIT_NEW_ICONST (cfg, iargs [2], n);
3071                 
3072                 memcpy_method = mini_get_memcpy_method ();
3073                 if (memcpy_ins)
3074                         mini_emit_calli (cfg, mono_method_signature (memcpy_method), iargs, memcpy_ins, NULL, NULL);
3075                 else
3076                         mono_emit_method_call (cfg, memcpy_method, iargs, NULL);
3077         }
3078 }
3079
3080 MonoMethod*
3081 mini_get_memset_method (void)
3082 {
3083         static MonoMethod *memset_method = NULL;
3084         if (!memset_method) {
3085                 memset_method = mono_class_get_method_from_name (mono_defaults.string_class, "memset", 3);
3086                 if (!memset_method)
3087                         g_error ("Old corlib found. Install a new one");
3088         }
3089         return memset_method;
3090 }
3091
3092 void
3093 mini_emit_initobj (MonoCompile *cfg, MonoInst *dest, const guchar *ip, MonoClass *klass)
3094 {
3095         MonoInst *iargs [3];
3096         int n;
3097         guint32 align;
3098         MonoMethod *memset_method;
3099         MonoInst *size_ins = NULL;
3100         MonoInst *bzero_ins = NULL;
3101         static MonoMethod *bzero_method;
3102
3103         /* FIXME: Optimize this for the case when dest is an LDADDR */
3104         mono_class_init (klass);
3105         if (mini_is_gsharedvt_klass (klass)) {
3106                 size_ins = mini_emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_VALUE_SIZE);
3107                 bzero_ins = mini_emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_BZERO);
3108                 if (!bzero_method)
3109                         bzero_method = mono_class_get_method_from_name (mono_defaults.string_class, "bzero_aligned_1", 2);
3110                 g_assert (bzero_method);
3111                 iargs [0] = dest;
3112                 iargs [1] = size_ins;
3113                 mini_emit_calli (cfg, mono_method_signature (bzero_method), iargs, bzero_ins, NULL, NULL);
3114                 return;
3115         }
3116
3117         klass = mono_class_from_mono_type (mini_get_underlying_type (&klass->byval_arg));
3118
3119         n = mono_class_value_size (klass, &align);
3120
3121         if (n <= sizeof (gpointer) * 8) {
3122                 mini_emit_memset (cfg, dest->dreg, 0, n, 0, align);
3123         }
3124         else {
3125                 memset_method = mini_get_memset_method ();
3126                 iargs [0] = dest;
3127                 EMIT_NEW_ICONST (cfg, iargs [1], 0);
3128                 EMIT_NEW_ICONST (cfg, iargs [2], n);
3129                 mono_emit_method_call (cfg, memset_method, iargs, NULL);
3130         }
3131 }
3132
3133 /*
3134  * emit_get_rgctx:
3135  *
3136  *   Emit IR to return either the this pointer for instance method,
3137  * or the mrgctx for static methods.
3138  */
3139 static MonoInst*
3140 emit_get_rgctx (MonoCompile *cfg, MonoMethod *method, int context_used)
3141 {
3142         MonoInst *this_ins = NULL;
3143
3144         g_assert (cfg->gshared);
3145
3146         if (!(method->flags & METHOD_ATTRIBUTE_STATIC) &&
3147                         !(context_used & MONO_GENERIC_CONTEXT_USED_METHOD) &&
3148                 !method->klass->valuetype)
3149                 EMIT_NEW_VARLOAD (cfg, this_ins, cfg->this_arg, &mono_defaults.object_class->byval_arg);
3150
3151         if (context_used & MONO_GENERIC_CONTEXT_USED_METHOD) {
3152                 MonoInst *mrgctx_loc, *mrgctx_var;
3153
3154                 g_assert (!this_ins);
3155                 g_assert (method->is_inflated && mono_method_get_context (method)->method_inst);
3156
3157                 mrgctx_loc = mono_get_vtable_var (cfg);
3158                 EMIT_NEW_TEMPLOAD (cfg, mrgctx_var, mrgctx_loc->inst_c0);
3159
3160                 return mrgctx_var;
3161         } else if (MONO_CLASS_IS_INTERFACE (cfg->method->klass)) {
3162                 MonoInst *mrgctx_loc, *mrgctx_var;
3163
3164                 /* Default interface methods need an mrgctx since the vtabke at runtime points at an implementing class */
3165                 mrgctx_loc = mono_get_vtable_var (cfg);
3166                 EMIT_NEW_TEMPLOAD (cfg, mrgctx_var, mrgctx_loc->inst_c0);
3167
3168                 g_assert (mono_method_needs_static_rgctx_invoke (cfg->method, TRUE));
3169
3170                 return mrgctx_var;
3171         } else if (method->flags & METHOD_ATTRIBUTE_STATIC || method->klass->valuetype) {
3172                 MonoInst *vtable_loc, *vtable_var;
3173
3174                 g_assert (!this_ins);
3175
3176                 vtable_loc = mono_get_vtable_var (cfg);
3177                 EMIT_NEW_TEMPLOAD (cfg, vtable_var, vtable_loc->inst_c0);
3178
3179                 if (method->is_inflated && mono_method_get_context (method)->method_inst) {
3180                         MonoInst *mrgctx_var = vtable_var;
3181                         int vtable_reg;
3182
3183                         vtable_reg = alloc_preg (cfg);
3184                         EMIT_NEW_LOAD_MEMBASE (cfg, vtable_var, OP_LOAD_MEMBASE, vtable_reg, mrgctx_var->dreg, MONO_STRUCT_OFFSET (MonoMethodRuntimeGenericContext, class_vtable));
3185                         vtable_var->type = STACK_PTR;
3186                 }
3187
3188                 return vtable_var;
3189         } else {
3190                 MonoInst *ins;
3191                 int vtable_reg;
3192         
3193                 vtable_reg = alloc_preg (cfg);
3194                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, vtable_reg, this_ins->dreg, MONO_STRUCT_OFFSET (MonoObject, vtable));
3195                 return ins;
3196         }
3197 }
3198
3199 static MonoJumpInfoRgctxEntry *
3200 mono_patch_info_rgctx_entry_new (MonoMemPool *mp, MonoMethod *method, gboolean in_mrgctx, MonoJumpInfoType patch_type, gconstpointer patch_data, MonoRgctxInfoType info_type)
3201 {
3202         MonoJumpInfoRgctxEntry *res = (MonoJumpInfoRgctxEntry *)mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoRgctxEntry));
3203         res->method = method;
3204         res->in_mrgctx = in_mrgctx;
3205         res->data = (MonoJumpInfo *)mono_mempool_alloc0 (mp, sizeof (MonoJumpInfo));
3206         res->data->type = patch_type;
3207         res->data->data.target = patch_data;
3208         res->info_type = info_type;
3209
3210         return res;
3211 }
3212
3213 static inline MonoInst*
3214 emit_rgctx_fetch_inline (MonoCompile *cfg, MonoInst *rgctx, MonoJumpInfoRgctxEntry *entry)
3215 {
3216         MonoInst *args [16];
3217         MonoInst *call;
3218
3219         // FIXME: No fastpath since the slot is not a compile time constant
3220         args [0] = rgctx;
3221         EMIT_NEW_AOTCONST (cfg, args [1], MONO_PATCH_INFO_RGCTX_SLOT_INDEX, entry);
3222         if (entry->in_mrgctx)
3223                 call = mono_emit_jit_icall (cfg, mono_fill_method_rgctx, args);
3224         else
3225                 call = mono_emit_jit_icall (cfg, mono_fill_class_rgctx, args);
3226         return call;
3227 #if 0
3228         /*
3229          * FIXME: This can be called during decompose, which is a problem since it creates
3230          * new bblocks.
3231          * Also, the fastpath doesn't work since the slot number is dynamically allocated.
3232          */
3233         int i, slot, depth, index, rgctx_reg, val_reg, res_reg;
3234         gboolean mrgctx;
3235         MonoBasicBlock *is_null_bb, *end_bb;
3236         MonoInst *res, *ins, *call;
3237         MonoInst *args[16];
3238
3239         slot = mini_get_rgctx_entry_slot (entry);
3240
3241         mrgctx = MONO_RGCTX_SLOT_IS_MRGCTX (slot);
3242         index = MONO_RGCTX_SLOT_INDEX (slot);
3243         if (mrgctx)
3244                 index += MONO_SIZEOF_METHOD_RUNTIME_GENERIC_CONTEXT / sizeof (gpointer);
3245         for (depth = 0; ; ++depth) {
3246                 int size = mono_class_rgctx_get_array_size (depth, mrgctx);
3247
3248                 if (index < size - 1)
3249                         break;
3250                 index -= size - 1;
3251         }
3252
3253         NEW_BBLOCK (cfg, end_bb);
3254         NEW_BBLOCK (cfg, is_null_bb);
3255
3256         if (mrgctx) {
3257                 rgctx_reg = rgctx->dreg;
3258         } else {
3259                 rgctx_reg = alloc_preg (cfg);
3260
3261                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, rgctx_reg, rgctx->dreg, MONO_STRUCT_OFFSET (MonoVTable, runtime_generic_context));
3262                 // FIXME: Avoid this check by allocating the table when the vtable is created etc.
3263                 NEW_BBLOCK (cfg, is_null_bb);
3264
3265                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, rgctx_reg, 0);
3266                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, is_null_bb);
3267         }
3268
3269         for (i = 0; i < depth; ++i) {
3270                 int array_reg = alloc_preg (cfg);
3271
3272                 /* load ptr to next array */
3273                 if (mrgctx && i == 0)
3274                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, array_reg, rgctx_reg, MONO_SIZEOF_METHOD_RUNTIME_GENERIC_CONTEXT);
3275                 else
3276                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, array_reg, rgctx_reg, 0);
3277                 rgctx_reg = array_reg;
3278                 /* is the ptr null? */
3279                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, rgctx_reg, 0);
3280                 /* if yes, jump to actual trampoline */
3281                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, is_null_bb);
3282         }
3283
3284         /* fetch slot */
3285         val_reg = alloc_preg (cfg);
3286         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, val_reg, rgctx_reg, (index + 1) * sizeof (gpointer));
3287         /* is the slot null? */
3288         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, val_reg, 0);
3289         /* if yes, jump to actual trampoline */
3290         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, is_null_bb);
3291
3292         /* Fastpath */
3293         res_reg = alloc_preg (cfg);
3294         MONO_INST_NEW (cfg, ins, OP_MOVE);
3295         ins->dreg = res_reg;
3296         ins->sreg1 = val_reg;
3297         MONO_ADD_INS (cfg->cbb, ins);
3298         res = ins;
3299         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
3300
3301         /* Slowpath */
3302         MONO_START_BB (cfg, is_null_bb);
3303         args [0] = rgctx;
3304         EMIT_NEW_ICONST (cfg, args [1], index);
3305         if (mrgctx)
3306                 call = mono_emit_jit_icall (cfg, mono_fill_method_rgctx, args);
3307         else
3308                 call = mono_emit_jit_icall (cfg, mono_fill_class_rgctx, args);
3309         MONO_INST_NEW (cfg, ins, OP_MOVE);
3310         ins->dreg = res_reg;
3311         ins->sreg1 = call->dreg;
3312         MONO_ADD_INS (cfg->cbb, ins);
3313         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
3314
3315         MONO_START_BB (cfg, end_bb);
3316
3317         return res;
3318 #endif
3319 }
3320
3321 /*
3322  * emit_rgctx_fetch:
3323  *
3324  *   Emit IR to load the value of the rgctx entry ENTRY from the rgctx
3325  * given by RGCTX.
3326  */
3327 static inline MonoInst*
3328 emit_rgctx_fetch (MonoCompile *cfg, MonoInst *rgctx, MonoJumpInfoRgctxEntry *entry)
3329 {
3330         if (cfg->llvm_only)
3331                 return emit_rgctx_fetch_inline (cfg, rgctx, entry);
3332         else
3333                 return mono_emit_abs_call (cfg, MONO_PATCH_INFO_RGCTX_FETCH, entry, helper_sig_rgctx_lazy_fetch_trampoline, &rgctx);
3334 }
3335
3336 MonoInst*
3337 mini_emit_get_rgctx_klass (MonoCompile *cfg, int context_used,
3338                                           MonoClass *klass, MonoRgctxInfoType rgctx_type)
3339 {
3340         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);
3341         MonoInst *rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3342
3343         return emit_rgctx_fetch (cfg, rgctx, entry);
3344 }
3345
3346 static MonoInst*
3347 emit_get_rgctx_sig (MonoCompile *cfg, int context_used,
3348                                         MonoMethodSignature *sig, MonoRgctxInfoType rgctx_type)
3349 {
3350         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);
3351         MonoInst *rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3352
3353         return emit_rgctx_fetch (cfg, rgctx, entry);
3354 }
3355
3356 static MonoInst*
3357 emit_get_rgctx_gsharedvt_call (MonoCompile *cfg, int context_used,
3358                                                            MonoMethodSignature *sig, MonoMethod *cmethod, MonoRgctxInfoType rgctx_type)
3359 {
3360         MonoJumpInfoGSharedVtCall *call_info;
3361         MonoJumpInfoRgctxEntry *entry;
3362         MonoInst *rgctx;
3363
3364         call_info = (MonoJumpInfoGSharedVtCall *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoJumpInfoGSharedVtCall));
3365         call_info->sig = sig;
3366         call_info->method = cmethod;
3367
3368         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);
3369         rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3370
3371         return emit_rgctx_fetch (cfg, rgctx, entry);
3372 }
3373
3374 /*
3375  * emit_get_rgctx_virt_method:
3376  *
3377  *   Return data for method VIRT_METHOD for a receiver of type KLASS.
3378  */
3379 static MonoInst*
3380 emit_get_rgctx_virt_method (MonoCompile *cfg, int context_used,
3381                                                         MonoClass *klass, MonoMethod *virt_method, MonoRgctxInfoType rgctx_type)
3382 {
3383         MonoJumpInfoVirtMethod *info;
3384         MonoJumpInfoRgctxEntry *entry;
3385         MonoInst *rgctx;
3386
3387         info = (MonoJumpInfoVirtMethod *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoJumpInfoVirtMethod));
3388         info->klass = klass;
3389         info->method = virt_method;
3390
3391         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);
3392         rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3393
3394         return emit_rgctx_fetch (cfg, rgctx, entry);
3395 }
3396
3397 static MonoInst*
3398 emit_get_rgctx_gsharedvt_method (MonoCompile *cfg, int context_used,
3399                                                                  MonoMethod *cmethod, MonoGSharedVtMethodInfo *info)
3400 {
3401         MonoJumpInfoRgctxEntry *entry;
3402         MonoInst *rgctx;
3403
3404         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);
3405         rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3406
3407         return emit_rgctx_fetch (cfg, rgctx, entry);
3408 }
3409
3410 /*
3411  * emit_get_rgctx_method:
3412  *
3413  *   Emit IR to load the property RGCTX_TYPE of CMETHOD. If context_used is 0, emit
3414  * normal constants, else emit a load from the rgctx.
3415  */
3416 static MonoInst*
3417 emit_get_rgctx_method (MonoCompile *cfg, int context_used,
3418                                            MonoMethod *cmethod, MonoRgctxInfoType rgctx_type)
3419 {
3420         if (!context_used) {
3421                 MonoInst *ins;
3422
3423                 switch (rgctx_type) {
3424                 case MONO_RGCTX_INFO_METHOD:
3425                         EMIT_NEW_METHODCONST (cfg, ins, cmethod);
3426                         return ins;
3427                 case MONO_RGCTX_INFO_METHOD_RGCTX:
3428                         EMIT_NEW_METHOD_RGCTX_CONST (cfg, ins, cmethod);
3429                         return ins;
3430                 default:
3431                         g_assert_not_reached ();
3432                 }
3433         } else {
3434                 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);
3435                 MonoInst *rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3436
3437                 return emit_rgctx_fetch (cfg, rgctx, entry);
3438         }
3439 }
3440
3441 static MonoInst*
3442 emit_get_rgctx_field (MonoCompile *cfg, int context_used,
3443                                           MonoClassField *field, MonoRgctxInfoType rgctx_type)
3444 {
3445         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);
3446         MonoInst *rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3447
3448         return emit_rgctx_fetch (cfg, rgctx, entry);
3449 }
3450
3451 static int
3452 get_gsharedvt_info_slot (MonoCompile *cfg, gpointer data, MonoRgctxInfoType rgctx_type)
3453 {
3454         MonoGSharedVtMethodInfo *info = cfg->gsharedvt_info;
3455         MonoRuntimeGenericContextInfoTemplate *template_;
3456         int i, idx;
3457
3458         g_assert (info);
3459
3460         for (i = 0; i < info->num_entries; ++i) {
3461                 MonoRuntimeGenericContextInfoTemplate *otemplate = &info->entries [i];
3462
3463                 if (otemplate->info_type == rgctx_type && otemplate->data == data && rgctx_type != MONO_RGCTX_INFO_LOCAL_OFFSET)
3464                         return i;
3465         }
3466
3467         if (info->num_entries == info->count_entries) {
3468                 MonoRuntimeGenericContextInfoTemplate *new_entries;
3469                 int new_count_entries = info->count_entries ? info->count_entries * 2 : 16;
3470
3471                 new_entries = (MonoRuntimeGenericContextInfoTemplate *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoRuntimeGenericContextInfoTemplate) * new_count_entries);
3472
3473                 memcpy (new_entries, info->entries, sizeof (MonoRuntimeGenericContextInfoTemplate) * info->count_entries);
3474                 info->entries = new_entries;
3475                 info->count_entries = new_count_entries;
3476         }
3477
3478         idx = info->num_entries;
3479         template_ = &info->entries [idx];
3480         template_->info_type = rgctx_type;
3481         template_->data = data;
3482
3483         info->num_entries ++;
3484
3485         return idx;
3486 }
3487
3488 /*
3489  * emit_get_gsharedvt_info:
3490  *
3491  *   This is similar to emit_get_rgctx_.., but loads the data from the gsharedvt info var instead of calling an rgctx fetch trampoline.
3492  */
3493 static MonoInst*
3494 emit_get_gsharedvt_info (MonoCompile *cfg, gpointer data, MonoRgctxInfoType rgctx_type)
3495 {
3496         MonoInst *ins;
3497         int idx, dreg;
3498
3499         idx = get_gsharedvt_info_slot (cfg, data, rgctx_type);
3500         /* Load info->entries [idx] */
3501         dreg = alloc_preg (cfg);
3502         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, dreg, cfg->gsharedvt_info_var->dreg, MONO_STRUCT_OFFSET (MonoGSharedVtMethodRuntimeInfo, entries) + (idx * sizeof (gpointer)));
3503
3504         return ins;
3505 }
3506
3507 MonoInst*
3508 mini_emit_get_gsharedvt_info_klass (MonoCompile *cfg, MonoClass *klass, MonoRgctxInfoType rgctx_type)
3509 {
3510         return emit_get_gsharedvt_info (cfg, &klass->byval_arg, rgctx_type);
3511 }
3512
3513 /*
3514  * On return the caller must check @klass for load errors.
3515  */
3516 static void
3517 emit_class_init (MonoCompile *cfg, MonoClass *klass)
3518 {
3519         MonoInst *vtable_arg;
3520         int context_used;
3521
3522         context_used = mini_class_check_context_used (cfg, klass);
3523
3524         if (context_used) {
3525                 vtable_arg = mini_emit_get_rgctx_klass (cfg, context_used,
3526                                                                                    klass, MONO_RGCTX_INFO_VTABLE);
3527         } else {
3528                 MonoVTable *vtable = mono_class_vtable (cfg->domain, klass);
3529
3530                 if (!vtable)
3531                         return;
3532                 EMIT_NEW_VTABLECONST (cfg, vtable_arg, vtable);
3533         }
3534
3535         if (!COMPILE_LLVM (cfg) && cfg->backend->have_op_generic_class_init) {
3536                 MonoInst *ins;
3537
3538                 /*
3539                  * Using an opcode instead of emitting IR here allows the hiding of the call inside the opcode,
3540                  * so this doesn't have to clobber any regs and it doesn't break basic blocks.
3541                  */
3542                 MONO_INST_NEW (cfg, ins, OP_GENERIC_CLASS_INIT);
3543                 ins->sreg1 = vtable_arg->dreg;
3544                 MONO_ADD_INS (cfg->cbb, ins);
3545         } else {
3546                 int inited_reg;
3547                 MonoBasicBlock *inited_bb;
3548                 MonoInst *args [16];
3549
3550                 inited_reg = alloc_ireg (cfg);
3551
3552                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADU1_MEMBASE, inited_reg, vtable_arg->dreg, MONO_STRUCT_OFFSET (MonoVTable, initialized));
3553
3554                 NEW_BBLOCK (cfg, inited_bb);
3555
3556                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, inited_reg, 0);
3557                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBNE_UN, inited_bb);
3558
3559                 args [0] = vtable_arg;
3560                 mono_emit_jit_icall (cfg, mono_generic_class_init, args);
3561
3562                 MONO_START_BB (cfg, inited_bb);
3563         }
3564 }
3565
3566 static void
3567 emit_seq_point (MonoCompile *cfg, MonoMethod *method, guint8* ip, gboolean intr_loc, gboolean nonempty_stack)
3568 {
3569         MonoInst *ins;
3570
3571         if (cfg->gen_seq_points && cfg->method == method) {
3572                 NEW_SEQ_POINT (cfg, ins, ip - cfg->header->code, intr_loc);
3573                 if (nonempty_stack)
3574                         ins->flags |= MONO_INST_NONEMPTY_STACK;
3575                 MONO_ADD_INS (cfg->cbb, ins);
3576         }
3577 }
3578
3579 void
3580 mini_save_cast_details (MonoCompile *cfg, MonoClass *klass, int obj_reg, gboolean null_check)
3581 {
3582         if (mini_get_debug_options ()->better_cast_details) {
3583                 int vtable_reg = alloc_preg (cfg);
3584                 int klass_reg = alloc_preg (cfg);
3585                 MonoBasicBlock *is_null_bb = NULL;
3586                 MonoInst *tls_get;
3587                 int to_klass_reg, context_used;
3588
3589                 if (null_check) {
3590                         NEW_BBLOCK (cfg, is_null_bb);
3591
3592                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, obj_reg, 0);
3593                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, is_null_bb);
3594                 }
3595
3596                 tls_get = mono_create_tls_get (cfg, TLS_KEY_JIT_TLS);
3597                 if (!tls_get) {
3598                         fprintf (stderr, "error: --debug=casts not supported on this platform.\n.");
3599                         exit (1);
3600                 }
3601
3602                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, vtable_reg, obj_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
3603                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, klass));
3604
3605                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, tls_get->dreg, MONO_STRUCT_OFFSET (MonoJitTlsData, class_cast_from), klass_reg);
3606
3607                 context_used = mini_class_check_context_used (cfg, klass);
3608                 if (context_used) {
3609                         MonoInst *class_ins;
3610
3611                         class_ins = mini_emit_get_rgctx_klass (cfg, context_used, klass, MONO_RGCTX_INFO_KLASS);
3612                         to_klass_reg = class_ins->dreg;
3613                 } else {
3614                         to_klass_reg = alloc_preg (cfg);
3615                         MONO_EMIT_NEW_CLASSCONST (cfg, to_klass_reg, klass);
3616                 }
3617                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, tls_get->dreg, MONO_STRUCT_OFFSET (MonoJitTlsData, class_cast_to), to_klass_reg);
3618
3619                 if (null_check)
3620                         MONO_START_BB (cfg, is_null_bb);
3621         }
3622 }
3623
3624 void
3625 mini_reset_cast_details (MonoCompile *cfg)
3626 {
3627         /* Reset the variables holding the cast details */
3628         if (mini_get_debug_options ()->better_cast_details) {
3629                 MonoInst *tls_get = mono_create_tls_get (cfg, TLS_KEY_JIT_TLS);
3630                 /* It is enough to reset the from field */
3631                 MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STORE_MEMBASE_IMM, tls_get->dreg, MONO_STRUCT_OFFSET (MonoJitTlsData, class_cast_from), 0);
3632         }
3633 }
3634
3635 /*
3636  * On return the caller must check @array_class for load errors
3637  */
3638 static void
3639 mini_emit_check_array_type (MonoCompile *cfg, MonoInst *obj, MonoClass *array_class)
3640 {
3641         int vtable_reg = alloc_preg (cfg);
3642         int context_used;
3643
3644         context_used = mini_class_check_context_used (cfg, array_class);
3645
3646         mini_save_cast_details (cfg, array_class, obj->dreg, FALSE);
3647
3648         MONO_EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, vtable_reg, obj->dreg, MONO_STRUCT_OFFSET (MonoObject, vtable));
3649
3650         if (cfg->opt & MONO_OPT_SHARED) {
3651                 int class_reg = alloc_preg (cfg);
3652                 MonoInst *ins;
3653
3654                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, class_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, klass));
3655                 ins = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_CLASS, array_class);
3656                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, class_reg, ins->dreg);
3657         } else if (context_used) {
3658                 MonoInst *vtable_ins;
3659
3660                 vtable_ins = mini_emit_get_rgctx_klass (cfg, context_used, array_class, MONO_RGCTX_INFO_VTABLE);
3661                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, vtable_reg, vtable_ins->dreg);
3662         } else {
3663                 if (cfg->compile_aot) {
3664                         int vt_reg;
3665                         MonoVTable *vtable;
3666
3667                         if (!(vtable = mono_class_vtable (cfg->domain, array_class)))
3668                                 return;
3669                         vt_reg = alloc_preg (cfg);
3670                         MONO_EMIT_NEW_VTABLECONST (cfg, vt_reg, vtable);
3671                         MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, vtable_reg, vt_reg);
3672                 } else {
3673                         MonoVTable *vtable;
3674                         if (!(vtable = mono_class_vtable (cfg->domain, array_class)))
3675                                 return;
3676                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, vtable_reg, vtable);
3677                 }
3678         }
3679         
3680         MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "ArrayTypeMismatchException");
3681
3682         mini_reset_cast_details (cfg);
3683 }
3684
3685 /**
3686  * Handles unbox of a Nullable<T>. If context_used is non zero, then shared 
3687  * generic code is generated.
3688  */
3689 static MonoInst*
3690 handle_unbox_nullable (MonoCompile* cfg, MonoInst* val, MonoClass* klass, int context_used)
3691 {
3692         MonoMethod* method = mono_class_get_method_from_name (klass, "Unbox", 1);
3693
3694         if (context_used) {
3695                 MonoInst *rgctx, *addr;
3696
3697                 /* FIXME: What if the class is shared?  We might not
3698                    have to get the address of the method from the
3699                    RGCTX. */
3700                 addr = emit_get_rgctx_method (cfg, context_used, method,
3701                                                                           MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
3702                 if (cfg->llvm_only) {
3703                         cfg->signatures = g_slist_prepend_mempool (cfg->mempool, cfg->signatures, mono_method_signature (method));
3704                         return emit_llvmonly_calli (cfg, mono_method_signature (method), &val, addr);
3705                 } else {
3706                         rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3707
3708                         return mini_emit_calli (cfg, mono_method_signature (method), &val, addr, NULL, rgctx);
3709                 }
3710         } else {
3711                 gboolean pass_vtable, pass_mrgctx;
3712                 MonoInst *rgctx_arg = NULL;
3713
3714                 check_method_sharing (cfg, method, &pass_vtable, &pass_mrgctx);
3715                 g_assert (!pass_mrgctx);
3716
3717                 if (pass_vtable) {
3718                         MonoVTable *vtable = mono_class_vtable (cfg->domain, method->klass);
3719
3720                         g_assert (vtable);
3721                         EMIT_NEW_VTABLECONST (cfg, rgctx_arg, vtable);
3722                 }
3723
3724                 return mono_emit_method_call_full (cfg, method, NULL, FALSE, &val, NULL, NULL, rgctx_arg);
3725         }
3726 }
3727
3728 static MonoInst*
3729 handle_unbox (MonoCompile *cfg, MonoClass *klass, MonoInst **sp, int context_used)
3730 {
3731         MonoInst *add;
3732         int obj_reg;
3733         int vtable_reg = alloc_dreg (cfg ,STACK_PTR);
3734         int klass_reg = alloc_dreg (cfg ,STACK_PTR);
3735         int eclass_reg = alloc_dreg (cfg ,STACK_PTR);
3736         int rank_reg = alloc_dreg (cfg ,STACK_I4);
3737
3738         obj_reg = sp [0]->dreg;
3739         MONO_EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, vtable_reg, obj_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
3740         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADU1_MEMBASE, rank_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, rank));
3741
3742         /* FIXME: generics */
3743         g_assert (klass->rank == 0);
3744                         
3745         // Check rank == 0
3746         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, rank_reg, 0);
3747         MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "InvalidCastException");
3748
3749         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, klass));
3750         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, eclass_reg, klass_reg, MONO_STRUCT_OFFSET (MonoClass, element_class));
3751
3752         if (context_used) {
3753                 MonoInst *element_class;
3754
3755                 /* This assertion is from the unboxcast insn */
3756                 g_assert (klass->rank == 0);
3757
3758                 element_class = mini_emit_get_rgctx_klass (cfg, context_used,
3759                                 klass, MONO_RGCTX_INFO_ELEMENT_KLASS);
3760
3761                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, eclass_reg, element_class->dreg);
3762                 MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "InvalidCastException");
3763         } else {
3764                 mini_save_cast_details (cfg, klass->element_class, obj_reg, FALSE);
3765                 mini_emit_class_check (cfg, eclass_reg, klass->element_class);
3766                 mini_reset_cast_details (cfg);
3767         }
3768
3769         NEW_BIALU_IMM (cfg, add, OP_ADD_IMM, alloc_dreg (cfg, STACK_MP), obj_reg, sizeof (MonoObject));
3770         MONO_ADD_INS (cfg->cbb, add);
3771         add->type = STACK_MP;
3772         add->klass = klass;
3773
3774         return add;
3775 }
3776
3777 static MonoInst*
3778 handle_unbox_gsharedvt (MonoCompile *cfg, MonoClass *klass, MonoInst *obj)
3779 {
3780         MonoInst *addr, *klass_inst, *is_ref, *args[16];
3781         MonoBasicBlock *is_ref_bb, *is_nullable_bb, *end_bb;
3782         MonoInst *ins;
3783         int dreg, addr_reg;
3784
3785         klass_inst = mini_emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_KLASS);
3786
3787         /* obj */
3788         args [0] = obj;
3789
3790         /* klass */
3791         args [1] = klass_inst;
3792
3793         /* CASTCLASS */
3794         obj = mono_emit_jit_icall (cfg, mono_object_castclass_unbox, args);
3795
3796         NEW_BBLOCK (cfg, is_ref_bb);
3797         NEW_BBLOCK (cfg, is_nullable_bb);
3798         NEW_BBLOCK (cfg, end_bb);
3799         is_ref = mini_emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_CLASS_BOX_TYPE);
3800         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, is_ref->dreg, MONO_GSHAREDVT_BOX_TYPE_REF);
3801         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, is_ref_bb);
3802
3803         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, is_ref->dreg, MONO_GSHAREDVT_BOX_TYPE_NULLABLE);
3804         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, is_nullable_bb);
3805
3806         /* This will contain either the address of the unboxed vtype, or an address of the temporary where the ref is stored */
3807         addr_reg = alloc_dreg (cfg, STACK_MP);
3808
3809         /* Non-ref case */
3810         /* UNBOX */
3811         NEW_BIALU_IMM (cfg, addr, OP_ADD_IMM, addr_reg, obj->dreg, sizeof (MonoObject));
3812         MONO_ADD_INS (cfg->cbb, addr);
3813
3814         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
3815
3816         /* Ref case */
3817         MONO_START_BB (cfg, is_ref_bb);
3818
3819         /* Save the ref to a temporary */
3820         dreg = alloc_ireg (cfg);
3821         EMIT_NEW_VARLOADA_VREG (cfg, addr, dreg, &klass->byval_arg);
3822         addr->dreg = addr_reg;
3823         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, addr->dreg, 0, obj->dreg);
3824         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
3825
3826         /* Nullable case */
3827         MONO_START_BB (cfg, is_nullable_bb);
3828
3829         {
3830                 MonoInst *addr = mini_emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_NULLABLE_CLASS_UNBOX);
3831                 MonoInst *unbox_call;
3832                 MonoMethodSignature *unbox_sig;
3833
3834                 unbox_sig = (MonoMethodSignature *)mono_mempool_alloc0 (cfg->mempool, MONO_SIZEOF_METHOD_SIGNATURE + (1 * sizeof (MonoType *)));
3835                 unbox_sig->ret = &klass->byval_arg;
3836                 unbox_sig->param_count = 1;
3837                 unbox_sig->params [0] = &mono_defaults.object_class->byval_arg;
3838
3839                 if (cfg->llvm_only)
3840                         unbox_call = emit_llvmonly_calli (cfg, unbox_sig, &obj, addr);
3841                 else
3842                         unbox_call = mini_emit_calli (cfg, unbox_sig, &obj, addr, NULL, NULL);
3843
3844                 EMIT_NEW_VARLOADA_VREG (cfg, addr, unbox_call->dreg, &klass->byval_arg);
3845                 addr->dreg = addr_reg;
3846         }
3847
3848         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
3849
3850         /* End */
3851         MONO_START_BB (cfg, end_bb);
3852
3853         /* LDOBJ */
3854         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr_reg, 0);
3855
3856         return ins;
3857 }
3858
3859 /*
3860  * Returns NULL and set the cfg exception on error.
3861  */
3862 static MonoInst*
3863 handle_alloc (MonoCompile *cfg, MonoClass *klass, gboolean for_box, int context_used)
3864 {
3865         MonoInst *iargs [2];
3866         void *alloc_ftn;
3867
3868         if (context_used) {
3869                 MonoInst *data;
3870                 MonoRgctxInfoType rgctx_info;
3871                 MonoInst *iargs [2];
3872                 gboolean known_instance_size = !mini_is_gsharedvt_klass (klass);
3873
3874                 MonoMethod *managed_alloc = mono_gc_get_managed_allocator (klass, for_box, known_instance_size);
3875
3876                 if (cfg->opt & MONO_OPT_SHARED)
3877                         rgctx_info = MONO_RGCTX_INFO_KLASS;
3878                 else
3879                         rgctx_info = MONO_RGCTX_INFO_VTABLE;
3880                 data = mini_emit_get_rgctx_klass (cfg, context_used, klass, rgctx_info);
3881
3882                 if (cfg->opt & MONO_OPT_SHARED) {
3883                         EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
3884                         iargs [1] = data;
3885                         alloc_ftn = ves_icall_object_new;
3886                 } else {
3887                         iargs [0] = data;
3888                         alloc_ftn = ves_icall_object_new_specific;
3889                 }
3890
3891                 if (managed_alloc && !(cfg->opt & MONO_OPT_SHARED)) {
3892                         if (known_instance_size) {
3893                                 int size = mono_class_instance_size (klass);
3894                                 if (size < sizeof (MonoObject))
3895                                         g_error ("Invalid size %d for class %s", size, mono_type_get_full_name (klass));
3896
3897                                 EMIT_NEW_ICONST (cfg, iargs [1], size);
3898                         }
3899                         return mono_emit_method_call (cfg, managed_alloc, iargs, NULL);
3900                 }
3901
3902                 return mono_emit_jit_icall (cfg, alloc_ftn, iargs);
3903         }
3904
3905         if (cfg->opt & MONO_OPT_SHARED) {
3906                 EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
3907                 EMIT_NEW_CLASSCONST (cfg, iargs [1], klass);
3908
3909                 alloc_ftn = ves_icall_object_new;
3910         } else if (cfg->compile_aot && cfg->cbb->out_of_line && klass->type_token && klass->image == mono_defaults.corlib && !mono_class_is_ginst (klass)) {
3911                 /* This happens often in argument checking code, eg. throw new FooException... */
3912                 /* Avoid relocations and save some space by calling a helper function specialized to mscorlib */
3913                 EMIT_NEW_ICONST (cfg, iargs [0], mono_metadata_token_index (klass->type_token));
3914                 return mono_emit_jit_icall (cfg, mono_helper_newobj_mscorlib, iargs);
3915         } else {
3916                 MonoVTable *vtable = mono_class_vtable (cfg->domain, klass);
3917                 MonoMethod *managed_alloc = NULL;
3918                 gboolean pass_lw;
3919
3920                 if (!vtable) {
3921                         mono_cfg_set_exception (cfg, MONO_EXCEPTION_TYPE_LOAD);
3922                         cfg->exception_ptr = klass;
3923                         return NULL;
3924                 }
3925
3926                 managed_alloc = mono_gc_get_managed_allocator (klass, for_box, TRUE);
3927
3928                 if (managed_alloc) {
3929                         int size = mono_class_instance_size (klass);
3930                         if (size < sizeof (MonoObject))
3931                                 g_error ("Invalid size %d for class %s", size, mono_type_get_full_name (klass));
3932
3933                         EMIT_NEW_VTABLECONST (cfg, iargs [0], vtable);
3934                         EMIT_NEW_ICONST (cfg, iargs [1], size);
3935                         return mono_emit_method_call (cfg, managed_alloc, iargs, NULL);
3936                 }
3937                 alloc_ftn = mono_class_get_allocation_ftn (vtable, for_box, &pass_lw);
3938                 if (pass_lw) {
3939                         guint32 lw = vtable->klass->instance_size;
3940                         lw = ((lw + (sizeof (gpointer) - 1)) & ~(sizeof (gpointer) - 1)) / sizeof (gpointer);
3941                         EMIT_NEW_ICONST (cfg, iargs [0], lw);
3942                         EMIT_NEW_VTABLECONST (cfg, iargs [1], vtable);
3943                 }
3944                 else {
3945                         EMIT_NEW_VTABLECONST (cfg, iargs [0], vtable);
3946                 }
3947         }
3948
3949         return mono_emit_jit_icall (cfg, alloc_ftn, iargs);
3950 }
3951         
3952 /*
3953  * Returns NULL and set the cfg exception on error.
3954  */     
3955 static MonoInst*
3956 handle_box (MonoCompile *cfg, MonoInst *val, MonoClass *klass, int context_used)
3957 {
3958         MonoInst *alloc, *ins;
3959
3960         if (mono_class_is_nullable (klass)) {
3961                 MonoMethod* method = mono_class_get_method_from_name (klass, "Box", 1);
3962
3963                 if (context_used) {
3964                         if (cfg->llvm_only && cfg->gsharedvt) {
3965                                 MonoInst *addr = emit_get_rgctx_method (cfg, context_used, method,
3966                                                                                                                 MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
3967                                 return emit_llvmonly_calli (cfg, mono_method_signature (method), &val, addr);
3968                         } else {
3969                                 /* FIXME: What if the class is shared?  We might not
3970                                    have to get the method address from the RGCTX. */
3971                                 MonoInst *addr = emit_get_rgctx_method (cfg, context_used, method,
3972                                                                                                                 MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
3973                                 MonoInst *rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3974
3975                                 return mini_emit_calli (cfg, mono_method_signature (method), &val, addr, NULL, rgctx);
3976                         }
3977                 } else {
3978                         gboolean pass_vtable, pass_mrgctx;
3979                         MonoInst *rgctx_arg = NULL;
3980
3981                         check_method_sharing (cfg, method, &pass_vtable, &pass_mrgctx);
3982                         g_assert (!pass_mrgctx);
3983
3984                         if (pass_vtable) {
3985                                 MonoVTable *vtable = mono_class_vtable (cfg->domain, method->klass);
3986
3987                                 g_assert (vtable);
3988                                 EMIT_NEW_VTABLECONST (cfg, rgctx_arg, vtable);
3989                         }
3990
3991                         return mono_emit_method_call_full (cfg, method, NULL, FALSE, &val, NULL, NULL, rgctx_arg);
3992                 }
3993         }
3994
3995         if (mini_is_gsharedvt_klass (klass)) {
3996                 MonoBasicBlock *is_ref_bb, *is_nullable_bb, *end_bb;
3997                 MonoInst *res, *is_ref, *src_var, *addr;
3998                 int dreg;
3999
4000                 dreg = alloc_ireg (cfg);
4001
4002                 NEW_BBLOCK (cfg, is_ref_bb);
4003                 NEW_BBLOCK (cfg, is_nullable_bb);
4004                 NEW_BBLOCK (cfg, end_bb);
4005                 is_ref = mini_emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_CLASS_BOX_TYPE);
4006                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, is_ref->dreg, MONO_GSHAREDVT_BOX_TYPE_REF);
4007                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, is_ref_bb);
4008
4009                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, is_ref->dreg, MONO_GSHAREDVT_BOX_TYPE_NULLABLE);
4010                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, is_nullable_bb);
4011
4012                 /* Non-ref case */
4013                 alloc = handle_alloc (cfg, klass, TRUE, context_used);
4014                 if (!alloc)
4015                         return NULL;
4016                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, alloc->dreg, sizeof (MonoObject), val->dreg);
4017                 ins->opcode = OP_STOREV_MEMBASE;
4018
4019                 EMIT_NEW_UNALU (cfg, res, OP_MOVE, dreg, alloc->dreg);
4020                 res->type = STACK_OBJ;
4021                 res->klass = klass;
4022                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
4023                 
4024                 /* Ref case */
4025                 MONO_START_BB (cfg, is_ref_bb);
4026
4027                 /* val is a vtype, so has to load the value manually */
4028                 src_var = get_vreg_to_inst (cfg, val->dreg);
4029                 if (!src_var)
4030                         src_var = mono_compile_create_var_for_vreg (cfg, &klass->byval_arg, OP_LOCAL, val->dreg);
4031                 EMIT_NEW_VARLOADA (cfg, addr, src_var, src_var->inst_vtype);
4032                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, dreg, addr->dreg, 0);
4033                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
4034
4035                 /* Nullable case */
4036                 MONO_START_BB (cfg, is_nullable_bb);
4037
4038                 {
4039                         MonoInst *addr = mini_emit_get_gsharedvt_info_klass (cfg, klass,
4040                                                                                                         MONO_RGCTX_INFO_NULLABLE_CLASS_BOX);
4041                         MonoInst *box_call;
4042                         MonoMethodSignature *box_sig;
4043
4044                         /*
4045                          * klass is Nullable<T>, need to call Nullable<T>.Box () using a gsharedvt signature, but we cannot
4046                          * construct that method at JIT time, so have to do things by hand.
4047                          */
4048                         box_sig = (MonoMethodSignature *)mono_mempool_alloc0 (cfg->mempool, MONO_SIZEOF_METHOD_SIGNATURE + (1 * sizeof (MonoType *)));
4049                         box_sig->ret = &mono_defaults.object_class->byval_arg;
4050                         box_sig->param_count = 1;
4051                         box_sig->params [0] = &klass->byval_arg;
4052
4053                         if (cfg->llvm_only)
4054                                 box_call = emit_llvmonly_calli (cfg, box_sig, &val, addr);
4055                         else
4056                                 box_call = mini_emit_calli (cfg, box_sig, &val, addr, NULL, NULL);
4057                         EMIT_NEW_UNALU (cfg, res, OP_MOVE, dreg, box_call->dreg);
4058                         res->type = STACK_OBJ;
4059                         res->klass = klass;
4060                 }
4061
4062                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
4063
4064                 MONO_START_BB (cfg, end_bb);
4065
4066                 return res;
4067         } else {
4068                 alloc = handle_alloc (cfg, klass, TRUE, context_used);
4069                 if (!alloc)
4070                         return NULL;
4071
4072                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, alloc->dreg, sizeof (MonoObject), val->dreg);
4073                 return alloc;
4074         }
4075 }
4076
4077 static GHashTable* direct_icall_type_hash;
4078
4079 static gboolean
4080 icall_is_direct_callable (MonoCompile *cfg, MonoMethod *cmethod)
4081 {
4082         /* LLVM on amd64 can't handle calls to non-32 bit addresses */
4083         if (!direct_icalls_enabled (cfg))
4084                 return FALSE;
4085
4086         /*
4087          * An icall is directly callable if it doesn't directly or indirectly call mono_raise_exception ().
4088          * Whitelist a few icalls for now.
4089          */
4090         if (!direct_icall_type_hash) {
4091                 GHashTable *h = g_hash_table_new (g_str_hash, g_str_equal);
4092
4093                 g_hash_table_insert (h, (char*)"Decimal", GUINT_TO_POINTER (1));
4094                 g_hash_table_insert (h, (char*)"Number", GUINT_TO_POINTER (1));
4095                 g_hash_table_insert (h, (char*)"Buffer", GUINT_TO_POINTER (1));
4096                 g_hash_table_insert (h, (char*)"Monitor", GUINT_TO_POINTER (1));
4097                 mono_memory_barrier ();
4098                 direct_icall_type_hash = h;
4099         }
4100
4101         if (cmethod->klass == mono_defaults.math_class)
4102                 return TRUE;
4103         /* No locking needed */
4104         if (cmethod->klass->image == mono_defaults.corlib && g_hash_table_lookup (direct_icall_type_hash, cmethod->klass->name))
4105                 return TRUE;
4106         return FALSE;
4107 }
4108
4109 static gboolean
4110 method_needs_stack_walk (MonoCompile *cfg, MonoMethod *cmethod)
4111 {
4112         if (cmethod->klass == mono_defaults.systemtype_class) {
4113                 if (!strcmp (cmethod->name, "GetType"))
4114                         return TRUE;
4115         }
4116         return FALSE;
4117 }
4118
4119 static G_GNUC_UNUSED MonoInst*
4120 handle_enum_has_flag (MonoCompile *cfg, MonoClass *klass, MonoInst *enum_this, MonoInst *enum_flag)
4121 {
4122         MonoType *enum_type = mono_type_get_underlying_type (&klass->byval_arg);
4123         guint32 load_opc = mono_type_to_load_membase (cfg, enum_type);
4124         gboolean is_i4;
4125
4126         switch (enum_type->type) {
4127         case MONO_TYPE_I8:
4128         case MONO_TYPE_U8:
4129 #if SIZEOF_REGISTER == 8
4130         case MONO_TYPE_I:
4131         case MONO_TYPE_U:
4132 #endif
4133                 is_i4 = FALSE;
4134                 break;
4135         default:
4136                 is_i4 = TRUE;
4137                 break;
4138         }
4139
4140         {
4141                 MonoInst *load, *and_, *cmp, *ceq;
4142                 int enum_reg = is_i4 ? alloc_ireg (cfg) : alloc_lreg (cfg);
4143                 int and_reg = is_i4 ? alloc_ireg (cfg) : alloc_lreg (cfg);
4144                 int dest_reg = alloc_ireg (cfg);
4145
4146                 EMIT_NEW_LOAD_MEMBASE (cfg, load, load_opc, enum_reg, enum_this->dreg, 0);
4147                 EMIT_NEW_BIALU (cfg, and_, is_i4 ? OP_IAND : OP_LAND, and_reg, enum_reg, enum_flag->dreg);
4148                 EMIT_NEW_BIALU (cfg, cmp, is_i4 ? OP_ICOMPARE : OP_LCOMPARE, -1, and_reg, enum_flag->dreg);
4149                 EMIT_NEW_UNALU (cfg, ceq, is_i4 ? OP_ICEQ : OP_LCEQ, dest_reg, -1);
4150
4151                 ceq->type = STACK_I4;
4152
4153                 if (!is_i4) {
4154                         load = mono_decompose_opcode (cfg, load);
4155                         and_ = mono_decompose_opcode (cfg, and_);
4156                         cmp = mono_decompose_opcode (cfg, cmp);
4157                         ceq = mono_decompose_opcode (cfg, ceq);
4158                 }
4159
4160                 return ceq;
4161         }
4162 }
4163
4164 /*
4165  * Returns NULL and set the cfg exception on error.
4166  */
4167 static G_GNUC_UNUSED MonoInst*
4168 handle_delegate_ctor (MonoCompile *cfg, MonoClass *klass, MonoInst *target, MonoMethod *method, int context_used, gboolean virtual_)
4169 {
4170         MonoInst *ptr;
4171         int dreg;
4172         gpointer trampoline;
4173         MonoInst *obj, *method_ins, *tramp_ins;
4174         MonoDomain *domain;
4175         guint8 **code_slot;
4176
4177         if (virtual_ && !cfg->llvm_only) {
4178                 MonoMethod *invoke = mono_get_delegate_invoke (klass);
4179                 g_assert (invoke);
4180
4181                 if (!mono_get_delegate_virtual_invoke_impl (mono_method_signature (invoke), context_used ? NULL : method))
4182                         return NULL;
4183         }
4184
4185         obj = handle_alloc (cfg, klass, FALSE, mono_class_check_context_used (klass));
4186         if (!obj)
4187                 return NULL;
4188
4189         /* Inline the contents of mono_delegate_ctor */
4190
4191         /* Set target field */
4192         /* Optimize away setting of NULL target */
4193         if (!MONO_INS_IS_PCONST_NULL (target)) {
4194                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, target), target->dreg);
4195                 if (cfg->gen_write_barriers) {
4196                         dreg = alloc_preg (cfg);
4197                         EMIT_NEW_BIALU_IMM (cfg, ptr, OP_PADD_IMM, dreg, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, target));
4198                         mini_emit_write_barrier (cfg, ptr, target);
4199                 }
4200         }
4201
4202         /* Set method field */
4203         method_ins = emit_get_rgctx_method (cfg, context_used, method, MONO_RGCTX_INFO_METHOD);
4204         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, method), method_ins->dreg);
4205
4206         /* 
4207          * To avoid looking up the compiled code belonging to the target method
4208          * in mono_delegate_trampoline (), we allocate a per-domain memory slot to
4209          * store it, and we fill it after the method has been compiled.
4210          */
4211         if (!method->dynamic && !(cfg->opt & MONO_OPT_SHARED)) {
4212                 MonoInst *code_slot_ins;
4213
4214                 if (context_used) {
4215                         code_slot_ins = emit_get_rgctx_method (cfg, context_used, method, MONO_RGCTX_INFO_METHOD_DELEGATE_CODE);
4216                 } else {
4217                         domain = mono_domain_get ();
4218                         mono_domain_lock (domain);
4219                         if (!domain_jit_info (domain)->method_code_hash)
4220                                 domain_jit_info (domain)->method_code_hash = g_hash_table_new (NULL, NULL);
4221                         code_slot = (guint8 **)g_hash_table_lookup (domain_jit_info (domain)->method_code_hash, method);
4222                         if (!code_slot) {
4223                                 code_slot = (guint8 **)mono_domain_alloc0 (domain, sizeof (gpointer));
4224                                 g_hash_table_insert (domain_jit_info (domain)->method_code_hash, method, code_slot);
4225                         }
4226                         mono_domain_unlock (domain);
4227
4228                         code_slot_ins = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_METHOD_CODE_SLOT, method);
4229                 }
4230                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, method_code), code_slot_ins->dreg);                
4231         }
4232
4233         if (cfg->llvm_only) {
4234                 MonoInst *args [16];
4235
4236                 if (virtual_) {
4237                         args [0] = obj;
4238                         args [1] = target;
4239                         args [2] = emit_get_rgctx_method (cfg, context_used, method, MONO_RGCTX_INFO_METHOD);
4240                         mono_emit_jit_icall (cfg, mono_llvmonly_init_delegate_virtual, args);
4241                 } else {
4242                         args [0] = obj;
4243                         mono_emit_jit_icall (cfg, mono_llvmonly_init_delegate, args);
4244                 }
4245
4246                 return obj;
4247         }
4248
4249         if (cfg->compile_aot) {
4250                 MonoDelegateClassMethodPair *del_tramp;
4251
4252                 del_tramp = (MonoDelegateClassMethodPair *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoDelegateClassMethodPair));
4253                 del_tramp->klass = klass;
4254                 del_tramp->method = context_used ? NULL : method;
4255                 del_tramp->is_virtual = virtual_;
4256                 EMIT_NEW_AOTCONST (cfg, tramp_ins, MONO_PATCH_INFO_DELEGATE_TRAMPOLINE, del_tramp);
4257         } else {
4258                 if (virtual_)
4259                         trampoline = mono_create_delegate_virtual_trampoline (cfg->domain, klass, context_used ? NULL : method);
4260                 else
4261                         trampoline = mono_create_delegate_trampoline_info (cfg->domain, klass, context_used ? NULL : method);
4262                 EMIT_NEW_PCONST (cfg, tramp_ins, trampoline);
4263         }
4264
4265         /* Set invoke_impl field */
4266         if (virtual_) {
4267                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, invoke_impl), tramp_ins->dreg);
4268         } else {
4269                 dreg = alloc_preg (cfg);
4270                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, dreg, tramp_ins->dreg, MONO_STRUCT_OFFSET (MonoDelegateTrampInfo, invoke_impl));
4271                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, invoke_impl), dreg);
4272
4273                 dreg = alloc_preg (cfg);
4274                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, dreg, tramp_ins->dreg, MONO_STRUCT_OFFSET (MonoDelegateTrampInfo, method_ptr));
4275                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, method_ptr), dreg);
4276         }
4277
4278         dreg = alloc_preg (cfg);
4279         MONO_EMIT_NEW_ICONST (cfg, dreg, virtual_ ? 1 : 0);
4280         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI1_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, method_is_virtual), dreg);
4281
4282         /* All the checks which are in mono_delegate_ctor () are done by the delegate trampoline */
4283
4284         return obj;
4285 }
4286
4287 static MonoInst*
4288 handle_array_new (MonoCompile *cfg, int rank, MonoInst **sp, unsigned char *ip)
4289 {
4290         MonoJitICallInfo *info;
4291
4292         /* Need to register the icall so it gets an icall wrapper */
4293         info = mono_get_array_new_va_icall (rank);
4294
4295         cfg->flags |= MONO_CFG_HAS_VARARGS;
4296
4297         /* mono_array_new_va () needs a vararg calling convention */
4298         cfg->exception_message = g_strdup ("array-new");
4299         cfg->disable_llvm = TRUE;
4300
4301         /* FIXME: This uses info->sig, but it should use the signature of the wrapper */
4302         return mono_emit_native_call (cfg, mono_icall_get_wrapper (info), info->sig, sp);
4303 }
4304
4305 /*
4306  * handle_constrained_gsharedvt_call:
4307  *
4308  *   Handle constrained calls where the receiver is a gsharedvt type.
4309  * Return the instruction representing the call. Set the cfg exception on failure.
4310  */
4311 static MonoInst*
4312 handle_constrained_gsharedvt_call (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **sp, MonoClass *constrained_class,
4313                                                                    gboolean *ref_emit_widen)
4314 {
4315         MonoInst *ins = NULL;
4316         gboolean emit_widen = *ref_emit_widen;
4317
4318         /*
4319          * Constrained calls need to behave differently at runtime dependending on whenever the receiver is instantiated as ref type or as a vtype.
4320          * 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
4321          * pack the arguments into an array, and do the rest of the work in in an icall.
4322          */
4323         if (((cmethod->klass == mono_defaults.object_class) || mono_class_is_interface (cmethod->klass) || (!cmethod->klass->valuetype && cmethod->klass->image != mono_defaults.corlib)) &&
4324                 (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)) &&
4325                 (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]))))) {
4326                 MonoInst *args [16];
4327
4328                 /*
4329                  * This case handles calls to
4330                  * - object:ToString()/Equals()/GetHashCode(),
4331                  * - System.IComparable<T>:CompareTo()
4332                  * - System.IEquatable<T>:Equals ()
4333                  * plus some simple interface calls enough to support AsyncTaskMethodBuilder.
4334                  */
4335
4336                 args [0] = sp [0];
4337                 if (mono_method_check_context_used (cmethod))
4338                         args [1] = emit_get_rgctx_method (cfg, mono_method_check_context_used (cmethod), cmethod, MONO_RGCTX_INFO_METHOD);
4339                 else
4340                         EMIT_NEW_METHODCONST (cfg, args [1], cmethod);
4341                 args [2] = mini_emit_get_rgctx_klass (cfg, mono_class_check_context_used (constrained_class), constrained_class, MONO_RGCTX_INFO_KLASS);
4342
4343                 /* !fsig->hasthis is for the wrapper for the Object.GetType () icall */
4344                 if (fsig->hasthis && fsig->param_count) {
4345                         /* Pass the arguments using a localloc-ed array using the format expected by runtime_invoke () */
4346                         MONO_INST_NEW (cfg, ins, OP_LOCALLOC_IMM);
4347                         ins->dreg = alloc_preg (cfg);
4348                         ins->inst_imm = fsig->param_count * sizeof (mgreg_t);
4349                         MONO_ADD_INS (cfg->cbb, ins);
4350                         args [4] = ins;
4351
4352                         if (mini_is_gsharedvt_type (fsig->params [0])) {
4353                                 int addr_reg, deref_arg_reg;
4354
4355                                 ins = mini_emit_get_gsharedvt_info_klass (cfg, mono_class_from_mono_type (fsig->params [0]), MONO_RGCTX_INFO_CLASS_BOX_TYPE);
4356                                 deref_arg_reg = alloc_preg (cfg);
4357                                 /* deref_arg = BOX_TYPE != MONO_GSHAREDVT_BOX_TYPE_VTYPE */
4358                                 EMIT_NEW_BIALU_IMM (cfg, args [3], OP_ISUB_IMM, deref_arg_reg, ins->dreg, 1);
4359
4360                                 EMIT_NEW_VARLOADA_VREG (cfg, ins, sp [1]->dreg, fsig->params [0]);
4361                                 addr_reg = ins->dreg;
4362                                 EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STORE_MEMBASE_REG, args [4]->dreg, 0, addr_reg);
4363                         } else {
4364                                 EMIT_NEW_ICONST (cfg, args [3], 0);
4365                                 EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STORE_MEMBASE_REG, args [4]->dreg, 0, sp [1]->dreg);
4366                         }
4367                 } else {
4368                         EMIT_NEW_ICONST (cfg, args [3], 0);
4369                         EMIT_NEW_ICONST (cfg, args [4], 0);
4370                 }
4371                 ins = mono_emit_jit_icall (cfg, mono_gsharedvt_constrained_call, args);
4372                 emit_widen = FALSE;
4373
4374                 if (mini_is_gsharedvt_type (fsig->ret)) {
4375                         ins = handle_unbox_gsharedvt (cfg, mono_class_from_mono_type (fsig->ret), ins);
4376                 } else if (MONO_TYPE_IS_PRIMITIVE (fsig->ret) || MONO_TYPE_ISSTRUCT (fsig->ret) || mono_class_is_enum (mono_class_from_mono_type (fsig->ret))) {
4377                         MonoInst *add;
4378
4379                         /* Unbox */
4380                         NEW_BIALU_IMM (cfg, add, OP_ADD_IMM, alloc_dreg (cfg, STACK_MP), ins->dreg, sizeof (MonoObject));
4381                         MONO_ADD_INS (cfg->cbb, add);
4382                         /* Load value */
4383                         NEW_LOAD_MEMBASE_TYPE (cfg, ins, fsig->ret, add->dreg, 0);
4384                         MONO_ADD_INS (cfg->cbb, ins);
4385                         /* ins represents the call result */
4386                 }
4387         } else {
4388                 GSHAREDVT_FAILURE (CEE_CALLVIRT);
4389         }
4390
4391         *ref_emit_widen = emit_widen;
4392
4393         return ins;
4394
4395  exception_exit:
4396         return NULL;
4397 }
4398
4399 static void
4400 mono_emit_load_got_addr (MonoCompile *cfg)
4401 {
4402         MonoInst *getaddr, *dummy_use;
4403
4404         if (!cfg->got_var || cfg->got_var_allocated)
4405                 return;
4406
4407         MONO_INST_NEW (cfg, getaddr, OP_LOAD_GOTADDR);
4408         getaddr->cil_code = cfg->header->code;
4409         getaddr->dreg = cfg->got_var->dreg;
4410
4411         /* Add it to the start of the first bblock */
4412         if (cfg->bb_entry->code) {
4413                 getaddr->next = cfg->bb_entry->code;
4414                 cfg->bb_entry->code = getaddr;
4415         }
4416         else
4417                 MONO_ADD_INS (cfg->bb_entry, getaddr);
4418
4419         cfg->got_var_allocated = TRUE;
4420
4421         /* 
4422          * Add a dummy use to keep the got_var alive, since real uses might
4423          * only be generated by the back ends.
4424          * Add it to end_bblock, so the variable's lifetime covers the whole
4425          * method.
4426          * It would be better to make the usage of the got var explicit in all
4427          * cases when the backend needs it (i.e. calls, throw etc.), so this
4428          * wouldn't be needed.
4429          */
4430         NEW_DUMMY_USE (cfg, dummy_use, cfg->got_var);
4431         MONO_ADD_INS (cfg->bb_exit, dummy_use);
4432 }
4433
4434 static int inline_limit;
4435 static gboolean inline_limit_inited;
4436
4437 static gboolean
4438 mono_method_check_inlining (MonoCompile *cfg, MonoMethod *method)
4439 {
4440         MonoMethodHeaderSummary header;
4441         MonoVTable *vtable;
4442 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
4443         MonoMethodSignature *sig = mono_method_signature (method);
4444         int i;
4445 #endif
4446
4447         if (cfg->disable_inline)
4448                 return FALSE;
4449         if (cfg->gsharedvt)
4450                 return FALSE;
4451
4452         if (cfg->inline_depth > 10)
4453                 return FALSE;
4454
4455         if (!mono_method_get_header_summary (method, &header))
4456                 return FALSE;
4457
4458         /*runtime, icall and pinvoke are checked by summary call*/
4459         if ((method->iflags & METHOD_IMPL_ATTRIBUTE_NOINLINING) ||
4460             (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) ||
4461             (mono_class_is_marshalbyref (method->klass)) ||
4462             header.has_clauses)
4463                 return FALSE;
4464
4465         /* also consider num_locals? */
4466         /* Do the size check early to avoid creating vtables */
4467         if (!inline_limit_inited) {
4468                 char *inlinelimit;
4469                 if ((inlinelimit = g_getenv ("MONO_INLINELIMIT"))) {
4470                         inline_limit = atoi (inlinelimit);
4471                         g_free (inlinelimit);
4472                 } else
4473                         inline_limit = INLINE_LENGTH_LIMIT;
4474                 inline_limit_inited = TRUE;
4475         }
4476         if (header.code_size >= inline_limit && !(method->iflags & METHOD_IMPL_ATTRIBUTE_AGGRESSIVE_INLINING))
4477                 return FALSE;
4478
4479         /*
4480          * if we can initialize the class of the method right away, we do,
4481          * otherwise we don't allow inlining if the class needs initialization,
4482          * since it would mean inserting a call to mono_runtime_class_init()
4483          * inside the inlined code
4484          */
4485         if (cfg->gshared && method->klass->has_cctor && mini_class_check_context_used (cfg, method->klass))
4486                 return FALSE;
4487
4488         if (!(cfg->opt & MONO_OPT_SHARED)) {
4489                 /* The AggressiveInlining hint is a good excuse to force that cctor to run. */
4490                 if (method->iflags & METHOD_IMPL_ATTRIBUTE_AGGRESSIVE_INLINING) {
4491                         if (method->klass->has_cctor) {
4492                                 vtable = mono_class_vtable (cfg->domain, method->klass);
4493                                 if (!vtable)
4494                                         return FALSE;
4495                                 if (!cfg->compile_aot) {
4496                                         MonoError error;
4497                                         if (!mono_runtime_class_init_full (vtable, &error)) {
4498                                                 mono_error_cleanup (&error);
4499                                                 return FALSE;
4500                                         }
4501                                 }
4502                         }
4503                 } else if (mono_class_is_before_field_init (method->klass)) {
4504                         if (cfg->run_cctors && method->klass->has_cctor) {
4505                                 /*FIXME it would easier and lazier to just use mono_class_try_get_vtable */
4506                                 if (!method->klass->runtime_info)
4507                                         /* No vtable created yet */
4508                                         return FALSE;
4509                                 vtable = mono_class_vtable (cfg->domain, method->klass);
4510                                 if (!vtable)
4511                                         return FALSE;
4512                                 /* This makes so that inline cannot trigger */
4513                                 /* .cctors: too many apps depend on them */
4514                                 /* running with a specific order... */
4515                                 if (! vtable->initialized)
4516                                         return FALSE;
4517                                 MonoError error;
4518                                 if (!mono_runtime_class_init_full (vtable, &error)) {
4519                                         mono_error_cleanup (&error);
4520                                         return FALSE;
4521                                 }
4522                         }
4523                 } else if (mono_class_needs_cctor_run (method->klass, NULL)) {
4524                         if (!method->klass->runtime_info)
4525                                 /* No vtable created yet */
4526                                 return FALSE;
4527                         vtable = mono_class_vtable (cfg->domain, method->klass);
4528                         if (!vtable)
4529                                 return FALSE;
4530                         if (!vtable->initialized)
4531                                 return FALSE;
4532                 }
4533         } else {
4534                 /* 
4535                  * If we're compiling for shared code
4536                  * the cctor will need to be run at aot method load time, for example,
4537                  * or at the end of the compilation of the inlining method.
4538                  */
4539                 if (mono_class_needs_cctor_run (method->klass, NULL) && !mono_class_is_before_field_init (method->klass))
4540                         return FALSE;
4541         }
4542
4543 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
4544         if (mono_arch_is_soft_float ()) {
4545                 /* FIXME: */
4546                 if (sig->ret && sig->ret->type == MONO_TYPE_R4)
4547                         return FALSE;
4548                 for (i = 0; i < sig->param_count; ++i)
4549                         if (!sig->params [i]->byref && sig->params [i]->type == MONO_TYPE_R4)
4550                                 return FALSE;
4551         }
4552 #endif
4553
4554         if (g_list_find (cfg->dont_inline, method))
4555                 return FALSE;
4556
4557         return TRUE;
4558 }
4559
4560 static gboolean
4561 mini_field_access_needs_cctor_run (MonoCompile *cfg, MonoMethod *method, MonoClass *klass, MonoVTable *vtable)
4562 {
4563         if (!cfg->compile_aot) {
4564                 g_assert (vtable);
4565                 if (vtable->initialized)
4566                         return FALSE;
4567         }
4568
4569         if (mono_class_is_before_field_init (klass)) {
4570                 if (cfg->method == method)
4571                         return FALSE;
4572         }
4573
4574         if (!mono_class_needs_cctor_run (klass, method))
4575                 return FALSE;
4576
4577         if (! (method->flags & METHOD_ATTRIBUTE_STATIC) && (klass == method->klass))
4578                 /* The initialization is already done before the method is called */
4579                 return FALSE;
4580
4581         return TRUE;
4582 }
4583
4584 MonoInst*
4585 mini_emit_ldelema_1_ins (MonoCompile *cfg, MonoClass *klass, MonoInst *arr, MonoInst *index, gboolean bcheck)
4586 {
4587         MonoInst *ins;
4588         guint32 size;
4589         int mult_reg, add_reg, array_reg, index_reg, index2_reg;
4590         int context_used;
4591
4592         if (mini_is_gsharedvt_variable_klass (klass)) {
4593                 size = -1;
4594         } else {
4595                 mono_class_init (klass);
4596                 size = mono_class_array_element_size (klass);
4597         }
4598
4599         mult_reg = alloc_preg (cfg);
4600         array_reg = arr->dreg;
4601         index_reg = index->dreg;
4602
4603 #if SIZEOF_REGISTER == 8
4604         /* The array reg is 64 bits but the index reg is only 32 */
4605         if (COMPILE_LLVM (cfg)) {
4606                 /*
4607                  * abcrem can't handle the OP_SEXT_I4, so add this after abcrem,
4608                  * during OP_BOUNDS_CHECK decomposition, and in the implementation
4609                  * of OP_X86_LEA for llvm.
4610                  */
4611                 index2_reg = index_reg;
4612         } else {
4613                 index2_reg = alloc_preg (cfg);
4614                 MONO_EMIT_NEW_UNALU (cfg, OP_SEXT_I4, index2_reg, index_reg);
4615         }
4616 #else
4617         if (index->type == STACK_I8) {
4618                 index2_reg = alloc_preg (cfg);
4619                 MONO_EMIT_NEW_UNALU (cfg, OP_LCONV_TO_I4, index2_reg, index_reg);
4620         } else {
4621                 index2_reg = index_reg;
4622         }
4623 #endif
4624
4625         if (bcheck)
4626                 MONO_EMIT_BOUNDS_CHECK (cfg, array_reg, MonoArray, max_length, index2_reg);
4627
4628 #if defined(TARGET_X86) || defined(TARGET_AMD64)
4629         if (size == 1 || size == 2 || size == 4 || size == 8) {
4630                 static const int fast_log2 [] = { 1, 0, 1, -1, 2, -1, -1, -1, 3 };
4631
4632                 EMIT_NEW_X86_LEA (cfg, ins, array_reg, index2_reg, fast_log2 [size], MONO_STRUCT_OFFSET (MonoArray, vector));
4633                 ins->klass = mono_class_get_element_class (klass);
4634                 ins->type = STACK_MP;
4635
4636                 return ins;
4637         }
4638 #endif          
4639
4640         add_reg = alloc_ireg_mp (cfg);
4641
4642         if (size == -1) {
4643                 MonoInst *rgctx_ins;
4644
4645                 /* gsharedvt */
4646                 g_assert (cfg->gshared);
4647                 context_used = mini_class_check_context_used (cfg, klass);
4648                 g_assert (context_used);
4649                 rgctx_ins = mini_emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_ARRAY_ELEMENT_SIZE);
4650                 MONO_EMIT_NEW_BIALU (cfg, OP_IMUL, mult_reg, index2_reg, rgctx_ins->dreg);
4651         } else {
4652                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_MUL_IMM, mult_reg, index2_reg, size);
4653         }
4654         MONO_EMIT_NEW_BIALU (cfg, OP_PADD, add_reg, array_reg, mult_reg);
4655         NEW_BIALU_IMM (cfg, ins, OP_PADD_IMM, add_reg, add_reg, MONO_STRUCT_OFFSET (MonoArray, vector));
4656         ins->klass = mono_class_get_element_class (klass);
4657         ins->type = STACK_MP;
4658         MONO_ADD_INS (cfg->cbb, ins);
4659
4660         return ins;
4661 }
4662
4663 static MonoInst*
4664 mini_emit_ldelema_2_ins (MonoCompile *cfg, MonoClass *klass, MonoInst *arr, MonoInst *index_ins1, MonoInst *index_ins2)
4665 {
4666         int bounds_reg = alloc_preg (cfg);
4667         int add_reg = alloc_ireg_mp (cfg);
4668         int mult_reg = alloc_preg (cfg);
4669         int mult2_reg = alloc_preg (cfg);
4670         int low1_reg = alloc_preg (cfg);
4671         int low2_reg = alloc_preg (cfg);
4672         int high1_reg = alloc_preg (cfg);
4673         int high2_reg = alloc_preg (cfg);
4674         int realidx1_reg = alloc_preg (cfg);
4675         int realidx2_reg = alloc_preg (cfg);
4676         int sum_reg = alloc_preg (cfg);
4677         int index1, index2, tmpreg;
4678         MonoInst *ins;
4679         guint32 size;
4680
4681         mono_class_init (klass);
4682         size = mono_class_array_element_size (klass);
4683
4684         index1 = index_ins1->dreg;
4685         index2 = index_ins2->dreg;
4686
4687 #if SIZEOF_REGISTER == 8
4688         /* The array reg is 64 bits but the index reg is only 32 */
4689         if (COMPILE_LLVM (cfg)) {
4690                 /* Not needed */
4691         } else {
4692                 tmpreg = alloc_preg (cfg);
4693                 MONO_EMIT_NEW_UNALU (cfg, OP_SEXT_I4, tmpreg, index1);
4694                 index1 = tmpreg;
4695                 tmpreg = alloc_preg (cfg);
4696                 MONO_EMIT_NEW_UNALU (cfg, OP_SEXT_I4, tmpreg, index2);
4697                 index2 = tmpreg;
4698         }
4699 #else
4700         // FIXME: Do we need to do something here for i8 indexes, like in ldelema_1_ins ?
4701         tmpreg = -1;
4702 #endif
4703
4704         /* range checking */
4705         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, bounds_reg, 
4706                                        arr->dreg, MONO_STRUCT_OFFSET (MonoArray, bounds));
4707
4708         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, low1_reg, 
4709                                        bounds_reg, MONO_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
4710         MONO_EMIT_NEW_BIALU (cfg, OP_PSUB, realidx1_reg, index1, low1_reg);
4711         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, high1_reg, 
4712                                        bounds_reg, MONO_STRUCT_OFFSET (MonoArrayBounds, length));
4713         MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, high1_reg, realidx1_reg);
4714         MONO_EMIT_NEW_COND_EXC (cfg, LE_UN, "IndexOutOfRangeException");
4715
4716         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, low2_reg, 
4717                                        bounds_reg, sizeof (MonoArrayBounds) + MONO_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
4718         MONO_EMIT_NEW_BIALU (cfg, OP_PSUB, realidx2_reg, index2, low2_reg);
4719         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, high2_reg, 
4720                                        bounds_reg, sizeof (MonoArrayBounds) + MONO_STRUCT_OFFSET (MonoArrayBounds, length));
4721         MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, high2_reg, realidx2_reg);
4722         MONO_EMIT_NEW_COND_EXC (cfg, LE_UN, "IndexOutOfRangeException");
4723
4724         MONO_EMIT_NEW_BIALU (cfg, OP_PMUL, mult_reg, high2_reg, realidx1_reg);
4725         MONO_EMIT_NEW_BIALU (cfg, OP_PADD, sum_reg, mult_reg, realidx2_reg);
4726         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PMUL_IMM, mult2_reg, sum_reg, size);
4727         MONO_EMIT_NEW_BIALU (cfg, OP_PADD, add_reg, mult2_reg, arr->dreg);
4728         NEW_BIALU_IMM (cfg, ins, OP_PADD_IMM, add_reg, add_reg, MONO_STRUCT_OFFSET (MonoArray, vector));
4729
4730         ins->type = STACK_MP;
4731         ins->klass = klass;
4732         MONO_ADD_INS (cfg->cbb, ins);
4733
4734         return ins;
4735 }
4736
4737 static MonoInst*
4738 mini_emit_ldelema_ins (MonoCompile *cfg, MonoMethod *cmethod, MonoInst **sp, unsigned char *ip, gboolean is_set)
4739 {
4740         int rank;
4741         MonoInst *addr;
4742         MonoMethod *addr_method;
4743         int element_size;
4744         MonoClass *eclass = cmethod->klass->element_class;
4745
4746         rank = mono_method_signature (cmethod)->param_count - (is_set? 1: 0);
4747
4748         if (rank == 1)
4749                 return mini_emit_ldelema_1_ins (cfg, eclass, sp [0], sp [1], TRUE);
4750
4751         /* emit_ldelema_2 depends on OP_LMUL */
4752         if (!cfg->backend->emulate_mul_div && rank == 2 && (cfg->opt & MONO_OPT_INTRINS) && !mini_is_gsharedvt_variable_klass (eclass)) {
4753                 return mini_emit_ldelema_2_ins (cfg, eclass, sp [0], sp [1], sp [2]);
4754         }
4755
4756         if (mini_is_gsharedvt_variable_klass (eclass))
4757                 element_size = 0;
4758         else
4759                 element_size = mono_class_array_element_size (eclass);
4760         addr_method = mono_marshal_get_array_address (rank, element_size);
4761         addr = mono_emit_method_call (cfg, addr_method, sp, NULL);
4762
4763         return addr;
4764 }
4765
4766 static MonoBreakPolicy
4767 always_insert_breakpoint (MonoMethod *method)
4768 {
4769         return MONO_BREAK_POLICY_ALWAYS;
4770 }
4771
4772 static MonoBreakPolicyFunc break_policy_func = always_insert_breakpoint;
4773
4774 /**
4775  * mono_set_break_policy:
4776  * \param policy_callback the new callback function
4777  *
4778  * Allow embedders to decide wherther to actually obey breakpoint instructions
4779  * (both break IL instructions and \c Debugger.Break method calls), for example
4780  * to not allow an app to be aborted by a perfectly valid IL opcode when executing
4781  * untrusted or semi-trusted code.
4782  *
4783  * \p policy_callback will be called every time a break point instruction needs to
4784  * be inserted with the method argument being the method that calls \c Debugger.Break
4785  * or has the IL \c break instruction. The callback should return \c MONO_BREAK_POLICY_NEVER
4786  * if it wants the breakpoint to not be effective in the given method.
4787  * \c MONO_BREAK_POLICY_ALWAYS is the default.
4788  */
4789 void
4790 mono_set_break_policy (MonoBreakPolicyFunc policy_callback)
4791 {
4792         if (policy_callback)
4793                 break_policy_func = policy_callback;
4794         else
4795                 break_policy_func = always_insert_breakpoint;
4796 }
4797
4798 static gboolean
4799 should_insert_brekpoint (MonoMethod *method) {
4800         switch (break_policy_func (method)) {
4801         case MONO_BREAK_POLICY_ALWAYS:
4802                 return TRUE;
4803         case MONO_BREAK_POLICY_NEVER:
4804                 return FALSE;
4805         case MONO_BREAK_POLICY_ON_DBG:
4806                 g_warning ("mdb no longer supported");
4807                 return FALSE;
4808         default:
4809                 g_warning ("Incorrect value returned from break policy callback");
4810                 return FALSE;
4811         }
4812 }
4813
4814 /* optimize the simple GetGenericValueImpl/SetGenericValueImpl generic icalls */
4815 static MonoInst*
4816 emit_array_generic_access (MonoCompile *cfg, MonoMethodSignature *fsig, MonoInst **args, int is_set)
4817 {
4818         MonoInst *addr, *store, *load;
4819         MonoClass *eklass = mono_class_from_mono_type (fsig->params [2]);
4820
4821         /* the bounds check is already done by the callers */
4822         addr = mini_emit_ldelema_1_ins (cfg, eklass, args [0], args [1], FALSE);
4823         if (is_set) {
4824                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, load, &eklass->byval_arg, args [2]->dreg, 0);
4825                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, store, &eklass->byval_arg, addr->dreg, 0, load->dreg);
4826                 if (mini_type_is_reference (&eklass->byval_arg))
4827                         mini_emit_write_barrier (cfg, addr, load);
4828         } else {
4829                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, load, &eklass->byval_arg, addr->dreg, 0);
4830                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, store, &eklass->byval_arg, args [2]->dreg, 0, load->dreg);
4831         }
4832         return store;
4833 }
4834
4835
4836 static gboolean
4837 generic_class_is_reference_type (MonoCompile *cfg, MonoClass *klass)
4838 {
4839         return mini_type_is_reference (&klass->byval_arg);
4840 }
4841
4842 static MonoInst*
4843 emit_array_store (MonoCompile *cfg, MonoClass *klass, MonoInst **sp, gboolean safety_checks)
4844 {
4845         if (safety_checks && generic_class_is_reference_type (cfg, klass) &&
4846                 !(MONO_INS_IS_PCONST_NULL (sp [2]))) {
4847                 MonoClass *obj_array = mono_array_class_get_cached (mono_defaults.object_class, 1);
4848                 MonoMethod *helper = mono_marshal_get_virtual_stelemref (obj_array);
4849                 MonoInst *iargs [3];
4850
4851                 if (!helper->slot)
4852                         mono_class_setup_vtable (obj_array);
4853                 g_assert (helper->slot);
4854
4855                 if (sp [0]->type != STACK_OBJ)
4856                         return NULL;
4857                 if (sp [2]->type != STACK_OBJ)
4858                         return NULL;
4859
4860                 iargs [2] = sp [2];
4861                 iargs [1] = sp [1];
4862                 iargs [0] = sp [0];
4863
4864                 return mono_emit_method_call (cfg, helper, iargs, sp [0]);
4865         } else {
4866                 MonoInst *ins;
4867
4868                 if (mini_is_gsharedvt_variable_klass (klass)) {
4869                         MonoInst *addr;
4870
4871                         // FIXME-VT: OP_ICONST optimization
4872                         addr = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1], TRUE);
4873                         EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr->dreg, 0, sp [2]->dreg);
4874                         ins->opcode = OP_STOREV_MEMBASE;
4875                 } else if (sp [1]->opcode == OP_ICONST) {
4876                         int array_reg = sp [0]->dreg;
4877                         int index_reg = sp [1]->dreg;
4878                         int offset = (mono_class_array_element_size (klass) * sp [1]->inst_c0) + MONO_STRUCT_OFFSET (MonoArray, vector);
4879
4880                         if (SIZEOF_REGISTER == 8 && COMPILE_LLVM (cfg))
4881                                 MONO_EMIT_NEW_UNALU (cfg, OP_ZEXT_I4, index_reg, index_reg);
4882
4883                         if (safety_checks)
4884                                 MONO_EMIT_BOUNDS_CHECK (cfg, array_reg, MonoArray, max_length, index_reg);
4885                         EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, array_reg, offset, sp [2]->dreg);
4886                 } else {
4887                         MonoInst *addr = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1], safety_checks);
4888                         EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr->dreg, 0, sp [2]->dreg);
4889                         if (generic_class_is_reference_type (cfg, klass))
4890                                 mini_emit_write_barrier (cfg, addr, sp [2]);
4891                 }
4892                 return ins;
4893         }
4894 }
4895
4896 static MonoInst*
4897 emit_array_unsafe_access (MonoCompile *cfg, MonoMethodSignature *fsig, MonoInst **args, int is_set)
4898 {
4899         MonoClass *eklass;
4900         
4901         if (is_set)
4902                 eklass = mono_class_from_mono_type (fsig->params [2]);
4903         else
4904                 eklass = mono_class_from_mono_type (fsig->ret);
4905
4906         if (is_set) {
4907                 return emit_array_store (cfg, eklass, args, FALSE);
4908         } else {
4909                 MonoInst *ins, *addr = mini_emit_ldelema_1_ins (cfg, eklass, args [0], args [1], FALSE);
4910                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &eklass->byval_arg, addr->dreg, 0);
4911                 return ins;
4912         }
4913 }
4914
4915 static gboolean
4916 is_unsafe_mov_compatible (MonoCompile *cfg, MonoClass *param_klass, MonoClass *return_klass)
4917 {
4918         uint32_t align;
4919         int param_size, return_size;
4920
4921         param_klass = mono_class_from_mono_type (mini_get_underlying_type (&param_klass->byval_arg));
4922         return_klass = mono_class_from_mono_type (mini_get_underlying_type (&return_klass->byval_arg));
4923
4924         if (cfg->verbose_level > 3)
4925                 printf ("[UNSAFE-MOV-INTRISIC] %s <- %s\n", return_klass->name, param_klass->name);
4926
4927         //Don't allow mixing reference types with value types
4928         if (param_klass->valuetype != return_klass->valuetype) {
4929                 if (cfg->verbose_level > 3)
4930                         printf ("[UNSAFE-MOV-INTRISIC]\tone of the args is a valuetype and the other is not\n");
4931                 return FALSE;
4932         }
4933
4934         if (!param_klass->valuetype) {
4935                 if (cfg->verbose_level > 3)
4936                         printf ("[UNSAFE-MOV-INTRISIC]\targs are reference types\n");
4937                 return TRUE;
4938         }
4939
4940         //That are blitable
4941         if (param_klass->has_references || return_klass->has_references)
4942                 return FALSE;
4943
4944         /* Avoid mixing structs and primitive types/enums, they need to be handled differently in the JIT */
4945         if ((MONO_TYPE_ISSTRUCT (&param_klass->byval_arg) && !MONO_TYPE_ISSTRUCT (&return_klass->byval_arg)) ||
4946                 (!MONO_TYPE_ISSTRUCT (&param_klass->byval_arg) && MONO_TYPE_ISSTRUCT (&return_klass->byval_arg))) {
4947                         if (cfg->verbose_level > 3)
4948                                 printf ("[UNSAFE-MOV-INTRISIC]\tmixing structs and scalars\n");
4949                 return FALSE;
4950         }
4951
4952         if (param_klass->byval_arg.type == MONO_TYPE_R4 || param_klass->byval_arg.type == MONO_TYPE_R8 ||
4953                 return_klass->byval_arg.type == MONO_TYPE_R4 || return_klass->byval_arg.type == MONO_TYPE_R8) {
4954                 if (cfg->verbose_level > 3)
4955                         printf ("[UNSAFE-MOV-INTRISIC]\tfloat or double are not supported\n");
4956                 return FALSE;
4957         }
4958
4959         param_size = mono_class_value_size (param_klass, &align);
4960         return_size = mono_class_value_size (return_klass, &align);
4961
4962         //We can do it if sizes match
4963         if (param_size == return_size) {
4964                 if (cfg->verbose_level > 3)
4965                         printf ("[UNSAFE-MOV-INTRISIC]\tsame size\n");
4966                 return TRUE;
4967         }
4968
4969         //No simple way to handle struct if sizes don't match
4970         if (MONO_TYPE_ISSTRUCT (&param_klass->byval_arg)) {
4971                 if (cfg->verbose_level > 3)
4972                         printf ("[UNSAFE-MOV-INTRISIC]\tsize mismatch and type is a struct\n");
4973                 return FALSE;
4974         }
4975
4976         /*
4977          * Same reg size category.
4978          * A quick note on why we don't require widening here.
4979          * The intrinsic is "R Array.UnsafeMov<S,R> (S s)".
4980          *
4981          * Since the source value comes from a function argument, the JIT will already have
4982          * the value in a VREG and performed any widening needed before (say, when loading from a field).
4983          */
4984         if (param_size <= 4 && return_size <= 4) {
4985                 if (cfg->verbose_level > 3)
4986                         printf ("[UNSAFE-MOV-INTRISIC]\tsize mismatch but both are of the same reg class\n");
4987                 return TRUE;
4988         }
4989
4990         return FALSE;
4991 }
4992
4993 static MonoInst*
4994 emit_array_unsafe_mov (MonoCompile *cfg, MonoMethodSignature *fsig, MonoInst **args)
4995 {
4996         MonoClass *param_klass = mono_class_from_mono_type (fsig->params [0]);
4997         MonoClass *return_klass = mono_class_from_mono_type (fsig->ret);
4998
4999         if (mini_is_gsharedvt_variable_type (fsig->ret))
5000                 return NULL;
5001
5002         //Valuetypes that are semantically equivalent or numbers than can be widened to
5003         if (is_unsafe_mov_compatible (cfg, param_klass, return_klass))
5004                 return args [0];
5005
5006         //Arrays of valuetypes that are semantically equivalent
5007         if (param_klass->rank == 1 && return_klass->rank == 1 && is_unsafe_mov_compatible (cfg, param_klass->element_class, return_klass->element_class))
5008                 return args [0];
5009
5010         return NULL;
5011 }
5012
5013 static MonoInst*
5014 mini_emit_inst_for_ctor (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
5015 {
5016 #ifdef MONO_ARCH_SIMD_INTRINSICS
5017         MonoInst *ins = NULL;
5018
5019         if (cfg->opt & MONO_OPT_SIMD) {
5020                 ins = mono_emit_simd_intrinsics (cfg, cmethod, fsig, args);
5021                 if (ins)
5022                         return ins;
5023         }
5024 #endif
5025
5026         return mono_emit_native_types_intrinsics (cfg, cmethod, fsig, args);
5027 }
5028
5029 MonoInst*
5030 mini_emit_memory_barrier (MonoCompile *cfg, int kind)
5031 {
5032         MonoInst *ins = NULL;
5033         MONO_INST_NEW (cfg, ins, OP_MEMORY_BARRIER);
5034         MONO_ADD_INS (cfg->cbb, ins);
5035         ins->backend.memory_barrier_kind = kind;
5036
5037         return ins;
5038 }
5039
5040 static MonoInst*
5041 llvm_emit_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
5042 {
5043         MonoInst *ins = NULL;
5044         int opcode = 0;
5045
5046         /* The LLVM backend supports these intrinsics */
5047         if (cmethod->klass == mono_defaults.math_class) {
5048                 if (strcmp (cmethod->name, "Sin") == 0) {
5049                         opcode = OP_SIN;
5050                 } else if (strcmp (cmethod->name, "Cos") == 0) {
5051                         opcode = OP_COS;
5052                 } else if (strcmp (cmethod->name, "Sqrt") == 0) {
5053                         opcode = OP_SQRT;
5054                 } else if (strcmp (cmethod->name, "Abs") == 0 && fsig->params [0]->type == MONO_TYPE_R8) {
5055                         opcode = OP_ABS;
5056                 }
5057
5058                 if (opcode && fsig->param_count == 1) {
5059                         MONO_INST_NEW (cfg, ins, opcode);
5060                         ins->type = STACK_R8;
5061                         ins->dreg = mono_alloc_dreg (cfg, ins->type);
5062                         ins->sreg1 = args [0]->dreg;
5063                         MONO_ADD_INS (cfg->cbb, ins);
5064                 }
5065
5066                 opcode = 0;
5067                 if (cfg->opt & MONO_OPT_CMOV) {
5068                         if (strcmp (cmethod->name, "Min") == 0) {
5069                                 if (fsig->params [0]->type == MONO_TYPE_I4)
5070                                         opcode = OP_IMIN;
5071                                 if (fsig->params [0]->type == MONO_TYPE_U4)
5072                                         opcode = OP_IMIN_UN;
5073                                 else if (fsig->params [0]->type == MONO_TYPE_I8)
5074                                         opcode = OP_LMIN;
5075                                 else if (fsig->params [0]->type == MONO_TYPE_U8)
5076                                         opcode = OP_LMIN_UN;
5077                         } else if (strcmp (cmethod->name, "Max") == 0) {
5078                                 if (fsig->params [0]->type == MONO_TYPE_I4)
5079                                         opcode = OP_IMAX;
5080                                 if (fsig->params [0]->type == MONO_TYPE_U4)
5081                                         opcode = OP_IMAX_UN;
5082                                 else if (fsig->params [0]->type == MONO_TYPE_I8)
5083                                         opcode = OP_LMAX;
5084                                 else if (fsig->params [0]->type == MONO_TYPE_U8)
5085                                         opcode = OP_LMAX_UN;
5086                         }
5087                 }
5088
5089                 if (opcode && fsig->param_count == 2) {
5090                         MONO_INST_NEW (cfg, ins, opcode);
5091                         ins->type = fsig->params [0]->type == MONO_TYPE_I4 ? STACK_I4 : STACK_I8;
5092                         ins->dreg = mono_alloc_dreg (cfg, ins->type);
5093                         ins->sreg1 = args [0]->dreg;
5094                         ins->sreg2 = args [1]->dreg;
5095                         MONO_ADD_INS (cfg->cbb, ins);
5096                 }
5097         }
5098
5099         return ins;
5100 }
5101
5102 static MonoInst*
5103 mini_emit_inst_for_sharable_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
5104 {
5105         if (cmethod->klass == mono_defaults.array_class) {
5106                 if (strcmp (cmethod->name, "UnsafeStore") == 0)
5107                         return emit_array_unsafe_access (cfg, fsig, args, TRUE);
5108                 else if (strcmp (cmethod->name, "UnsafeLoad") == 0)
5109                         return emit_array_unsafe_access (cfg, fsig, args, FALSE);
5110                 else if (strcmp (cmethod->name, "UnsafeMov") == 0)
5111                         return emit_array_unsafe_mov (cfg, fsig, args);
5112         }
5113
5114         return NULL;
5115 }
5116
5117 static MonoInst*
5118 mini_emit_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
5119 {
5120         MonoInst *ins = NULL;
5121         MonoClass *runtime_helpers_class = mono_class_get_runtime_helpers_class ();
5122
5123         if (cmethod->klass == mono_defaults.string_class) {
5124                 if (strcmp (cmethod->name, "get_Chars") == 0 && fsig->param_count + fsig->hasthis == 2) {
5125                         int dreg = alloc_ireg (cfg);
5126                         int index_reg = alloc_preg (cfg);
5127                         int add_reg = alloc_preg (cfg);
5128
5129 #if SIZEOF_REGISTER == 8
5130                         if (COMPILE_LLVM (cfg)) {
5131                                 MONO_EMIT_NEW_UNALU (cfg, OP_ZEXT_I4, index_reg, args [1]->dreg);
5132                         } else {
5133                                 /* The array reg is 64 bits but the index reg is only 32 */
5134                                 MONO_EMIT_NEW_UNALU (cfg, OP_SEXT_I4, index_reg, args [1]->dreg);
5135                         }
5136 #else
5137                         index_reg = args [1]->dreg;
5138 #endif  
5139                         MONO_EMIT_BOUNDS_CHECK (cfg, args [0]->dreg, MonoString, length, index_reg);
5140
5141 #if defined(TARGET_X86) || defined(TARGET_AMD64)
5142                         EMIT_NEW_X86_LEA (cfg, ins, args [0]->dreg, index_reg, 1, MONO_STRUCT_OFFSET (MonoString, chars));
5143                         add_reg = ins->dreg;
5144                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADU2_MEMBASE, dreg, 
5145                                                                    add_reg, 0);
5146 #else
5147                         int mult_reg = alloc_preg (cfg);
5148                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHL_IMM, mult_reg, index_reg, 1);
5149                         MONO_EMIT_NEW_BIALU (cfg, OP_PADD, add_reg, mult_reg, args [0]->dreg);
5150                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADU2_MEMBASE, dreg, 
5151                                                                    add_reg, MONO_STRUCT_OFFSET (MonoString, chars));
5152 #endif
5153                         type_from_op (cfg, ins, NULL, NULL);
5154                         return ins;
5155                 } else if (strcmp (cmethod->name, "get_Length") == 0 && fsig->param_count + fsig->hasthis == 1) {
5156                         int dreg = alloc_ireg (cfg);
5157                         /* Decompose later to allow more optimizations */
5158                         EMIT_NEW_UNALU (cfg, ins, OP_STRLEN, dreg, args [0]->dreg);
5159                         ins->type = STACK_I4;
5160                         ins->flags |= MONO_INST_FAULT;
5161                         cfg->cbb->has_array_access = TRUE;
5162                         cfg->flags |= MONO_CFG_HAS_ARRAY_ACCESS;
5163
5164                         return ins;
5165                 } else 
5166                         return NULL;
5167         } else if (cmethod->klass == mono_defaults.object_class) {
5168                 if (strcmp (cmethod->name, "GetType") == 0 && fsig->param_count + fsig->hasthis == 1) {
5169                         int dreg = alloc_ireg_ref (cfg);
5170                         int vt_reg = alloc_preg (cfg);
5171                         MONO_EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, vt_reg, args [0]->dreg, MONO_STRUCT_OFFSET (MonoObject, vtable));
5172                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, dreg, vt_reg, MONO_STRUCT_OFFSET (MonoVTable, type));
5173                         type_from_op (cfg, ins, NULL, NULL);
5174
5175                         return ins;
5176                 } else if (!cfg->backend->emulate_mul_div && strcmp (cmethod->name, "InternalGetHashCode") == 0 && fsig->param_count == 1 && !mono_gc_is_moving ()) {
5177                         int dreg = alloc_ireg (cfg);
5178                         int t1 = alloc_ireg (cfg);
5179         
5180                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHL_IMM, t1, args [0]->dreg, 3);
5181                         EMIT_NEW_BIALU_IMM (cfg, ins, OP_MUL_IMM, dreg, t1, 2654435761u);
5182                         ins->type = STACK_I4;
5183
5184                         return ins;
5185                 } else if (strcmp (cmethod->name, ".ctor") == 0 && fsig->param_count == 0) {
5186                         MONO_INST_NEW (cfg, ins, OP_NOP);
5187                         MONO_ADD_INS (cfg->cbb, ins);
5188                         return ins;
5189                 } else
5190                         return NULL;
5191         } else if (cmethod->klass == mono_defaults.array_class) {
5192                 if (strcmp (cmethod->name, "GetGenericValueImpl") == 0 && fsig->param_count + fsig->hasthis == 3 && !cfg->gsharedvt)
5193                         return emit_array_generic_access (cfg, fsig, args, FALSE);
5194                 else if (strcmp (cmethod->name, "SetGenericValueImpl") == 0 && fsig->param_count + fsig->hasthis == 3 && !cfg->gsharedvt)
5195                         return emit_array_generic_access (cfg, fsig, args, TRUE);
5196
5197 #ifndef MONO_BIG_ARRAYS
5198                 /*
5199                  * This is an inline version of GetLength/GetLowerBound(0) used frequently in
5200                  * Array methods.
5201                  */
5202                 else if (((strcmp (cmethod->name, "GetLength") == 0 && fsig->param_count + fsig->hasthis == 2) ||
5203                          (strcmp (cmethod->name, "GetLowerBound") == 0 && fsig->param_count + fsig->hasthis == 2)) &&
5204                          args [1]->opcode == OP_ICONST && args [1]->inst_c0 == 0) {
5205                         int dreg = alloc_ireg (cfg);
5206                         int bounds_reg = alloc_ireg_mp (cfg);
5207                         MonoBasicBlock *end_bb, *szarray_bb;
5208                         gboolean get_length = strcmp (cmethod->name, "GetLength") == 0;
5209
5210                         NEW_BBLOCK (cfg, end_bb);
5211                         NEW_BBLOCK (cfg, szarray_bb);
5212
5213                         EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, ins, OP_LOAD_MEMBASE, bounds_reg,
5214                                                                                  args [0]->dreg, MONO_STRUCT_OFFSET (MonoArray, bounds));
5215                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, bounds_reg, 0);
5216                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, szarray_bb);
5217                         /* Non-szarray case */
5218                         if (get_length)
5219                                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADI4_MEMBASE, dreg,
5220                                                                            bounds_reg, MONO_STRUCT_OFFSET (MonoArrayBounds, length));
5221                         else
5222                                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADI4_MEMBASE, dreg,
5223                                                                            bounds_reg, MONO_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
5224                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
5225                         MONO_START_BB (cfg, szarray_bb);
5226                         /* Szarray case */
5227                         if (get_length)
5228                                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADI4_MEMBASE, dreg,
5229                                                                            args [0]->dreg, MONO_STRUCT_OFFSET (MonoArray, max_length));
5230                         else
5231                                 MONO_EMIT_NEW_ICONST (cfg, dreg, 0);
5232                         MONO_START_BB (cfg, end_bb);
5233
5234                         EMIT_NEW_UNALU (cfg, ins, OP_MOVE, dreg, dreg);
5235                         ins->type = STACK_I4;
5236                         
5237                         return ins;
5238                 }
5239 #endif
5240
5241                 if (cmethod->name [0] != 'g')
5242                         return NULL;
5243
5244                 if (strcmp (cmethod->name, "get_Rank") == 0 && fsig->param_count + fsig->hasthis == 1) {
5245                         int dreg = alloc_ireg (cfg);
5246                         int vtable_reg = alloc_preg (cfg);
5247                         MONO_EMIT_NEW_LOAD_MEMBASE_OP_FAULT (cfg, OP_LOAD_MEMBASE, vtable_reg, 
5248                                                                                                  args [0]->dreg, MONO_STRUCT_OFFSET (MonoObject, vtable));
5249                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADU1_MEMBASE, dreg,
5250                                                                    vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, rank));
5251                         type_from_op (cfg, ins, NULL, NULL);
5252
5253                         return ins;
5254                 } else if (strcmp (cmethod->name, "get_Length") == 0 && fsig->param_count + fsig->hasthis == 1) {
5255                         int dreg = alloc_ireg (cfg);
5256
5257                         EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, ins, OP_LOADI4_MEMBASE, dreg, 
5258                                                                                  args [0]->dreg, MONO_STRUCT_OFFSET (MonoArray, max_length));
5259                         type_from_op (cfg, ins, NULL, NULL);
5260
5261                         return ins;
5262                 } else
5263                         return NULL;
5264         } else if (cmethod->klass == runtime_helpers_class) {
5265                 if (strcmp (cmethod->name, "get_OffsetToStringData") == 0 && fsig->param_count == 0) {
5266                         EMIT_NEW_ICONST (cfg, ins, MONO_STRUCT_OFFSET (MonoString, chars));
5267                         return ins;
5268                 } else if (strcmp (cmethod->name, "IsReferenceOrContainsReferences") == 0 && fsig->param_count == 0) {
5269                         MonoGenericContext *ctx = mono_method_get_context (cmethod);
5270                         g_assert (ctx);
5271                         g_assert (ctx->method_inst);
5272                         g_assert (ctx->method_inst->type_argc == 1);
5273                         MonoType *t = mini_get_underlying_type (ctx->method_inst->type_argv [0]);
5274                         MonoClass *klass = mono_class_from_mono_type (t);
5275
5276                         ins = NULL;
5277
5278                         mono_class_init (klass);
5279                         if (MONO_TYPE_IS_REFERENCE (t))
5280                                 EMIT_NEW_ICONST (cfg, ins, 1);
5281                         else if (MONO_TYPE_IS_PRIMITIVE (t))
5282                                 EMIT_NEW_ICONST (cfg, ins, 0);
5283                         else if (cfg->gshared && (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR) && !mini_type_var_is_vt (t))
5284                                 EMIT_NEW_ICONST (cfg, ins, 1);
5285                         else if (!cfg->gshared || !mini_class_check_context_used (cfg, klass))
5286                                 EMIT_NEW_ICONST (cfg, ins, klass->has_references ? 1 : 0);
5287                         else {
5288                                 g_assert (cfg->gshared);
5289
5290                                 int context_used = mini_class_check_context_used (cfg, klass);
5291
5292                                 /* This returns 1 or 2 */
5293                                 MonoInst *info = mini_emit_get_rgctx_klass (cfg, context_used, klass,   MONO_RGCTX_INFO_CLASS_IS_REF_OR_CONTAINS_REFS);
5294                                 int dreg = alloc_ireg (cfg);
5295                                 EMIT_NEW_BIALU_IMM (cfg, ins, OP_ISUB_IMM, dreg, info->dreg, 1);
5296                         }
5297
5298                         return ins;
5299                 } else
5300                         return NULL;
5301         } else if (cmethod->klass == mono_defaults.monitor_class) {
5302                 gboolean is_enter = FALSE;
5303                 gboolean is_v4 = FALSE;
5304
5305                 if (!strcmp (cmethod->name, "Enter") && fsig->param_count == 2 && fsig->params [1]->byref) {
5306                         is_enter = TRUE;
5307                         is_v4 = TRUE;
5308                 }
5309                 if (!strcmp (cmethod->name, "Enter") && fsig->param_count == 1)
5310                         is_enter = TRUE;
5311
5312                 if (is_enter) {
5313                         /*
5314                          * To make async stack traces work, icalls which can block should have a wrapper.
5315                          * For Monitor.Enter, emit two calls: a fastpath which doesn't have a wrapper, and a slowpath, which does.
5316                          */
5317                         MonoBasicBlock *end_bb;
5318
5319                         NEW_BBLOCK (cfg, end_bb);
5320
5321                         ins = mono_emit_jit_icall (cfg, is_v4 ? (gpointer)mono_monitor_enter_v4_fast : (gpointer)mono_monitor_enter_fast, args);
5322                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ICOMPARE_IMM, -1, ins->dreg, 0);
5323                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBNE_UN, end_bb);
5324                         ins = mono_emit_jit_icall (cfg, is_v4 ? (gpointer)mono_monitor_enter_v4_internal : (gpointer)mono_monitor_enter_internal, args);
5325                         MONO_START_BB (cfg, end_bb);
5326                         return ins;
5327                 }
5328         } else if (cmethod->klass == mono_defaults.thread_class) {
5329                 if (strcmp (cmethod->name, "SpinWait_nop") == 0 && fsig->param_count == 0) {
5330                         MONO_INST_NEW (cfg, ins, OP_RELAXED_NOP);
5331                         MONO_ADD_INS (cfg->cbb, ins);
5332                         return ins;
5333                 } else if (strcmp (cmethod->name, "MemoryBarrier") == 0 && fsig->param_count == 0) {
5334                         return mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
5335                 } else if (!strcmp (cmethod->name, "VolatileRead") && fsig->param_count == 1) {
5336                         guint32 opcode = 0;
5337                         gboolean is_ref = mini_type_is_reference (fsig->params [0]);
5338
5339                         if (fsig->params [0]->type == MONO_TYPE_I1)
5340                                 opcode = OP_LOADI1_MEMBASE;
5341                         else if (fsig->params [0]->type == MONO_TYPE_U1)
5342                                 opcode = OP_LOADU1_MEMBASE;
5343                         else if (fsig->params [0]->type == MONO_TYPE_I2)
5344                                 opcode = OP_LOADI2_MEMBASE;
5345                         else if (fsig->params [0]->type == MONO_TYPE_U2)
5346                                 opcode = OP_LOADU2_MEMBASE;
5347                         else if (fsig->params [0]->type == MONO_TYPE_I4)
5348                                 opcode = OP_LOADI4_MEMBASE;
5349                         else if (fsig->params [0]->type == MONO_TYPE_U4)
5350                                 opcode = OP_LOADU4_MEMBASE;
5351                         else if (fsig->params [0]->type == MONO_TYPE_I8 || fsig->params [0]->type == MONO_TYPE_U8)
5352                                 opcode = OP_LOADI8_MEMBASE;
5353                         else if (fsig->params [0]->type == MONO_TYPE_R4)
5354                                 opcode = OP_LOADR4_MEMBASE;
5355                         else if (fsig->params [0]->type == MONO_TYPE_R8)
5356                                 opcode = OP_LOADR8_MEMBASE;
5357                         else if (is_ref || fsig->params [0]->type == MONO_TYPE_I || fsig->params [0]->type == MONO_TYPE_U)
5358                                 opcode = OP_LOAD_MEMBASE;
5359
5360                         if (opcode) {
5361                                 MONO_INST_NEW (cfg, ins, opcode);
5362                                 ins->inst_basereg = args [0]->dreg;
5363                                 ins->inst_offset = 0;
5364                                 MONO_ADD_INS (cfg->cbb, ins);
5365
5366                                 switch (fsig->params [0]->type) {
5367                                 case MONO_TYPE_I1:
5368                                 case MONO_TYPE_U1:
5369                                 case MONO_TYPE_I2:
5370                                 case MONO_TYPE_U2:
5371                                 case MONO_TYPE_I4:
5372                                 case MONO_TYPE_U4:
5373                                         ins->dreg = mono_alloc_ireg (cfg);
5374                                         ins->type = STACK_I4;
5375                                         break;
5376                                 case MONO_TYPE_I8:
5377                                 case MONO_TYPE_U8:
5378                                         ins->dreg = mono_alloc_lreg (cfg);
5379                                         ins->type = STACK_I8;
5380                                         break;
5381                                 case MONO_TYPE_I:
5382                                 case MONO_TYPE_U:
5383                                         ins->dreg = mono_alloc_ireg (cfg);
5384 #if SIZEOF_REGISTER == 8
5385                                         ins->type = STACK_I8;
5386 #else
5387                                         ins->type = STACK_I4;
5388 #endif
5389                                         break;
5390                                 case MONO_TYPE_R4:
5391                                 case MONO_TYPE_R8:
5392                                         ins->dreg = mono_alloc_freg (cfg);
5393                                         ins->type = STACK_R8;
5394                                         break;
5395                                 default:
5396                                         g_assert (mini_type_is_reference (fsig->params [0]));
5397                                         ins->dreg = mono_alloc_ireg_ref (cfg);
5398                                         ins->type = STACK_OBJ;
5399                                         break;
5400                                 }
5401
5402                                 if (opcode == OP_LOADI8_MEMBASE)
5403                                         ins = mono_decompose_opcode (cfg, ins);
5404
5405                                 mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
5406
5407                                 return ins;
5408                         }
5409                 } else if (!strcmp (cmethod->name, "VolatileWrite") && fsig->param_count == 2) {
5410                         guint32 opcode = 0;
5411                         gboolean is_ref = mini_type_is_reference (fsig->params [0]);
5412
5413                         if (fsig->params [0]->type == MONO_TYPE_I1 || fsig->params [0]->type == MONO_TYPE_U1)
5414                                 opcode = OP_STOREI1_MEMBASE_REG;
5415                         else if (fsig->params [0]->type == MONO_TYPE_I2 || fsig->params [0]->type == MONO_TYPE_U2)
5416                                 opcode = OP_STOREI2_MEMBASE_REG;
5417                         else if (fsig->params [0]->type == MONO_TYPE_I4 || fsig->params [0]->type == MONO_TYPE_U4)
5418                                 opcode = OP_STOREI4_MEMBASE_REG;
5419                         else if (fsig->params [0]->type == MONO_TYPE_I8 || fsig->params [0]->type == MONO_TYPE_U8)
5420                                 opcode = OP_STOREI8_MEMBASE_REG;
5421                         else if (fsig->params [0]->type == MONO_TYPE_R4)
5422                                 opcode = OP_STORER4_MEMBASE_REG;
5423                         else if (fsig->params [0]->type == MONO_TYPE_R8)
5424                                 opcode = OP_STORER8_MEMBASE_REG;
5425                         else if (is_ref || fsig->params [0]->type == MONO_TYPE_I || fsig->params [0]->type == MONO_TYPE_U)
5426                                 opcode = OP_STORE_MEMBASE_REG;
5427
5428                         if (opcode) {
5429                                 mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
5430
5431                                 MONO_INST_NEW (cfg, ins, opcode);
5432                                 ins->sreg1 = args [1]->dreg;
5433                                 ins->inst_destbasereg = args [0]->dreg;
5434                                 ins->inst_offset = 0;
5435                                 MONO_ADD_INS (cfg->cbb, ins);
5436
5437                                 if (opcode == OP_STOREI8_MEMBASE_REG)
5438                                         ins = mono_decompose_opcode (cfg, ins);
5439
5440                                 return ins;
5441                         }
5442                 }
5443         } else if (cmethod->klass->image == mono_defaults.corlib &&
5444                            (strcmp (cmethod->klass->name_space, "System.Threading") == 0) &&
5445                            (strcmp (cmethod->klass->name, "Interlocked") == 0)) {
5446                 ins = NULL;
5447
5448 #if SIZEOF_REGISTER == 8
5449                 if (!cfg->llvm_only && strcmp (cmethod->name, "Read") == 0 && fsig->param_count == 1 && (fsig->params [0]->type == MONO_TYPE_I8)) {
5450                         if (!cfg->llvm_only && mono_arch_opcode_supported (OP_ATOMIC_LOAD_I8)) {
5451                                 MONO_INST_NEW (cfg, ins, OP_ATOMIC_LOAD_I8);
5452                                 ins->dreg = mono_alloc_preg (cfg);
5453                                 ins->sreg1 = args [0]->dreg;
5454                                 ins->type = STACK_I8;
5455                                 ins->backend.memory_barrier_kind = MONO_MEMORY_BARRIER_SEQ;
5456                                 MONO_ADD_INS (cfg->cbb, ins);
5457                         } else {
5458                                 MonoInst *load_ins;
5459
5460                                 mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
5461
5462                                 /* 64 bit reads are already atomic */
5463                                 MONO_INST_NEW (cfg, load_ins, OP_LOADI8_MEMBASE);
5464                                 load_ins->dreg = mono_alloc_preg (cfg);
5465                                 load_ins->inst_basereg = args [0]->dreg;
5466                                 load_ins->inst_offset = 0;
5467                                 load_ins->type = STACK_I8;
5468                                 MONO_ADD_INS (cfg->cbb, load_ins);
5469
5470                                 mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
5471
5472                                 ins = load_ins;
5473                         }
5474                 }
5475 #endif
5476
5477                 if (strcmp (cmethod->name, "Increment") == 0 && fsig->param_count == 1) {
5478                         MonoInst *ins_iconst;
5479                         guint32 opcode = 0;
5480
5481                         if (fsig->params [0]->type == MONO_TYPE_I4) {
5482                                 opcode = OP_ATOMIC_ADD_I4;
5483                                 cfg->has_atomic_add_i4 = TRUE;
5484                         }
5485 #if SIZEOF_REGISTER == 8
5486                         else if (fsig->params [0]->type == MONO_TYPE_I8)
5487                                 opcode = OP_ATOMIC_ADD_I8;
5488 #endif
5489                         if (opcode) {
5490                                 if (!mono_arch_opcode_supported (opcode))
5491                                         return NULL;
5492                                 MONO_INST_NEW (cfg, ins_iconst, OP_ICONST);
5493                                 ins_iconst->inst_c0 = 1;
5494                                 ins_iconst->dreg = mono_alloc_ireg (cfg);
5495                                 MONO_ADD_INS (cfg->cbb, ins_iconst);
5496
5497                                 MONO_INST_NEW (cfg, ins, opcode);
5498                                 ins->dreg = mono_alloc_ireg (cfg);
5499                                 ins->inst_basereg = args [0]->dreg;
5500                                 ins->inst_offset = 0;
5501                                 ins->sreg2 = ins_iconst->dreg;
5502                                 ins->type = (opcode == OP_ATOMIC_ADD_I4) ? STACK_I4 : STACK_I8;
5503                                 MONO_ADD_INS (cfg->cbb, ins);
5504                         }
5505                 } else if (strcmp (cmethod->name, "Decrement") == 0 && fsig->param_count == 1) {
5506                         MonoInst *ins_iconst;
5507                         guint32 opcode = 0;
5508
5509                         if (fsig->params [0]->type == MONO_TYPE_I4) {
5510                                 opcode = OP_ATOMIC_ADD_I4;
5511                                 cfg->has_atomic_add_i4 = TRUE;
5512                         }
5513 #if SIZEOF_REGISTER == 8
5514                         else if (fsig->params [0]->type == MONO_TYPE_I8)
5515                                 opcode = OP_ATOMIC_ADD_I8;
5516 #endif
5517                         if (opcode) {
5518                                 if (!mono_arch_opcode_supported (opcode))
5519                                         return NULL;
5520                                 MONO_INST_NEW (cfg, ins_iconst, OP_ICONST);
5521                                 ins_iconst->inst_c0 = -1;
5522                                 ins_iconst->dreg = mono_alloc_ireg (cfg);
5523                                 MONO_ADD_INS (cfg->cbb, ins_iconst);
5524
5525                                 MONO_INST_NEW (cfg, ins, opcode);
5526                                 ins->dreg = mono_alloc_ireg (cfg);
5527                                 ins->inst_basereg = args [0]->dreg;
5528                                 ins->inst_offset = 0;
5529                                 ins->sreg2 = ins_iconst->dreg;
5530                                 ins->type = (opcode == OP_ATOMIC_ADD_I4) ? STACK_I4 : STACK_I8;
5531                                 MONO_ADD_INS (cfg->cbb, ins);
5532                         }
5533                 } else if (strcmp (cmethod->name, "Add") == 0 && fsig->param_count == 2) {
5534                         guint32 opcode = 0;
5535
5536                         if (fsig->params [0]->type == MONO_TYPE_I4) {
5537                                 opcode = OP_ATOMIC_ADD_I4;
5538                                 cfg->has_atomic_add_i4 = TRUE;
5539                         }
5540 #if SIZEOF_REGISTER == 8
5541                         else if (fsig->params [0]->type == MONO_TYPE_I8)
5542                                 opcode = OP_ATOMIC_ADD_I8;
5543 #endif
5544                         if (opcode) {
5545                                 if (!mono_arch_opcode_supported (opcode))
5546                                         return NULL;
5547                                 MONO_INST_NEW (cfg, ins, opcode);
5548                                 ins->dreg = mono_alloc_ireg (cfg);
5549                                 ins->inst_basereg = args [0]->dreg;
5550                                 ins->inst_offset = 0;
5551                                 ins->sreg2 = args [1]->dreg;
5552                                 ins->type = (opcode == OP_ATOMIC_ADD_I4) ? STACK_I4 : STACK_I8;
5553                                 MONO_ADD_INS (cfg->cbb, ins);
5554                         }
5555                 }
5556                 else if (strcmp (cmethod->name, "Exchange") == 0 && fsig->param_count == 2) {
5557                         MonoInst *f2i = NULL, *i2f;
5558                         guint32 opcode, f2i_opcode, i2f_opcode;
5559                         gboolean is_ref = mini_type_is_reference (fsig->params [0]);
5560                         gboolean is_float = fsig->params [0]->type == MONO_TYPE_R4 || fsig->params [0]->type == MONO_TYPE_R8;
5561
5562                         if (fsig->params [0]->type == MONO_TYPE_I4 ||
5563                             fsig->params [0]->type == MONO_TYPE_R4) {
5564                                 opcode = OP_ATOMIC_EXCHANGE_I4;
5565                                 f2i_opcode = OP_MOVE_F_TO_I4;
5566                                 i2f_opcode = OP_MOVE_I4_TO_F;
5567                                 cfg->has_atomic_exchange_i4 = TRUE;
5568                         }
5569 #if SIZEOF_REGISTER == 8
5570                         else if (is_ref ||
5571                                  fsig->params [0]->type == MONO_TYPE_I8 ||
5572                                  fsig->params [0]->type == MONO_TYPE_R8 ||
5573                                  fsig->params [0]->type == MONO_TYPE_I) {
5574                                 opcode = OP_ATOMIC_EXCHANGE_I8;
5575                                 f2i_opcode = OP_MOVE_F_TO_I8;
5576                                 i2f_opcode = OP_MOVE_I8_TO_F;
5577                         }
5578 #else
5579                         else if (is_ref || fsig->params [0]->type == MONO_TYPE_I) {
5580                                 opcode = OP_ATOMIC_EXCHANGE_I4;
5581                                 cfg->has_atomic_exchange_i4 = TRUE;
5582                         }
5583 #endif
5584                         else
5585                                 return NULL;
5586
5587                         if (!mono_arch_opcode_supported (opcode))
5588                                 return NULL;
5589
5590                         if (is_float) {
5591                                 /* TODO: Decompose these opcodes instead of bailing here. */
5592                                 if (COMPILE_SOFT_FLOAT (cfg))
5593                                         return NULL;
5594
5595                                 MONO_INST_NEW (cfg, f2i, f2i_opcode);
5596                                 f2i->dreg = mono_alloc_ireg (cfg);
5597                                 f2i->sreg1 = args [1]->dreg;
5598                                 if (f2i_opcode == OP_MOVE_F_TO_I4)
5599                                         f2i->backend.spill_var = mini_get_int_to_float_spill_area (cfg);
5600                                 MONO_ADD_INS (cfg->cbb, f2i);
5601                         }
5602
5603                         MONO_INST_NEW (cfg, ins, opcode);
5604                         ins->dreg = is_ref ? mono_alloc_ireg_ref (cfg) : mono_alloc_ireg (cfg);
5605                         ins->inst_basereg = args [0]->dreg;
5606                         ins->inst_offset = 0;
5607                         ins->sreg2 = is_float ? f2i->dreg : args [1]->dreg;
5608                         MONO_ADD_INS (cfg->cbb, ins);
5609
5610                         switch (fsig->params [0]->type) {
5611                         case MONO_TYPE_I4:
5612                                 ins->type = STACK_I4;
5613                                 break;
5614                         case MONO_TYPE_I8:
5615                                 ins->type = STACK_I8;
5616                                 break;
5617                         case MONO_TYPE_I:
5618 #if SIZEOF_REGISTER == 8
5619                                 ins->type = STACK_I8;
5620 #else
5621                                 ins->type = STACK_I4;
5622 #endif
5623                                 break;
5624                         case MONO_TYPE_R4:
5625                         case MONO_TYPE_R8:
5626                                 ins->type = STACK_R8;
5627                                 break;
5628                         default:
5629                                 g_assert (mini_type_is_reference (fsig->params [0]));
5630                                 ins->type = STACK_OBJ;
5631                                 break;
5632                         }
5633
5634                         if (is_float) {
5635                                 MONO_INST_NEW (cfg, i2f, i2f_opcode);
5636                                 i2f->dreg = mono_alloc_freg (cfg);
5637                                 i2f->sreg1 = ins->dreg;
5638                                 i2f->type = STACK_R8;
5639                                 if (i2f_opcode == OP_MOVE_I4_TO_F)
5640                                         i2f->backend.spill_var = mini_get_int_to_float_spill_area (cfg);
5641                                 MONO_ADD_INS (cfg->cbb, i2f);
5642
5643                                 ins = i2f;
5644                         }
5645
5646                         if (cfg->gen_write_barriers && is_ref)
5647                                 mini_emit_write_barrier (cfg, args [0], args [1]);
5648                 }
5649                 else if ((strcmp (cmethod->name, "CompareExchange") == 0) && fsig->param_count == 3) {
5650                         MonoInst *f2i_new = NULL, *f2i_cmp = NULL, *i2f;
5651                         guint32 opcode, f2i_opcode, i2f_opcode;
5652                         gboolean is_ref = mini_type_is_reference (fsig->params [1]);
5653                         gboolean is_float = fsig->params [1]->type == MONO_TYPE_R4 || fsig->params [1]->type == MONO_TYPE_R8;
5654
5655                         if (fsig->params [1]->type == MONO_TYPE_I4 ||
5656                             fsig->params [1]->type == MONO_TYPE_R4) {
5657                                 opcode = OP_ATOMIC_CAS_I4;
5658                                 f2i_opcode = OP_MOVE_F_TO_I4;
5659                                 i2f_opcode = OP_MOVE_I4_TO_F;
5660                                 cfg->has_atomic_cas_i4 = TRUE;
5661                         }
5662 #if SIZEOF_REGISTER == 8
5663                         else if (is_ref ||
5664                                  fsig->params [1]->type == MONO_TYPE_I8 ||
5665                                  fsig->params [1]->type == MONO_TYPE_R8 ||
5666                                  fsig->params [1]->type == MONO_TYPE_I) {
5667                                 opcode = OP_ATOMIC_CAS_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 [1]->type == MONO_TYPE_I) {
5673                                 opcode = OP_ATOMIC_CAS_I4;
5674                                 cfg->has_atomic_cas_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_new, f2i_opcode);
5689                                 f2i_new->dreg = mono_alloc_ireg (cfg);
5690                                 f2i_new->sreg1 = args [1]->dreg;
5691                                 if (f2i_opcode == OP_MOVE_F_TO_I4)
5692                                         f2i_new->backend.spill_var = mini_get_int_to_float_spill_area (cfg);
5693                                 MONO_ADD_INS (cfg->cbb, f2i_new);
5694
5695                                 MONO_INST_NEW (cfg, f2i_cmp, f2i_opcode);
5696                                 f2i_cmp->dreg = mono_alloc_ireg (cfg);
5697                                 f2i_cmp->sreg1 = args [2]->dreg;
5698                                 if (f2i_opcode == OP_MOVE_F_TO_I4)
5699                                         f2i_cmp->backend.spill_var = mini_get_int_to_float_spill_area (cfg);
5700                                 MONO_ADD_INS (cfg->cbb, f2i_cmp);
5701                         }
5702
5703                         MONO_INST_NEW (cfg, ins, opcode);
5704                         ins->dreg = is_ref ? alloc_ireg_ref (cfg) : alloc_ireg (cfg);
5705                         ins->sreg1 = args [0]->dreg;
5706                         ins->sreg2 = is_float ? f2i_new->dreg : args [1]->dreg;
5707                         ins->sreg3 = is_float ? f2i_cmp->dreg : args [2]->dreg;
5708                         MONO_ADD_INS (cfg->cbb, ins);
5709
5710                         switch (fsig->params [1]->type) {
5711                         case MONO_TYPE_I4:
5712                                 ins->type = STACK_I4;
5713                                 break;
5714                         case MONO_TYPE_I8:
5715                                 ins->type = STACK_I8;
5716                                 break;
5717                         case MONO_TYPE_I:
5718 #if SIZEOF_REGISTER == 8
5719                                 ins->type = STACK_I8;
5720 #else
5721                                 ins->type = STACK_I4;
5722 #endif
5723                                 break;
5724                         case MONO_TYPE_R4:
5725                                 ins->type = cfg->r4_stack_type;
5726                                 break;
5727                         case MONO_TYPE_R8:
5728                                 ins->type = STACK_R8;
5729                                 break;
5730                         default:
5731                                 g_assert (mini_type_is_reference (fsig->params [1]));
5732                                 ins->type = STACK_OBJ;
5733                                 break;
5734                         }
5735
5736                         if (is_float) {
5737                                 MONO_INST_NEW (cfg, i2f, i2f_opcode);
5738                                 i2f->dreg = mono_alloc_freg (cfg);
5739                                 i2f->sreg1 = ins->dreg;
5740                                 i2f->type = STACK_R8;
5741                                 if (i2f_opcode == OP_MOVE_I4_TO_F)
5742                                         i2f->backend.spill_var = mini_get_int_to_float_spill_area (cfg);
5743                                 MONO_ADD_INS (cfg->cbb, i2f);
5744
5745                                 ins = i2f;
5746                         }
5747
5748                         if (cfg->gen_write_barriers && is_ref)
5749                                 mini_emit_write_barrier (cfg, args [0], args [1]);
5750                 }
5751                 else if ((strcmp (cmethod->name, "CompareExchange") == 0) && fsig->param_count == 4 &&
5752                          fsig->params [1]->type == MONO_TYPE_I4) {
5753                         MonoInst *cmp, *ceq;
5754
5755                         if (!mono_arch_opcode_supported (OP_ATOMIC_CAS_I4))
5756                                 return NULL;
5757
5758                         /* int32 r = CAS (location, value, comparand); */
5759                         MONO_INST_NEW (cfg, ins, OP_ATOMIC_CAS_I4);
5760                         ins->dreg = alloc_ireg (cfg);
5761                         ins->sreg1 = args [0]->dreg;
5762                         ins->sreg2 = args [1]->dreg;
5763                         ins->sreg3 = args [2]->dreg;
5764                         ins->type = STACK_I4;
5765                         MONO_ADD_INS (cfg->cbb, ins);
5766
5767                         /* bool result = r == comparand; */
5768                         MONO_INST_NEW (cfg, cmp, OP_ICOMPARE);
5769                         cmp->sreg1 = ins->dreg;
5770                         cmp->sreg2 = args [2]->dreg;
5771                         cmp->type = STACK_I4;
5772                         MONO_ADD_INS (cfg->cbb, cmp);
5773
5774                         MONO_INST_NEW (cfg, ceq, OP_ICEQ);
5775                         ceq->dreg = alloc_ireg (cfg);
5776                         ceq->type = STACK_I4;
5777                         MONO_ADD_INS (cfg->cbb, ceq);
5778
5779                         /* *success = result; */
5780                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI1_MEMBASE_REG, args [3]->dreg, 0, ceq->dreg);
5781
5782                         cfg->has_atomic_cas_i4 = TRUE;
5783                 }
5784                 else if (strcmp (cmethod->name, "MemoryBarrier") == 0 && fsig->param_count == 0)
5785                         ins = mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
5786
5787                 if (ins)
5788                         return ins;
5789         } else if (cmethod->klass->image == mono_defaults.corlib &&
5790                            (strcmp (cmethod->klass->name_space, "System.Threading") == 0) &&
5791                            (strcmp (cmethod->klass->name, "Volatile") == 0)) {
5792                 ins = NULL;
5793
5794                 if (!cfg->llvm_only && !strcmp (cmethod->name, "Read") && fsig->param_count == 1) {
5795                         guint32 opcode = 0;
5796                         MonoType *t = fsig->params [0];
5797                         gboolean is_ref;
5798                         gboolean is_float = t->type == MONO_TYPE_R4 || t->type == MONO_TYPE_R8;
5799
5800                         g_assert (t->byref);
5801                         /* t is a byref type, so the reference check is more complicated */
5802                         is_ref = mini_type_is_reference (&mono_class_from_mono_type (t)->byval_arg);
5803                         if (t->type == MONO_TYPE_I1)
5804                                 opcode = OP_ATOMIC_LOAD_I1;
5805                         else if (t->type == MONO_TYPE_U1 || t->type == MONO_TYPE_BOOLEAN)
5806                                 opcode = OP_ATOMIC_LOAD_U1;
5807                         else if (t->type == MONO_TYPE_I2)
5808                                 opcode = OP_ATOMIC_LOAD_I2;
5809                         else if (t->type == MONO_TYPE_U2)
5810                                 opcode = OP_ATOMIC_LOAD_U2;
5811                         else if (t->type == MONO_TYPE_I4)
5812                                 opcode = OP_ATOMIC_LOAD_I4;
5813                         else if (t->type == MONO_TYPE_U4)
5814                                 opcode = OP_ATOMIC_LOAD_U4;
5815                         else if (t->type == MONO_TYPE_R4)
5816                                 opcode = OP_ATOMIC_LOAD_R4;
5817                         else if (t->type == MONO_TYPE_R8)
5818                                 opcode = OP_ATOMIC_LOAD_R8;
5819 #if SIZEOF_REGISTER == 8
5820                         else if (t->type == MONO_TYPE_I8 || t->type == MONO_TYPE_I)
5821                                 opcode = OP_ATOMIC_LOAD_I8;
5822                         else if (is_ref || t->type == MONO_TYPE_U8 || t->type == MONO_TYPE_U)
5823                                 opcode = OP_ATOMIC_LOAD_U8;
5824 #else
5825                         else if (t->type == MONO_TYPE_I)
5826                                 opcode = OP_ATOMIC_LOAD_I4;
5827                         else if (is_ref || t->type == MONO_TYPE_U)
5828                                 opcode = OP_ATOMIC_LOAD_U4;
5829 #endif
5830
5831                         if (opcode) {
5832                                 if (!mono_arch_opcode_supported (opcode))
5833                                         return NULL;
5834
5835                                 MONO_INST_NEW (cfg, ins, opcode);
5836                                 ins->dreg = is_ref ? mono_alloc_ireg_ref (cfg) : (is_float ? mono_alloc_freg (cfg) : mono_alloc_ireg (cfg));
5837                                 ins->sreg1 = args [0]->dreg;
5838                                 ins->backend.memory_barrier_kind = MONO_MEMORY_BARRIER_ACQ;
5839                                 MONO_ADD_INS (cfg->cbb, ins);
5840
5841                                 switch (t->type) {
5842                                 case MONO_TYPE_BOOLEAN:
5843                                 case MONO_TYPE_I1:
5844                                 case MONO_TYPE_U1:
5845                                 case MONO_TYPE_I2:
5846                                 case MONO_TYPE_U2:
5847                                 case MONO_TYPE_I4:
5848                                 case MONO_TYPE_U4:
5849                                         ins->type = STACK_I4;
5850                                         break;
5851                                 case MONO_TYPE_I8:
5852                                 case MONO_TYPE_U8:
5853                                         ins->type = STACK_I8;
5854                                         break;
5855                                 case MONO_TYPE_I:
5856                                 case MONO_TYPE_U:
5857 #if SIZEOF_REGISTER == 8
5858                                         ins->type = STACK_I8;
5859 #else
5860                                         ins->type = STACK_I4;
5861 #endif
5862                                         break;
5863                                 case MONO_TYPE_R4:
5864                                         ins->type = cfg->r4_stack_type;
5865                                         break;
5866                                 case MONO_TYPE_R8:
5867                                         ins->type = STACK_R8;
5868                                         break;
5869                                 default:
5870                                         g_assert (is_ref);
5871                                         ins->type = STACK_OBJ;
5872                                         break;
5873                                 }
5874                         }
5875                 }
5876
5877                 if (!cfg->llvm_only && !strcmp (cmethod->name, "Write") && fsig->param_count == 2) {
5878                         guint32 opcode = 0;
5879                         MonoType *t = fsig->params [0];
5880                         gboolean is_ref;
5881
5882                         g_assert (t->byref);
5883                         is_ref = mini_type_is_reference (&mono_class_from_mono_type (t)->byval_arg);
5884                         if (t->type == MONO_TYPE_I1)
5885                                 opcode = OP_ATOMIC_STORE_I1;
5886                         else if (t->type == MONO_TYPE_U1 || t->type == MONO_TYPE_BOOLEAN)
5887                                 opcode = OP_ATOMIC_STORE_U1;
5888                         else if (t->type == MONO_TYPE_I2)
5889                                 opcode = OP_ATOMIC_STORE_I2;
5890                         else if (t->type == MONO_TYPE_U2)
5891                                 opcode = OP_ATOMIC_STORE_U2;
5892                         else if (t->type == MONO_TYPE_I4)
5893                                 opcode = OP_ATOMIC_STORE_I4;
5894                         else if (t->type == MONO_TYPE_U4)
5895                                 opcode = OP_ATOMIC_STORE_U4;
5896                         else if (t->type == MONO_TYPE_R4)
5897                                 opcode = OP_ATOMIC_STORE_R4;
5898                         else if (t->type == MONO_TYPE_R8)
5899                                 opcode = OP_ATOMIC_STORE_R8;
5900 #if SIZEOF_REGISTER == 8
5901                         else if (t->type == MONO_TYPE_I8 || t->type == MONO_TYPE_I)
5902                                 opcode = OP_ATOMIC_STORE_I8;
5903                         else if (is_ref || t->type == MONO_TYPE_U8 || t->type == MONO_TYPE_U)
5904                                 opcode = OP_ATOMIC_STORE_U8;
5905 #else
5906                         else if (t->type == MONO_TYPE_I)
5907                                 opcode = OP_ATOMIC_STORE_I4;
5908                         else if (is_ref || t->type == MONO_TYPE_U)
5909                                 opcode = OP_ATOMIC_STORE_U4;
5910 #endif
5911
5912                         if (opcode) {
5913                                 if (!mono_arch_opcode_supported (opcode))
5914                                         return NULL;
5915
5916                                 MONO_INST_NEW (cfg, ins, opcode);
5917                                 ins->dreg = args [0]->dreg;
5918                                 ins->sreg1 = args [1]->dreg;
5919                                 ins->backend.memory_barrier_kind = MONO_MEMORY_BARRIER_REL;
5920                                 MONO_ADD_INS (cfg->cbb, ins);
5921
5922                                 if (cfg->gen_write_barriers && is_ref)
5923                                         mini_emit_write_barrier (cfg, args [0], args [1]);
5924                         }
5925                 }
5926
5927                 if (ins)
5928                         return ins;
5929         } else if (cmethod->klass->image == mono_defaults.corlib &&
5930                            (strcmp (cmethod->klass->name_space, "System.Diagnostics") == 0) &&
5931                            (strcmp (cmethod->klass->name, "Debugger") == 0)) {
5932                 if (!strcmp (cmethod->name, "Break") && fsig->param_count == 0) {
5933                         if (should_insert_brekpoint (cfg->method)) {
5934                                 ins = mono_emit_jit_icall (cfg, mono_debugger_agent_user_break, NULL);
5935                         } else {
5936                                 MONO_INST_NEW (cfg, ins, OP_NOP);
5937                                 MONO_ADD_INS (cfg->cbb, ins);
5938                         }
5939                         return ins;
5940                 }
5941         } else if (cmethod->klass->image == mono_defaults.corlib &&
5942                    (strcmp (cmethod->klass->name_space, "System") == 0) &&
5943                    (strcmp (cmethod->klass->name, "Environment") == 0)) {
5944                 if (!strcmp (cmethod->name, "get_IsRunningOnWindows") && fsig->param_count == 0) {
5945 #ifdef TARGET_WIN32
5946                         EMIT_NEW_ICONST (cfg, ins, 1);
5947 #else
5948                         EMIT_NEW_ICONST (cfg, ins, 0);
5949 #endif
5950                 }
5951         } else if (cmethod->klass->image == mono_defaults.corlib &&
5952                            (strcmp (cmethod->klass->name_space, "System.Reflection") == 0) &&
5953                            (strcmp (cmethod->klass->name, "Assembly") == 0)) {
5954                 if (cfg->llvm_only && !strcmp (cmethod->name, "GetExecutingAssembly")) {
5955                         /* No stack walks are currently available, so implement this as an intrinsic */
5956                         MonoInst *assembly_ins;
5957
5958                         EMIT_NEW_AOTCONST (cfg, assembly_ins, MONO_PATCH_INFO_IMAGE, cfg->method->klass->image);
5959                         ins = mono_emit_jit_icall (cfg, mono_get_assembly_object, &assembly_ins);
5960                         return ins;
5961                 }
5962         } else if (cmethod->klass->image == mono_defaults.corlib &&
5963                            (strcmp (cmethod->klass->name_space, "System.Reflection") == 0) &&
5964                            (strcmp (cmethod->klass->name, "MethodBase") == 0)) {
5965                 if (cfg->llvm_only && !strcmp (cmethod->name, "GetCurrentMethod")) {
5966                         /* No stack walks are currently available, so implement this as an intrinsic */
5967                         MonoInst *method_ins;
5968                         MonoMethod *declaring = cfg->method;
5969
5970                         /* This returns the declaring generic method */
5971                         if (declaring->is_inflated)
5972                                 declaring = ((MonoMethodInflated*)cfg->method)->declaring;
5973                         EMIT_NEW_AOTCONST (cfg, method_ins, MONO_PATCH_INFO_METHODCONST, declaring);
5974                         ins = mono_emit_jit_icall (cfg, mono_get_method_object, &method_ins);
5975                         cfg->no_inline = TRUE;
5976                         if (cfg->method != cfg->current_method)
5977                                 inline_failure (cfg, "MethodBase:GetCurrentMethod ()");
5978                         return ins;
5979                 }
5980         } else if (cmethod->klass == mono_defaults.math_class) {
5981                 /* 
5982                  * There is general branchless code for Min/Max, but it does not work for 
5983                  * all inputs:
5984                  * http://everything2.com/?node_id=1051618
5985                  */
5986         } else if (cmethod->klass == mono_defaults.systemtype_class && !strcmp (cmethod->name, "op_Equality")) {
5987                 EMIT_NEW_BIALU (cfg, ins, OP_COMPARE, -1, args [0]->dreg, args [1]->dreg);
5988                 MONO_INST_NEW (cfg, ins, OP_PCEQ);
5989                 ins->dreg = alloc_preg (cfg);
5990                 ins->type = STACK_I4;
5991                 MONO_ADD_INS (cfg->cbb, ins);
5992                 return ins;
5993         } else if (((!strcmp (cmethod->klass->image->assembly->aname.name, "MonoMac") ||
5994                     !strcmp (cmethod->klass->image->assembly->aname.name, "monotouch")) &&
5995                                 !strcmp (cmethod->klass->name_space, "XamCore.ObjCRuntime") &&
5996                                 !strcmp (cmethod->klass->name, "Selector")) ||
5997                            ((!strcmp (cmethod->klass->image->assembly->aname.name, "Xamarin.iOS") ||
5998                                  !strcmp (cmethod->klass->image->assembly->aname.name, "Xamarin.Mac")) &&
5999                                 !strcmp (cmethod->klass->name_space, "ObjCRuntime") &&
6000                                 !strcmp (cmethod->klass->name, "Selector"))
6001                            ) {
6002                 if ((cfg->backend->have_objc_get_selector || cfg->compile_llvm) &&
6003                         !strcmp (cmethod->name, "GetHandle") && fsig->param_count == 1 &&
6004                     (args [0]->opcode == OP_GOT_ENTRY || args [0]->opcode == OP_AOTCONST) &&
6005                     cfg->compile_aot) {
6006                         MonoInst *pi;
6007                         MonoJumpInfoToken *ji;
6008                         char *s;
6009
6010                         if (args [0]->opcode == OP_GOT_ENTRY) {
6011                                 pi = (MonoInst *)args [0]->inst_p1;
6012                                 g_assert (pi->opcode == OP_PATCH_INFO);
6013                                 g_assert (GPOINTER_TO_INT (pi->inst_p1) == MONO_PATCH_INFO_LDSTR);
6014                                 ji = (MonoJumpInfoToken *)pi->inst_p0;
6015                         } else {
6016                                 g_assert (GPOINTER_TO_INT (args [0]->inst_p1) == MONO_PATCH_INFO_LDSTR);
6017                                 ji = (MonoJumpInfoToken *)args [0]->inst_p0;
6018                         }
6019
6020                         NULLIFY_INS (args [0]);
6021
6022                         s = mono_ldstr_utf8 (ji->image, mono_metadata_token_index (ji->token), &cfg->error);
6023                         return_val_if_nok (&cfg->error, NULL);
6024
6025                         MONO_INST_NEW (cfg, ins, OP_OBJC_GET_SELECTOR);
6026                         ins->dreg = mono_alloc_ireg (cfg);
6027                         // FIXME: Leaks
6028                         ins->inst_p0 = s;
6029                         MONO_ADD_INS (cfg->cbb, ins);
6030                         return ins;
6031                 }
6032         }
6033
6034 #ifdef MONO_ARCH_SIMD_INTRINSICS
6035         if (cfg->opt & MONO_OPT_SIMD) {
6036                 ins = mono_emit_simd_intrinsics (cfg, cmethod, fsig, args);
6037                 if (ins)
6038                         return ins;
6039         }
6040 #endif
6041
6042         ins = mono_emit_native_types_intrinsics (cfg, cmethod, fsig, args);
6043         if (ins)
6044                 return ins;
6045
6046         if (COMPILE_LLVM (cfg)) {
6047                 ins = llvm_emit_inst_for_method (cfg, cmethod, fsig, args);
6048                 if (ins)
6049                         return ins;
6050         }
6051
6052         return mono_arch_emit_inst_for_method (cfg, cmethod, fsig, args);
6053 }
6054
6055 /*
6056  * This entry point could be used later for arbitrary method
6057  * redirection.
6058  */
6059 inline static MonoInst*
6060 mini_redirect_call (MonoCompile *cfg, MonoMethod *method,  
6061                                         MonoMethodSignature *signature, MonoInst **args, MonoInst *this_ins)
6062 {
6063         if (method->klass == mono_defaults.string_class) {
6064                 /* managed string allocation support */
6065                 if (strcmp (method->name, "InternalAllocateStr") == 0 && !(mono_profiler_events & MONO_PROFILE_ALLOCATIONS) && !(cfg->opt & MONO_OPT_SHARED)) {
6066                         MonoInst *iargs [2];
6067                         MonoVTable *vtable = mono_class_vtable (cfg->domain, method->klass);
6068                         MonoMethod *managed_alloc = NULL;
6069
6070                         g_assert (vtable); /*Should not fail since it System.String*/
6071 #ifndef MONO_CROSS_COMPILE
6072                         managed_alloc = mono_gc_get_managed_allocator (method->klass, FALSE, FALSE);
6073 #endif
6074                         if (!managed_alloc)
6075                                 return NULL;
6076                         EMIT_NEW_VTABLECONST (cfg, iargs [0], vtable);
6077                         iargs [1] = args [0];
6078                         return mono_emit_method_call (cfg, managed_alloc, iargs, this_ins);
6079                 }
6080         }
6081         return NULL;
6082 }
6083
6084 static void
6085 mono_save_args (MonoCompile *cfg, MonoMethodSignature *sig, MonoInst **sp)
6086 {
6087         MonoInst *store, *temp;
6088         int i;
6089
6090         for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
6091                 MonoType *argtype = (sig->hasthis && (i == 0)) ? type_from_stack_type (*sp) : sig->params [i - sig->hasthis];
6092
6093                 /*
6094                  * FIXME: We should use *args++ = sp [0], but that would mean the arg
6095                  * would be different than the MonoInst's used to represent arguments, and
6096                  * the ldelema implementation can't deal with that.
6097                  * Solution: When ldelema is used on an inline argument, create a var for 
6098                  * it, emit ldelema on that var, and emit the saving code below in
6099                  * inline_method () if needed.
6100                  */
6101                 temp = mono_compile_create_var (cfg, argtype, OP_LOCAL);
6102                 cfg->args [i] = temp;
6103                 /* This uses cfg->args [i] which is set by the preceeding line */
6104                 EMIT_NEW_ARGSTORE (cfg, store, i, *sp);
6105                 store->cil_code = sp [0]->cil_code;
6106                 sp++;
6107         }
6108 }
6109
6110 #define MONO_INLINE_CALLED_LIMITED_METHODS 1
6111 #define MONO_INLINE_CALLER_LIMITED_METHODS 1
6112
6113 #if (MONO_INLINE_CALLED_LIMITED_METHODS)
6114 static gboolean
6115 check_inline_called_method_name_limit (MonoMethod *called_method)
6116 {
6117         int strncmp_result;
6118         static const char *limit = NULL;
6119         
6120         if (limit == NULL) {
6121                 const char *limit_string = g_getenv ("MONO_INLINE_CALLED_METHOD_NAME_LIMIT");
6122
6123                 if (limit_string != NULL)
6124                         limit = limit_string;
6125                 else
6126                         limit = "";
6127         }
6128
6129         if (limit [0] != '\0') {
6130                 char *called_method_name = mono_method_full_name (called_method, TRUE);
6131
6132                 strncmp_result = strncmp (called_method_name, limit, strlen (limit));
6133                 g_free (called_method_name);
6134         
6135                 //return (strncmp_result <= 0);
6136                 return (strncmp_result == 0);
6137         } else {
6138                 return TRUE;
6139         }
6140 }
6141 #endif
6142
6143 #if (MONO_INLINE_CALLER_LIMITED_METHODS)
6144 static gboolean
6145 check_inline_caller_method_name_limit (MonoMethod *caller_method)
6146 {
6147         int strncmp_result;
6148         static const char *limit = NULL;
6149         
6150         if (limit == NULL) {
6151                 const char *limit_string = g_getenv ("MONO_INLINE_CALLER_METHOD_NAME_LIMIT");
6152                 if (limit_string != NULL) {
6153                         limit = limit_string;
6154                 } else {
6155                         limit = "";
6156                 }
6157         }
6158
6159         if (limit [0] != '\0') {
6160                 char *caller_method_name = mono_method_full_name (caller_method, TRUE);
6161
6162                 strncmp_result = strncmp (caller_method_name, limit, strlen (limit));
6163                 g_free (caller_method_name);
6164         
6165                 //return (strncmp_result <= 0);
6166                 return (strncmp_result == 0);
6167         } else {
6168                 return TRUE;
6169         }
6170 }
6171 #endif
6172
6173 static void
6174 emit_init_rvar (MonoCompile *cfg, int dreg, MonoType *rtype)
6175 {
6176         static double r8_0 = 0.0;
6177         static float r4_0 = 0.0;
6178         MonoInst *ins;
6179         int t;
6180
6181         rtype = mini_get_underlying_type (rtype);
6182         t = rtype->type;
6183
6184         if (rtype->byref) {
6185                 MONO_EMIT_NEW_PCONST (cfg, dreg, NULL);
6186         } else if (t >= MONO_TYPE_BOOLEAN && t <= MONO_TYPE_U4) {
6187                 MONO_EMIT_NEW_ICONST (cfg, dreg, 0);
6188         } else if (t == MONO_TYPE_I8 || t == MONO_TYPE_U8) {
6189                 MONO_EMIT_NEW_I8CONST (cfg, dreg, 0);
6190         } else if (cfg->r4fp && t == MONO_TYPE_R4) {
6191                 MONO_INST_NEW (cfg, ins, OP_R4CONST);
6192                 ins->type = STACK_R4;
6193                 ins->inst_p0 = (void*)&r4_0;
6194                 ins->dreg = dreg;
6195                 MONO_ADD_INS (cfg->cbb, ins);
6196         } else if (t == MONO_TYPE_R4 || t == MONO_TYPE_R8) {
6197                 MONO_INST_NEW (cfg, ins, OP_R8CONST);
6198                 ins->type = STACK_R8;
6199                 ins->inst_p0 = (void*)&r8_0;
6200                 ins->dreg = dreg;
6201                 MONO_ADD_INS (cfg->cbb, ins);
6202         } else if ((t == MONO_TYPE_VALUETYPE) || (t == MONO_TYPE_TYPEDBYREF) ||
6203                    ((t == MONO_TYPE_GENERICINST) && mono_type_generic_inst_is_valuetype (rtype))) {
6204                 MONO_EMIT_NEW_VZERO (cfg, dreg, mono_class_from_mono_type (rtype));
6205         } else if (((t == MONO_TYPE_VAR) || (t == MONO_TYPE_MVAR)) && mini_type_var_is_vt (rtype)) {
6206                 MONO_EMIT_NEW_VZERO (cfg, dreg, mono_class_from_mono_type (rtype));
6207         } else {
6208                 MONO_EMIT_NEW_PCONST (cfg, dreg, NULL);
6209         }
6210 }
6211
6212 static void
6213 emit_dummy_init_rvar (MonoCompile *cfg, int dreg, MonoType *rtype)
6214 {
6215         int t;
6216
6217         rtype = mini_get_underlying_type (rtype);
6218         t = rtype->type;
6219
6220         if (rtype->byref) {
6221                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_PCONST);
6222         } else if (t >= MONO_TYPE_BOOLEAN && t <= MONO_TYPE_U4) {
6223                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_ICONST);
6224         } else if (t == MONO_TYPE_I8 || t == MONO_TYPE_U8) {
6225                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_I8CONST);
6226         } else if (cfg->r4fp && t == MONO_TYPE_R4) {
6227                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_R4CONST);
6228         } else if (t == MONO_TYPE_R4 || t == MONO_TYPE_R8) {
6229                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_R8CONST);
6230         } else if ((t == MONO_TYPE_VALUETYPE) || (t == MONO_TYPE_TYPEDBYREF) ||
6231                    ((t == MONO_TYPE_GENERICINST) && mono_type_generic_inst_is_valuetype (rtype))) {
6232                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_VZERO);
6233         } else if (((t == MONO_TYPE_VAR) || (t == MONO_TYPE_MVAR)) && mini_type_var_is_vt (rtype)) {
6234                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_VZERO);
6235         } else {
6236                 emit_init_rvar (cfg, dreg, rtype);
6237         }
6238 }
6239
6240 /* If INIT is FALSE, emit dummy initialization statements to keep the IR valid */
6241 static void
6242 emit_init_local (MonoCompile *cfg, int local, MonoType *type, gboolean init)
6243 {
6244         MonoInst *var = cfg->locals [local];
6245         if (COMPILE_SOFT_FLOAT (cfg)) {
6246                 MonoInst *store;
6247                 int reg = alloc_dreg (cfg, (MonoStackType)var->type);
6248                 emit_init_rvar (cfg, reg, type);
6249                 EMIT_NEW_LOCSTORE (cfg, store, local, cfg->cbb->last_ins);
6250         } else {
6251                 if (init)
6252                         emit_init_rvar (cfg, var->dreg, type);
6253                 else
6254                         emit_dummy_init_rvar (cfg, var->dreg, type);
6255         }
6256 }
6257
6258 int
6259 mini_inline_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **sp, guchar *ip, guint real_offset, gboolean inline_always)
6260 {
6261         return inline_method (cfg, cmethod, fsig, sp, ip, real_offset, inline_always);
6262 }
6263
6264 /*
6265  * inline_method:
6266  *
6267  * Return the cost of inlining CMETHOD, or zero if it should not be inlined.
6268  */
6269 static int
6270 inline_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **sp,
6271                guchar *ip, guint real_offset, gboolean inline_always)
6272 {
6273         MonoError error;
6274         MonoInst *ins, *rvar = NULL;
6275         MonoMethodHeader *cheader;
6276         MonoBasicBlock *ebblock, *sbblock;
6277         int i, costs;
6278         MonoMethod *prev_inlined_method;
6279         MonoInst **prev_locals, **prev_args;
6280         MonoType **prev_arg_types;
6281         guint prev_real_offset;
6282         GHashTable *prev_cbb_hash;
6283         MonoBasicBlock **prev_cil_offset_to_bb;
6284         MonoBasicBlock *prev_cbb;
6285         const unsigned char *prev_ip;
6286         unsigned char *prev_cil_start;
6287         guint32 prev_cil_offset_to_bb_len;
6288         MonoMethod *prev_current_method;
6289         MonoGenericContext *prev_generic_context;
6290         gboolean ret_var_set, prev_ret_var_set, prev_disable_inline, virtual_ = FALSE;
6291
6292         g_assert (cfg->exception_type == MONO_EXCEPTION_NONE);
6293
6294 #if (MONO_INLINE_CALLED_LIMITED_METHODS)
6295         if ((! inline_always) && ! check_inline_called_method_name_limit (cmethod))
6296                 return 0;
6297 #endif
6298 #if (MONO_INLINE_CALLER_LIMITED_METHODS)
6299         if ((! inline_always) && ! check_inline_caller_method_name_limit (cfg->method))
6300                 return 0;
6301 #endif
6302
6303         if (!fsig)
6304                 fsig = mono_method_signature (cmethod);
6305
6306         if (cfg->verbose_level > 2)
6307                 printf ("INLINE START %p %s -> %s\n", cmethod,  mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
6308
6309         if (!cmethod->inline_info) {
6310                 cfg->stat_inlineable_methods++;
6311                 cmethod->inline_info = 1;
6312         }
6313
6314         /* allocate local variables */
6315         cheader = mono_method_get_header_checked (cmethod, &error);
6316         if (!cheader) {
6317                 if (inline_always) {
6318                         mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
6319                         mono_error_move (&cfg->error, &error);
6320                 } else {
6321                         mono_error_cleanup (&error);
6322                 }
6323                 return 0;
6324         }
6325
6326         /*Must verify before creating locals as it can cause the JIT to assert.*/
6327         if (mono_compile_is_broken (cfg, cmethod, FALSE)) {
6328                 mono_metadata_free_mh (cheader);
6329                 return 0;
6330         }
6331
6332         /* allocate space to store the return value */
6333         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
6334                 rvar = mono_compile_create_var (cfg, fsig->ret, OP_LOCAL);
6335         }
6336
6337         prev_locals = cfg->locals;
6338         cfg->locals = (MonoInst **)mono_mempool_alloc0 (cfg->mempool, cheader->num_locals * sizeof (MonoInst*));
6339         for (i = 0; i < cheader->num_locals; ++i)
6340                 cfg->locals [i] = mono_compile_create_var (cfg, cheader->locals [i], OP_LOCAL);
6341
6342         /* allocate start and end blocks */
6343         /* This is needed so if the inline is aborted, we can clean up */
6344         NEW_BBLOCK (cfg, sbblock);
6345         sbblock->real_offset = real_offset;
6346
6347         NEW_BBLOCK (cfg, ebblock);
6348         ebblock->block_num = cfg->num_bblocks++;
6349         ebblock->real_offset = real_offset;
6350
6351         prev_args = cfg->args;
6352         prev_arg_types = cfg->arg_types;
6353         prev_inlined_method = cfg->inlined_method;
6354         cfg->inlined_method = cmethod;
6355         cfg->ret_var_set = FALSE;
6356         cfg->inline_depth ++;
6357         prev_real_offset = cfg->real_offset;
6358         prev_cbb_hash = cfg->cbb_hash;
6359         prev_cil_offset_to_bb = cfg->cil_offset_to_bb;
6360         prev_cil_offset_to_bb_len = cfg->cil_offset_to_bb_len;
6361         prev_cil_start = cfg->cil_start;
6362         prev_ip = cfg->ip;
6363         prev_cbb = cfg->cbb;
6364         prev_current_method = cfg->current_method;
6365         prev_generic_context = cfg->generic_context;
6366         prev_ret_var_set = cfg->ret_var_set;
6367         prev_disable_inline = cfg->disable_inline;
6368
6369         if (ip && *ip == CEE_CALLVIRT && !(cmethod->flags & METHOD_ATTRIBUTE_STATIC))
6370                 virtual_ = TRUE;
6371
6372         costs = mono_method_to_ir (cfg, cmethod, sbblock, ebblock, rvar, sp, real_offset, virtual_);
6373
6374         ret_var_set = cfg->ret_var_set;
6375
6376         cfg->inlined_method = prev_inlined_method;
6377         cfg->real_offset = prev_real_offset;
6378         cfg->cbb_hash = prev_cbb_hash;
6379         cfg->cil_offset_to_bb = prev_cil_offset_to_bb;
6380         cfg->cil_offset_to_bb_len = prev_cil_offset_to_bb_len;
6381         cfg->cil_start = prev_cil_start;
6382         cfg->ip = prev_ip;
6383         cfg->locals = prev_locals;
6384         cfg->args = prev_args;
6385         cfg->arg_types = prev_arg_types;
6386         cfg->current_method = prev_current_method;
6387         cfg->generic_context = prev_generic_context;
6388         cfg->ret_var_set = prev_ret_var_set;
6389         cfg->disable_inline = prev_disable_inline;
6390         cfg->inline_depth --;
6391
6392         if ((costs >= 0 && costs < 60) || inline_always || (costs >= 0 && (cmethod->iflags & METHOD_IMPL_ATTRIBUTE_AGGRESSIVE_INLINING))) {
6393                 if (cfg->verbose_level > 2)
6394                         printf ("INLINE END %s -> %s\n", mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
6395
6396                 cfg->stat_inlined_methods++;
6397
6398                 /* always add some code to avoid block split failures */
6399                 MONO_INST_NEW (cfg, ins, OP_NOP);
6400                 MONO_ADD_INS (prev_cbb, ins);
6401
6402                 prev_cbb->next_bb = sbblock;
6403                 link_bblock (cfg, prev_cbb, sbblock);
6404
6405                 /* 
6406                  * Get rid of the begin and end bblocks if possible to aid local
6407                  * optimizations.
6408                  */
6409                 if (prev_cbb->out_count == 1)
6410                         mono_merge_basic_blocks (cfg, prev_cbb, sbblock);
6411
6412                 if ((prev_cbb->out_count == 1) && (prev_cbb->out_bb [0]->in_count == 1) && (prev_cbb->out_bb [0] != ebblock))
6413                         mono_merge_basic_blocks (cfg, prev_cbb, prev_cbb->out_bb [0]);
6414
6415                 if ((ebblock->in_count == 1) && ebblock->in_bb [0]->out_count == 1) {
6416                         MonoBasicBlock *prev = ebblock->in_bb [0];
6417
6418                         if (prev->next_bb == ebblock) {
6419                                 mono_merge_basic_blocks (cfg, prev, ebblock);
6420                                 cfg->cbb = prev;
6421                                 if ((prev_cbb->out_count == 1) && (prev_cbb->out_bb [0]->in_count == 1) && (prev_cbb->out_bb [0] == prev)) {
6422                                         mono_merge_basic_blocks (cfg, prev_cbb, prev);
6423                                         cfg->cbb = prev_cbb;
6424                                 }
6425                         } else {
6426                                 /* There could be a bblock after 'prev', and making 'prev' the current bb could cause problems */
6427                                 cfg->cbb = ebblock;
6428                         }
6429                 } else {
6430                         /* 
6431                          * Its possible that the rvar is set in some prev bblock, but not in others.
6432                          * (#1835).
6433                          */
6434                         if (rvar) {
6435                                 MonoBasicBlock *bb;
6436
6437                                 for (i = 0; i < ebblock->in_count; ++i) {
6438                                         bb = ebblock->in_bb [i];
6439
6440                                         if (bb->last_ins && bb->last_ins->opcode == OP_NOT_REACHED) {
6441                                                 cfg->cbb = bb;
6442
6443                                                 emit_init_rvar (cfg, rvar->dreg, fsig->ret);
6444                                         }
6445                                 }
6446                         }
6447
6448                         cfg->cbb = ebblock;
6449                 }
6450
6451                 if (rvar) {
6452                         /*
6453                          * If the inlined method contains only a throw, then the ret var is not 
6454                          * set, so set it to a dummy value.
6455                          */
6456                         if (!ret_var_set)
6457                                 emit_init_rvar (cfg, rvar->dreg, fsig->ret);
6458
6459                         EMIT_NEW_TEMPLOAD (cfg, ins, rvar->inst_c0);
6460                         *sp++ = ins;
6461                 }
6462                 cfg->headers_to_free = g_slist_prepend_mempool (cfg->mempool, cfg->headers_to_free, cheader);
6463                 return costs + 1;
6464         } else {
6465                 if (cfg->verbose_level > 2)
6466                         printf ("INLINE ABORTED %s (cost %d)\n", mono_method_full_name (cmethod, TRUE), costs);
6467                 cfg->exception_type = MONO_EXCEPTION_NONE;
6468
6469                 /* This gets rid of the newly added bblocks */
6470                 cfg->cbb = prev_cbb;
6471         }
6472         cfg->headers_to_free = g_slist_prepend_mempool (cfg->mempool, cfg->headers_to_free, cheader);
6473         return 0;
6474 }
6475
6476 /*
6477  * Some of these comments may well be out-of-date.
6478  * Design decisions: we do a single pass over the IL code (and we do bblock 
6479  * splitting/merging in the few cases when it's required: a back jump to an IL
6480  * address that was not already seen as bblock starting point).
6481  * Code is validated as we go (full verification is still better left to metadata/verify.c).
6482  * Complex operations are decomposed in simpler ones right away. We need to let the 
6483  * arch-specific code peek and poke inside this process somehow (except when the 
6484  * optimizations can take advantage of the full semantic info of coarse opcodes).
6485  * All the opcodes of the form opcode.s are 'normalized' to opcode.
6486  * MonoInst->opcode initially is the IL opcode or some simplification of that 
6487  * (OP_LOAD, OP_STORE). The arch-specific code may rearrange it to an arch-specific 
6488  * opcode with value bigger than OP_LAST.
6489  * At this point the IR can be handed over to an interpreter, a dumb code generator
6490  * or to the optimizing code generator that will translate it to SSA form.
6491  *
6492  * Profiling directed optimizations.
6493  * We may compile by default with few or no optimizations and instrument the code
6494  * or the user may indicate what methods to optimize the most either in a config file
6495  * or through repeated runs where the compiler applies offline the optimizations to 
6496  * each method and then decides if it was worth it.
6497  */
6498
6499 #define CHECK_TYPE(ins) if (!(ins)->type) UNVERIFIED
6500 #define CHECK_STACK(num) if ((sp - stack_start) < (num)) UNVERIFIED
6501 #define CHECK_STACK_OVF(num) if (((sp - stack_start) + (num)) > header->max_stack) UNVERIFIED
6502 #define CHECK_ARG(num) if ((unsigned)(num) >= (unsigned)num_args) UNVERIFIED
6503 #define CHECK_LOCAL(num) if ((unsigned)(num) >= (unsigned)header->num_locals) UNVERIFIED
6504 #define CHECK_OPSIZE(size) if (ip + size > end) UNVERIFIED
6505 #define CHECK_UNVERIFIABLE(cfg) if (cfg->unverifiable) UNVERIFIED
6506 #define CHECK_TYPELOAD(klass) if (!(klass) || mono_class_has_failure (klass)) TYPE_LOAD_ERROR ((klass))
6507
6508 /* offset from br.s -> br like opcodes */
6509 #define BIG_BRANCH_OFFSET 13
6510
6511 static gboolean
6512 ip_in_bb (MonoCompile *cfg, MonoBasicBlock *bb, const guint8* ip)
6513 {
6514         MonoBasicBlock *b = cfg->cil_offset_to_bb [ip - cfg->cil_start];
6515
6516         return b == NULL || b == bb;
6517 }
6518
6519 static int
6520 get_basic_blocks (MonoCompile *cfg, MonoMethodHeader* header, guint real_offset, unsigned char *start, unsigned char *end, unsigned char **pos)
6521 {
6522         unsigned char *ip = start;
6523         unsigned char *target;
6524         int i;
6525         guint cli_addr;
6526         MonoBasicBlock *bblock;
6527         const MonoOpcode *opcode;
6528
6529         while (ip < end) {
6530                 cli_addr = ip - start;
6531                 i = mono_opcode_value ((const guint8 **)&ip, end);
6532                 if (i < 0)
6533                         UNVERIFIED;
6534                 opcode = &mono_opcodes [i];
6535                 switch (opcode->argument) {
6536                 case MonoInlineNone:
6537                         ip++; 
6538                         break;
6539                 case MonoInlineString:
6540                 case MonoInlineType:
6541                 case MonoInlineField:
6542                 case MonoInlineMethod:
6543                 case MonoInlineTok:
6544                 case MonoInlineSig:
6545                 case MonoShortInlineR:
6546                 case MonoInlineI:
6547                         ip += 5;
6548                         break;
6549                 case MonoInlineVar:
6550                         ip += 3;
6551                         break;
6552                 case MonoShortInlineVar:
6553                 case MonoShortInlineI:
6554                         ip += 2;
6555                         break;
6556                 case MonoShortInlineBrTarget:
6557                         target = start + cli_addr + 2 + (signed char)ip [1];
6558                         GET_BBLOCK (cfg, bblock, target);
6559                         ip += 2;
6560                         if (ip < end)
6561                                 GET_BBLOCK (cfg, bblock, ip);
6562                         break;
6563                 case MonoInlineBrTarget:
6564                         target = start + cli_addr + 5 + (gint32)read32 (ip + 1);
6565                         GET_BBLOCK (cfg, bblock, target);
6566                         ip += 5;
6567                         if (ip < end)
6568                                 GET_BBLOCK (cfg, bblock, ip);
6569                         break;
6570                 case MonoInlineSwitch: {
6571                         guint32 n = read32 (ip + 1);
6572                         guint32 j;
6573                         ip += 5;
6574                         cli_addr += 5 + 4 * n;
6575                         target = start + cli_addr;
6576                         GET_BBLOCK (cfg, bblock, target);
6577                         
6578                         for (j = 0; j < n; ++j) {
6579                                 target = start + cli_addr + (gint32)read32 (ip);
6580                                 GET_BBLOCK (cfg, bblock, target);
6581                                 ip += 4;
6582                         }
6583                         break;
6584                 }
6585                 case MonoInlineR:
6586                 case MonoInlineI8:
6587                         ip += 9;
6588                         break;
6589                 default:
6590                         g_assert_not_reached ();
6591                 }
6592
6593                 if (i == CEE_THROW) {
6594                         unsigned char *bb_start = ip - 1;
6595                         
6596                         /* Find the start of the bblock containing the throw */
6597                         bblock = NULL;
6598                         while ((bb_start >= start) && !bblock) {
6599                                 bblock = cfg->cil_offset_to_bb [(bb_start) - start];
6600                                 bb_start --;
6601                         }
6602                         if (bblock)
6603                                 bblock->out_of_line = 1;
6604                 }
6605         }
6606         return 0;
6607 unverified:
6608 exception_exit:
6609         *pos = ip;
6610         return 1;
6611 }
6612
6613 static inline MonoMethod *
6614 mini_get_method_allow_open (MonoMethod *m, guint32 token, MonoClass *klass, MonoGenericContext *context, MonoError *error)
6615 {
6616         MonoMethod *method;
6617
6618         error_init (error);
6619
6620         if (m->wrapper_type != MONO_WRAPPER_NONE) {
6621                 method = (MonoMethod *)mono_method_get_wrapper_data (m, token);
6622                 if (context) {
6623                         method = mono_class_inflate_generic_method_checked (method, context, error);
6624                 }
6625         } else {
6626                 method = mono_get_method_checked (m->klass->image, token, klass, context, error);
6627         }
6628
6629         return method;
6630 }
6631
6632 static inline MonoMethod *
6633 mini_get_method (MonoCompile *cfg, MonoMethod *m, guint32 token, MonoClass *klass, MonoGenericContext *context)
6634 {
6635         MonoError error;
6636         MonoMethod *method = mini_get_method_allow_open (m, token, klass, context, cfg ? &cfg->error : &error);
6637
6638         if (method && cfg && !cfg->gshared && mono_class_is_open_constructed_type (&method->klass->byval_arg)) {
6639                 mono_error_set_bad_image (&cfg->error, cfg->method->klass->image, "Method with open type while not compiling gshared");
6640                 method = NULL;
6641         }
6642
6643         if (!method && !cfg)
6644                 mono_error_cleanup (&error); /* FIXME don't swallow the error */
6645
6646         return method;
6647 }
6648
6649 static inline MonoClass*
6650 mini_get_class (MonoMethod *method, guint32 token, MonoGenericContext *context)
6651 {
6652         MonoError error;
6653         MonoClass *klass;
6654
6655         if (method->wrapper_type != MONO_WRAPPER_NONE) {
6656                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
6657                 if (context) {
6658                         klass = mono_class_inflate_generic_class_checked (klass, context, &error);
6659                         mono_error_cleanup (&error); /* FIXME don't swallow the error */
6660                 }
6661         } else {
6662                 klass = mono_class_get_and_inflate_typespec_checked (method->klass->image, token, context, &error);
6663                 mono_error_cleanup (&error); /* FIXME don't swallow the error */
6664         }
6665         if (klass)
6666                 mono_class_init (klass);
6667         return klass;
6668 }
6669
6670 static inline MonoMethodSignature*
6671 mini_get_signature (MonoMethod *method, guint32 token, MonoGenericContext *context, MonoError *error)
6672 {
6673         MonoMethodSignature *fsig;
6674
6675         error_init (error);
6676         if (method->wrapper_type != MONO_WRAPPER_NONE) {
6677                 fsig = (MonoMethodSignature *)mono_method_get_wrapper_data (method, token);
6678         } else {
6679                 fsig = mono_metadata_parse_signature_checked (method->klass->image, token, error);
6680                 return_val_if_nok (error, NULL);
6681         }
6682         if (context) {
6683                 fsig = mono_inflate_generic_signature(fsig, context, error);
6684         }
6685         return fsig;
6686 }
6687
6688 static MonoMethod*
6689 throw_exception (void)
6690 {
6691         static MonoMethod *method = NULL;
6692
6693         if (!method) {
6694                 MonoSecurityManager *secman = mono_security_manager_get_methods ();
6695                 method = mono_class_get_method_from_name (secman->securitymanager, "ThrowException", 1);
6696         }
6697         g_assert (method);
6698         return method;
6699 }
6700
6701 static void
6702 emit_throw_exception (MonoCompile *cfg, MonoException *ex)
6703 {
6704         MonoMethod *thrower = throw_exception ();
6705         MonoInst *args [1];
6706
6707         EMIT_NEW_PCONST (cfg, args [0], ex);
6708         mono_emit_method_call (cfg, thrower, args, NULL);
6709 }
6710
6711 /*
6712  * Return the original method is a wrapper is specified. We can only access 
6713  * the custom attributes from the original method.
6714  */
6715 static MonoMethod*
6716 get_original_method (MonoMethod *method)
6717 {
6718         if (method->wrapper_type == MONO_WRAPPER_NONE)
6719                 return method;
6720
6721         /* native code (which is like Critical) can call any managed method XXX FIXME XXX to validate all usages */
6722         if (method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED)
6723                 return NULL;
6724
6725         /* in other cases we need to find the original method */
6726         return mono_marshal_method_from_wrapper (method);
6727 }
6728
6729 static void
6730 ensure_method_is_allowed_to_access_field (MonoCompile *cfg, MonoMethod *caller, MonoClassField *field)
6731 {
6732         /* we can't get the coreclr security level on wrappers since they don't have the attributes */
6733         MonoException *ex = mono_security_core_clr_is_field_access_allowed (get_original_method (caller), field);
6734         if (ex)
6735                 emit_throw_exception (cfg, ex);
6736 }
6737
6738 static void
6739 ensure_method_is_allowed_to_call_method (MonoCompile *cfg, MonoMethod *caller, MonoMethod *callee)
6740 {
6741         /* we can't get the coreclr security level on wrappers since they don't have the attributes */
6742         MonoException *ex = mono_security_core_clr_is_call_allowed (get_original_method (caller), callee);
6743         if (ex)
6744                 emit_throw_exception (cfg, ex);
6745 }
6746
6747 /*
6748  * Check that the IL instructions at ip are the array initialization
6749  * sequence and return the pointer to the data and the size.
6750  */
6751 static const char*
6752 initialize_array_data (MonoMethod *method, gboolean aot, unsigned char *ip, MonoClass *klass, guint32 len, int *out_size, guint32 *out_field_token)
6753 {
6754         /*
6755          * newarr[System.Int32]
6756          * dup
6757          * ldtoken field valuetype ...
6758          * call void class [mscorlib]System.Runtime.CompilerServices.RuntimeHelpers::InitializeArray(class [mscorlib]System.Array, valuetype [mscorlib]System.RuntimeFieldHandle)
6759          */
6760         if (ip [0] == CEE_DUP && ip [1] == CEE_LDTOKEN && ip [5] == 0x4 && ip [6] == CEE_CALL) {
6761                 MonoError error;
6762                 guint32 token = read32 (ip + 7);
6763                 guint32 field_token = read32 (ip + 2);
6764                 guint32 field_index = field_token & 0xffffff;
6765                 guint32 rva;
6766                 const char *data_ptr;
6767                 int size = 0;
6768                 MonoMethod *cmethod;
6769                 MonoClass *dummy_class;
6770                 MonoClassField *field = mono_field_from_token_checked (method->klass->image, field_token, &dummy_class, NULL, &error);
6771                 int dummy_align;
6772
6773                 if (!field) {
6774                         mono_error_cleanup (&error); /* FIXME don't swallow the error */
6775                         return NULL;
6776                 }
6777
6778                 *out_field_token = field_token;
6779
6780                 cmethod = mini_get_method (NULL, method, token, NULL, NULL);
6781                 if (!cmethod)
6782                         return NULL;
6783                 if (strcmp (cmethod->name, "InitializeArray") || strcmp (cmethod->klass->name, "RuntimeHelpers") || cmethod->klass->image != mono_defaults.corlib)
6784                         return NULL;
6785                 switch (mini_get_underlying_type (&klass->byval_arg)->type) {
6786                 case MONO_TYPE_I1:
6787                 case MONO_TYPE_U1:
6788                         size = 1; break;
6789                 /* we need to swap on big endian, so punt. Should we handle R4 and R8 as well? */
6790 #if TARGET_BYTE_ORDER == G_LITTLE_ENDIAN
6791                 case MONO_TYPE_I2:
6792                 case MONO_TYPE_U2:
6793                         size = 2; break;
6794                 case MONO_TYPE_I4:
6795                 case MONO_TYPE_U4:
6796                 case MONO_TYPE_R4:
6797                         size = 4; break;
6798                 case MONO_TYPE_R8:
6799                 case MONO_TYPE_I8:
6800                 case MONO_TYPE_U8:
6801                         size = 8; break;
6802 #endif
6803                 default:
6804                         return NULL;
6805                 }
6806                 size *= len;
6807                 if (size > mono_type_size (field->type, &dummy_align))
6808                     return NULL;
6809                 *out_size = size;
6810                 /*g_print ("optimized in %s: size: %d, numelems: %d\n", method->name, size, newarr->inst_newa_len->inst_c0);*/
6811                 if (!image_is_dynamic (method->klass->image)) {
6812                         field_index = read32 (ip + 2) & 0xffffff;
6813                         mono_metadata_field_info (method->klass->image, field_index - 1, NULL, &rva, NULL);
6814                         data_ptr = mono_image_rva_map (method->klass->image, rva);
6815                         /*g_print ("field: 0x%08x, rva: %d, rva_ptr: %p\n", read32 (ip + 2), rva, data_ptr);*/
6816                         /* for aot code we do the lookup on load */
6817                         if (aot && data_ptr)
6818                                 return (const char *)GUINT_TO_POINTER (rva);
6819                 } else {
6820                         /*FIXME is it possible to AOT a SRE assembly not meant to be saved? */ 
6821                         g_assert (!aot);
6822                         data_ptr = mono_field_get_data (field);
6823                 }
6824                 return data_ptr;
6825         }
6826         return NULL;
6827 }
6828
6829 static void
6830 set_exception_type_from_invalid_il (MonoCompile *cfg, MonoMethod *method, unsigned char *ip)
6831 {
6832         MonoError error;
6833         char *method_fname = mono_method_full_name (method, TRUE);
6834         char *method_code;
6835         MonoMethodHeader *header = mono_method_get_header_checked (method, &error);
6836
6837         if (!header) {
6838                 method_code = g_strdup_printf ("could not parse method body due to %s", mono_error_get_message (&error));
6839                 mono_error_cleanup (&error);
6840         } else if (header->code_size == 0)
6841                 method_code = g_strdup ("method body is empty.");
6842         else
6843                 method_code = mono_disasm_code_one (NULL, method, ip, NULL);
6844         mono_cfg_set_exception_invalid_program (cfg, g_strdup_printf ("Invalid IL code in %s: %s\n", method_fname, method_code));
6845         g_free (method_fname);
6846         g_free (method_code);
6847         cfg->headers_to_free = g_slist_prepend_mempool (cfg->mempool, cfg->headers_to_free, header);
6848 }
6849
6850 static void
6851 emit_stloc_ir (MonoCompile *cfg, MonoInst **sp, MonoMethodHeader *header, int n)
6852 {
6853         MonoInst *ins;
6854         guint32 opcode = mono_type_to_regmove (cfg, header->locals [n]);
6855         if ((opcode == OP_MOVE) && cfg->cbb->last_ins == sp [0]  &&
6856                         ((sp [0]->opcode == OP_ICONST) || (sp [0]->opcode == OP_I8CONST))) {
6857                 /* Optimize reg-reg moves away */
6858                 /* 
6859                  * Can't optimize other opcodes, since sp[0] might point to
6860                  * the last ins of a decomposed opcode.
6861                  */
6862                 sp [0]->dreg = (cfg)->locals [n]->dreg;
6863         } else {
6864                 EMIT_NEW_LOCSTORE (cfg, ins, n, *sp);
6865         }
6866 }
6867
6868 /*
6869  * ldloca inhibits many optimizations so try to get rid of it in common
6870  * cases.
6871  */
6872 static inline unsigned char *
6873 emit_optimized_ldloca_ir (MonoCompile *cfg, unsigned char *ip, unsigned char *end, int size)
6874 {
6875         int local, token;
6876         MonoClass *klass;
6877         MonoType *type;
6878
6879         if (size == 1) {
6880                 local = ip [1];
6881                 ip += 2;
6882         } else {
6883                 local = read16 (ip + 2);
6884                 ip += 4;
6885         }
6886         
6887         if (ip + 6 < end && (ip [0] == CEE_PREFIX1) && (ip [1] == CEE_INITOBJ) && ip_in_bb (cfg, cfg->cbb, ip + 1)) {
6888                 /* From the INITOBJ case */
6889                 token = read32 (ip + 2);
6890                 klass = mini_get_class (cfg->current_method, token, cfg->generic_context);
6891                 CHECK_TYPELOAD (klass);
6892                 type = mini_get_underlying_type (&klass->byval_arg);
6893                 emit_init_local (cfg, local, type, TRUE);
6894                 return ip + 6;
6895         }
6896  exception_exit:
6897         return NULL;
6898 }
6899
6900 static MonoInst*
6901 emit_llvmonly_virtual_call (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, int context_used, MonoInst **sp)
6902 {
6903         MonoInst *icall_args [16];
6904         MonoInst *call_target, *ins, *vtable_ins;
6905         int arg_reg, this_reg, vtable_reg;
6906         gboolean is_iface = mono_class_is_interface (cmethod->klass);
6907         gboolean is_gsharedvt = cfg->gsharedvt && mini_is_gsharedvt_variable_signature (fsig);
6908         gboolean variant_iface = FALSE;
6909         guint32 slot;
6910         int offset;
6911         gboolean special_array_interface = cmethod->klass->is_array_special_interface;
6912
6913         /*
6914          * In llvm-only mode, vtables contain function descriptors instead of
6915          * method addresses/trampolines.
6916          */
6917         MONO_EMIT_NULL_CHECK (cfg, sp [0]->dreg);
6918
6919         if (is_iface)
6920                 slot = mono_method_get_imt_slot (cmethod);
6921         else
6922                 slot = mono_method_get_vtable_index (cmethod);
6923
6924         this_reg = sp [0]->dreg;
6925
6926         if (is_iface && mono_class_has_variant_generic_params (cmethod->klass))
6927                 variant_iface = TRUE;
6928
6929         if (!fsig->generic_param_count && !is_iface && !is_gsharedvt) {
6930                 /*
6931                  * The simplest case, a normal virtual call.
6932                  */
6933                 int slot_reg = alloc_preg (cfg);
6934                 int addr_reg = alloc_preg (cfg);
6935                 int arg_reg = alloc_preg (cfg);
6936                 MonoBasicBlock *non_null_bb;
6937
6938                 vtable_reg = alloc_preg (cfg);
6939                 EMIT_NEW_LOAD_MEMBASE (cfg, vtable_ins, OP_LOAD_MEMBASE, vtable_reg, this_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
6940                 offset = MONO_STRUCT_OFFSET (MonoVTable, vtable) + (slot * SIZEOF_VOID_P);
6941
6942                 /* Load the vtable slot, which contains a function descriptor. */
6943                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, slot_reg, vtable_reg, offset);
6944
6945                 NEW_BBLOCK (cfg, non_null_bb);
6946
6947                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, slot_reg, 0);
6948                 cfg->cbb->last_ins->flags |= MONO_INST_LIKELY;
6949                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, non_null_bb);
6950
6951                 /* Slow path */
6952                 // FIXME: Make the wrapper use the preserveall cconv
6953                 // FIXME: Use one icall per slot for small slot numbers ?
6954                 icall_args [0] = vtable_ins;
6955                 EMIT_NEW_ICONST (cfg, icall_args [1], slot);
6956                 /* Make the icall return the vtable slot value to save some code space */
6957                 ins = mono_emit_jit_icall (cfg, mono_init_vtable_slot, icall_args);
6958                 ins->dreg = slot_reg;
6959                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, non_null_bb);
6960
6961                 /* Fastpath */
6962                 MONO_START_BB (cfg, non_null_bb);
6963                 /* Load the address + arg from the vtable slot */
6964                 EMIT_NEW_LOAD_MEMBASE (cfg, call_target, OP_LOAD_MEMBASE, addr_reg, slot_reg, 0);
6965                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, arg_reg, slot_reg, SIZEOF_VOID_P);
6966
6967                 return emit_extra_arg_calli (cfg, fsig, sp, arg_reg, call_target);
6968         }
6969
6970         if (!fsig->generic_param_count && is_iface && !variant_iface && !is_gsharedvt && !special_array_interface) {
6971                 /*
6972                  * A simple interface call
6973                  *
6974                  * We make a call through an imt slot to obtain the function descriptor we need to call.
6975                  * The imt slot contains a function descriptor for a runtime function + arg.
6976                  */
6977                 int slot_reg = alloc_preg (cfg);
6978                 int addr_reg = alloc_preg (cfg);
6979                 int arg_reg = alloc_preg (cfg);
6980                 MonoInst *thunk_addr_ins, *thunk_arg_ins, *ftndesc_ins;
6981
6982                 vtable_reg = alloc_preg (cfg);
6983                 EMIT_NEW_LOAD_MEMBASE (cfg, vtable_ins, OP_LOAD_MEMBASE, vtable_reg, this_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
6984                 offset = ((gint32)slot - MONO_IMT_SIZE) * SIZEOF_VOID_P;
6985
6986                 /*
6987                  * The slot is already initialized when the vtable is created so there is no need
6988                  * to check it here.
6989                  */
6990
6991                 /* Load the imt slot, which contains a function descriptor. */
6992                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, slot_reg, vtable_reg, offset);
6993
6994                 /* Load the address + arg of the imt thunk from the imt slot */
6995                 EMIT_NEW_LOAD_MEMBASE (cfg, thunk_addr_ins, OP_LOAD_MEMBASE, addr_reg, slot_reg, 0);
6996                 EMIT_NEW_LOAD_MEMBASE (cfg, thunk_arg_ins, OP_LOAD_MEMBASE, arg_reg, slot_reg, SIZEOF_VOID_P);
6997                 /*
6998                  * IMT thunks in llvm-only mode are C functions which take an info argument
6999                  * plus the imt method and return the ftndesc to call.
7000                  */
7001                 icall_args [0] = thunk_arg_ins;
7002                 icall_args [1] = emit_get_rgctx_method (cfg, context_used,
7003                                                                                                 cmethod, MONO_RGCTX_INFO_METHOD);
7004                 ftndesc_ins = mini_emit_calli (cfg, helper_sig_llvmonly_imt_trampoline, icall_args, thunk_addr_ins, NULL, NULL);
7005
7006                 return emit_llvmonly_calli (cfg, fsig, sp, ftndesc_ins);
7007         }
7008
7009         if ((fsig->generic_param_count || variant_iface || special_array_interface) && !is_gsharedvt) {
7010                 /*
7011                  * This is similar to the interface case, the vtable slot points to an imt thunk which is
7012                  * dynamically extended as more instantiations are discovered.
7013                  * This handles generic virtual methods both on classes and interfaces.
7014                  */
7015                 int slot_reg = alloc_preg (cfg);
7016                 int addr_reg = alloc_preg (cfg);
7017                 int arg_reg = alloc_preg (cfg);
7018                 int ftndesc_reg = alloc_preg (cfg);
7019                 MonoInst *thunk_addr_ins, *thunk_arg_ins, *ftndesc_ins;
7020                 MonoBasicBlock *slowpath_bb, *end_bb;
7021
7022                 NEW_BBLOCK (cfg, slowpath_bb);
7023                 NEW_BBLOCK (cfg, end_bb);
7024
7025                 vtable_reg = alloc_preg (cfg);
7026                 EMIT_NEW_LOAD_MEMBASE (cfg, vtable_ins, OP_LOAD_MEMBASE, vtable_reg, this_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
7027                 if (is_iface)
7028                         offset = ((gint32)slot - MONO_IMT_SIZE) * SIZEOF_VOID_P;
7029                 else
7030                         offset = MONO_STRUCT_OFFSET (MonoVTable, vtable) + (slot * SIZEOF_VOID_P);
7031
7032                 /* Load the slot, which contains a function descriptor. */
7033                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, slot_reg, vtable_reg, offset);
7034
7035                 /* These slots are not initialized, so fall back to the slow path until they are initialized */
7036                 /* That happens when mono_method_add_generic_virtual_invocation () creates an IMT thunk */
7037                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, slot_reg, 0);
7038                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, slowpath_bb);
7039
7040                 /* Fastpath */
7041                 /* Same as with iface calls */
7042                 EMIT_NEW_LOAD_MEMBASE (cfg, thunk_addr_ins, OP_LOAD_MEMBASE, addr_reg, slot_reg, 0);
7043                 EMIT_NEW_LOAD_MEMBASE (cfg, thunk_arg_ins, OP_LOAD_MEMBASE, arg_reg, slot_reg, SIZEOF_VOID_P);
7044                 icall_args [0] = thunk_arg_ins;
7045                 icall_args [1] = emit_get_rgctx_method (cfg, context_used,
7046                                                                                                 cmethod, MONO_RGCTX_INFO_METHOD);
7047                 ftndesc_ins = mini_emit_calli (cfg, helper_sig_llvmonly_imt_trampoline, icall_args, thunk_addr_ins, NULL, NULL);
7048                 ftndesc_ins->dreg = ftndesc_reg;
7049                 /*
7050                  * Unlike normal iface calls, these imt thunks can return NULL, i.e. when they are passed an instantiation
7051                  * they don't know about yet. Fall back to the slowpath in that case.
7052                  */
7053                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, ftndesc_reg, 0);
7054                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, slowpath_bb);
7055
7056                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
7057
7058                 /* Slowpath */
7059                 MONO_START_BB (cfg, slowpath_bb);
7060                 icall_args [0] = vtable_ins;
7061                 EMIT_NEW_ICONST (cfg, icall_args [1], slot);
7062                 icall_args [2] = emit_get_rgctx_method (cfg, context_used,
7063                                                                                                 cmethod, MONO_RGCTX_INFO_METHOD);
7064                 if (is_iface)
7065                         ftndesc_ins = mono_emit_jit_icall (cfg, mono_resolve_generic_virtual_iface_call, icall_args);
7066                 else
7067                         ftndesc_ins = mono_emit_jit_icall (cfg, mono_resolve_generic_virtual_call, icall_args);
7068                 ftndesc_ins->dreg = ftndesc_reg;
7069                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
7070
7071                 /* Common case */
7072                 MONO_START_BB (cfg, end_bb);
7073                 return emit_llvmonly_calli (cfg, fsig, sp, ftndesc_ins);
7074         }
7075
7076         /*
7077          * Non-optimized cases
7078          */
7079         icall_args [0] = sp [0];
7080         EMIT_NEW_ICONST (cfg, icall_args [1], slot);
7081
7082         icall_args [2] = emit_get_rgctx_method (cfg, context_used,
7083                                                                                         cmethod, MONO_RGCTX_INFO_METHOD);
7084
7085         arg_reg = alloc_preg (cfg);
7086         MONO_EMIT_NEW_PCONST (cfg, arg_reg, NULL);
7087         EMIT_NEW_VARLOADA_VREG (cfg, icall_args [3], arg_reg, &mono_defaults.int_class->byval_arg);
7088
7089         g_assert (is_gsharedvt);
7090         if (is_iface)
7091                 call_target = mono_emit_jit_icall (cfg, mono_resolve_iface_call_gsharedvt, icall_args);
7092         else
7093                 call_target = mono_emit_jit_icall (cfg, mono_resolve_vcall_gsharedvt, icall_args);
7094
7095         /*
7096          * Pass the extra argument even if the callee doesn't receive it, most
7097          * calling conventions allow this.
7098          */
7099         return emit_extra_arg_calli (cfg, fsig, sp, arg_reg, call_target);
7100 }
7101
7102 static gboolean
7103 is_exception_class (MonoClass *klass)
7104 {
7105         while (klass) {
7106                 if (klass == mono_defaults.exception_class)
7107                         return TRUE;
7108                 klass = klass->parent;
7109         }
7110         return FALSE;
7111 }
7112
7113 /*
7114  * is_jit_optimizer_disabled:
7115  *
7116  *   Determine whenever M's assembly has a DebuggableAttribute with the
7117  * IsJITOptimizerDisabled flag set.
7118  */
7119 static gboolean
7120 is_jit_optimizer_disabled (MonoMethod *m)
7121 {
7122         MonoError error;
7123         MonoAssembly *ass = m->klass->image->assembly;
7124         MonoCustomAttrInfo* attrs;
7125         MonoClass *klass;
7126         int i;
7127         gboolean val = FALSE;
7128
7129         g_assert (ass);
7130         if (ass->jit_optimizer_disabled_inited)
7131                 return ass->jit_optimizer_disabled;
7132
7133         klass = mono_class_try_get_debuggable_attribute_class ();
7134
7135         if (!klass) {
7136                 /* Linked away */
7137                 ass->jit_optimizer_disabled = FALSE;
7138                 mono_memory_barrier ();
7139                 ass->jit_optimizer_disabled_inited = TRUE;
7140                 return FALSE;
7141         }
7142
7143         attrs = mono_custom_attrs_from_assembly_checked (ass, FALSE, &error);
7144         mono_error_cleanup (&error); /* FIXME don't swallow the error */
7145         if (attrs) {
7146                 for (i = 0; i < attrs->num_attrs; ++i) {
7147                         MonoCustomAttrEntry *attr = &attrs->attrs [i];
7148                         const gchar *p;
7149                         MonoMethodSignature *sig;
7150
7151                         if (!attr->ctor || attr->ctor->klass != klass)
7152                                 continue;
7153                         /* Decode the attribute. See reflection.c */
7154                         p = (const char*)attr->data;
7155                         g_assert (read16 (p) == 0x0001);
7156                         p += 2;
7157
7158                         // FIXME: Support named parameters
7159                         sig = mono_method_signature (attr->ctor);
7160                         if (sig->param_count != 2 || sig->params [0]->type != MONO_TYPE_BOOLEAN || sig->params [1]->type != MONO_TYPE_BOOLEAN)
7161                                 continue;
7162                         /* Two boolean arguments */
7163                         p ++;
7164                         val = *p;
7165                 }
7166                 mono_custom_attrs_free (attrs);
7167         }
7168
7169         ass->jit_optimizer_disabled = val;
7170         mono_memory_barrier ();
7171         ass->jit_optimizer_disabled_inited = TRUE;
7172
7173         return val;
7174 }
7175
7176 static gboolean
7177 is_supported_tail_call (MonoCompile *cfg, MonoMethod *method, MonoMethod *cmethod, MonoMethodSignature *fsig, int call_opcode)
7178 {
7179         gboolean supported_tail_call;
7180         int i;
7181
7182         supported_tail_call = mono_arch_tail_call_supported (cfg, mono_method_signature (method), mono_method_signature (cmethod));
7183
7184         for (i = 0; i < fsig->param_count; ++i) {
7185                 if (fsig->params [i]->byref || fsig->params [i]->type == MONO_TYPE_PTR || fsig->params [i]->type == MONO_TYPE_FNPTR)
7186                         /* These can point to the current method's stack */
7187                         supported_tail_call = FALSE;
7188         }
7189         if (fsig->hasthis && cmethod->klass->valuetype)
7190                 /* this might point to the current method's stack */
7191                 supported_tail_call = FALSE;
7192         if (cmethod->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)
7193                 supported_tail_call = FALSE;
7194         if (cfg->method->save_lmf)
7195                 supported_tail_call = FALSE;
7196         if (cmethod->wrapper_type && cmethod->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
7197                 supported_tail_call = FALSE;
7198         if (call_opcode != CEE_CALL)
7199                 supported_tail_call = FALSE;
7200
7201         /* Debugging support */
7202 #if 0
7203         if (supported_tail_call) {
7204                 if (!mono_debug_count ())
7205                         supported_tail_call = FALSE;
7206         }
7207 #endif
7208
7209         return supported_tail_call;
7210 }
7211
7212 /*
7213  * handle_ctor_call:
7214  *
7215  *   Handle calls made to ctors from NEWOBJ opcodes.
7216  */
7217 static void
7218 handle_ctor_call (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, int context_used,
7219                                   MonoInst **sp, guint8 *ip, int *inline_costs)
7220 {
7221         MonoInst *vtable_arg = NULL, *callvirt_this_arg = NULL, *ins;
7222
7223         if (cmethod->klass->valuetype && mono_class_generic_sharing_enabled (cmethod->klass) &&
7224                                         mono_method_is_generic_sharable (cmethod, TRUE)) {
7225                 if (cmethod->is_inflated && mono_method_get_context (cmethod)->method_inst) {
7226                         mono_class_vtable (cfg->domain, cmethod->klass);
7227                         CHECK_TYPELOAD (cmethod->klass);
7228
7229                         vtable_arg = emit_get_rgctx_method (cfg, context_used,
7230                                                                                                 cmethod, MONO_RGCTX_INFO_METHOD_RGCTX);
7231                 } else {
7232                         if (context_used) {
7233                                 vtable_arg = mini_emit_get_rgctx_klass (cfg, context_used,
7234                                                                                                    cmethod->klass, MONO_RGCTX_INFO_VTABLE);
7235                         } else {
7236                                 MonoVTable *vtable = mono_class_vtable (cfg->domain, cmethod->klass);
7237
7238                                 CHECK_TYPELOAD (cmethod->klass);
7239                                 EMIT_NEW_VTABLECONST (cfg, vtable_arg, vtable);
7240                         }
7241                 }
7242         }
7243
7244         /* Avoid virtual calls to ctors if possible */
7245         if (mono_class_is_marshalbyref (cmethod->klass))
7246                 callvirt_this_arg = sp [0];
7247
7248         if (cmethod && (cfg->opt & MONO_OPT_INTRINS) && (ins = mini_emit_inst_for_ctor (cfg, cmethod, fsig, sp))) {
7249                 g_assert (MONO_TYPE_IS_VOID (fsig->ret));
7250                 CHECK_CFG_EXCEPTION;
7251         } else if ((cfg->opt & MONO_OPT_INLINE) && cmethod && !context_used && !vtable_arg &&
7252                            mono_method_check_inlining (cfg, cmethod) &&
7253                            !mono_class_is_subclass_of (cmethod->klass, mono_defaults.exception_class, FALSE)) {
7254                 int costs;
7255
7256                 if ((costs = inline_method (cfg, cmethod, fsig, sp, ip, cfg->real_offset, FALSE))) {
7257                         cfg->real_offset += 5;
7258
7259                         *inline_costs += costs - 5;
7260                 } else {
7261                         INLINE_FAILURE ("inline failure");
7262                         // FIXME-VT: Clean this up
7263                         if (cfg->gsharedvt && mini_is_gsharedvt_signature (fsig))
7264                                 GSHAREDVT_FAILURE(*ip);
7265                         mono_emit_method_call_full (cfg, cmethod, fsig, FALSE, sp, callvirt_this_arg, NULL, NULL);
7266                 }
7267         } else if (cfg->gsharedvt && mini_is_gsharedvt_signature (fsig)) {
7268                 MonoInst *addr;
7269
7270                 addr = emit_get_rgctx_gsharedvt_call (cfg, context_used, fsig, cmethod, MONO_RGCTX_INFO_METHOD_GSHAREDVT_OUT_TRAMPOLINE);
7271
7272                 if (cfg->llvm_only) {
7273                         // FIXME: Avoid initializing vtable_arg
7274                         emit_llvmonly_calli (cfg, fsig, sp, addr);
7275                 } else {
7276                         mini_emit_calli (cfg, fsig, sp, addr, NULL, vtable_arg);
7277                 }
7278         } else if (context_used &&
7279                            ((!mono_method_is_generic_sharable_full (cmethod, TRUE, FALSE, FALSE) ||
7280                                  !mono_class_generic_sharing_enabled (cmethod->klass)) || cfg->gsharedvt)) {
7281                 MonoInst *cmethod_addr;
7282
7283                 /* Generic calls made out of gsharedvt methods cannot be patched, so use an indirect call */
7284
7285                 if (cfg->llvm_only) {
7286                         MonoInst *addr = emit_get_rgctx_method (cfg, context_used, cmethod,
7287                                                                                                         MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
7288                         emit_llvmonly_calli (cfg, fsig, sp, addr);
7289                 } else {
7290                         cmethod_addr = emit_get_rgctx_method (cfg, context_used,
7291                                                                                                   cmethod, MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
7292
7293                         mini_emit_calli (cfg, fsig, sp, cmethod_addr, NULL, vtable_arg);
7294                 }
7295         } else {
7296                 INLINE_FAILURE ("ctor call");
7297                 ins = mono_emit_method_call_full (cfg, cmethod, fsig, FALSE, sp,
7298                                                                                   callvirt_this_arg, NULL, vtable_arg);
7299         }
7300  exception_exit:
7301         return;
7302 }
7303
7304 static void
7305 emit_setret (MonoCompile *cfg, MonoInst *val)
7306 {
7307         MonoType *ret_type = mini_get_underlying_type (mono_method_signature (cfg->method)->ret);
7308         MonoInst *ins;
7309
7310         if (mini_type_to_stind (cfg, ret_type) == CEE_STOBJ) {
7311                 MonoInst *ret_addr;
7312
7313                 if (!cfg->vret_addr) {
7314                         EMIT_NEW_VARSTORE (cfg, ins, cfg->ret, ret_type, val);
7315                 } else {
7316                         EMIT_NEW_RETLOADA (cfg, ret_addr);
7317
7318                         EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STOREV_MEMBASE, ret_addr->dreg, 0, val->dreg);
7319                         ins->klass = mono_class_from_mono_type (ret_type);
7320                 }
7321         } else {
7322 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
7323                 if (COMPILE_SOFT_FLOAT (cfg) && !ret_type->byref && ret_type->type == MONO_TYPE_R4) {
7324                         MonoInst *iargs [1];
7325                         MonoInst *conv;
7326
7327                         iargs [0] = val;
7328                         conv = mono_emit_jit_icall (cfg, mono_fload_r4_arg, iargs);
7329                         mono_arch_emit_setret (cfg, cfg->method, conv);
7330                 } else {
7331                         mono_arch_emit_setret (cfg, cfg->method, val);
7332                 }
7333 #else
7334                 mono_arch_emit_setret (cfg, cfg->method, val);
7335 #endif
7336         }
7337 }
7338
7339 /*
7340  * mono_method_to_ir:
7341  *
7342  * Translate the .net IL into linear IR.
7343  *
7344  * @start_bblock: if not NULL, the starting basic block, used during inlining.
7345  * @end_bblock: if not NULL, the ending basic block, used during inlining.
7346  * @return_var: if not NULL, the place where the return value is stored, used during inlining.   
7347  * @inline_args: if not NULL, contains the arguments to the inline call
7348  * @inline_offset: if not zero, the real offset from the inline call, or zero otherwise.
7349  * @is_virtual_call: whether this method is being called as a result of a call to callvirt
7350  *
7351  * This method is used to turn ECMA IL into Mono's internal Linear IR
7352  * reprensetation.  It is used both for entire methods, as well as
7353  * inlining existing methods.  In the former case, the @start_bblock,
7354  * @end_bblock, @return_var, @inline_args are all set to NULL, and the
7355  * inline_offset is set to zero.
7356  * 
7357  * Returns: the inline cost, or -1 if there was an error processing this method.
7358  */
7359 int
7360 mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_bblock, MonoBasicBlock *end_bblock, 
7361                    MonoInst *return_var, MonoInst **inline_args, 
7362                    guint inline_offset, gboolean is_virtual_call)
7363 {
7364         MonoError error;
7365         MonoInst *ins, **sp, **stack_start;
7366         MonoBasicBlock *tblock = NULL, *init_localsbb = NULL;
7367         MonoSimpleBasicBlock *bb = NULL, *original_bb = NULL;
7368         MonoMethod *cmethod, *method_definition;
7369         MonoInst **arg_array;
7370         MonoMethodHeader *header;
7371         MonoImage *image;
7372         guint32 token, ins_flag;
7373         MonoClass *klass;
7374         MonoClass *constrained_class = NULL;
7375         unsigned char *ip, *end, *target, *err_pos;
7376         MonoMethodSignature *sig;
7377         MonoGenericContext *generic_context = NULL;
7378         MonoGenericContainer *generic_container = NULL;
7379         MonoType **param_types;
7380         int i, n, start_new_bblock, dreg;
7381         int num_calls = 0, inline_costs = 0;
7382         int breakpoint_id = 0;
7383         guint num_args;
7384         GSList *class_inits = NULL;
7385         gboolean dont_verify, dont_verify_stloc, readonly = FALSE;
7386         int context_used;
7387         gboolean init_locals, seq_points, skip_dead_blocks;
7388         gboolean sym_seq_points = FALSE;
7389         MonoDebugMethodInfo *minfo;
7390         MonoBitSet *seq_point_locs = NULL;
7391         MonoBitSet *seq_point_set_locs = NULL;
7392
7393         cfg->disable_inline = is_jit_optimizer_disabled (method);
7394
7395         /* serialization and xdomain stuff may need access to private fields and methods */
7396         dont_verify = method->klass->image->assembly->corlib_internal? TRUE: FALSE;
7397         dont_verify |= method->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE;
7398         dont_verify |= method->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH;
7399         dont_verify |= method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE; /* bug #77896 */
7400         dont_verify |= method->wrapper_type == MONO_WRAPPER_COMINTEROP;
7401         dont_verify |= method->wrapper_type == MONO_WRAPPER_COMINTEROP_INVOKE;
7402
7403         /* still some type unsafety issues in marshal wrappers... (unknown is PtrToStructure) */
7404         dont_verify_stloc = method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE;
7405         dont_verify_stloc |= method->wrapper_type == MONO_WRAPPER_UNKNOWN;
7406         dont_verify_stloc |= method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED;
7407         dont_verify_stloc |= method->wrapper_type == MONO_WRAPPER_STELEMREF;
7408
7409         image = method->klass->image;
7410         header = mono_method_get_header_checked (method, &cfg->error);
7411         if (!header) {
7412                 mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
7413                 goto exception_exit;
7414         } else {
7415                 cfg->headers_to_free = g_slist_prepend_mempool (cfg->mempool, cfg->headers_to_free, header);
7416         }
7417
7418         generic_container = mono_method_get_generic_container (method);
7419         sig = mono_method_signature (method);
7420         num_args = sig->hasthis + sig->param_count;
7421         ip = (unsigned char*)header->code;
7422         cfg->cil_start = ip;
7423         end = ip + header->code_size;
7424         cfg->stat_cil_code_size += header->code_size;
7425
7426         seq_points = cfg->gen_seq_points && cfg->method == method;
7427
7428         if (method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED) {
7429                 /* We could hit a seq point before attaching to the JIT (#8338) */
7430                 seq_points = FALSE;
7431         }
7432
7433         if (cfg->gen_sdb_seq_points && cfg->method == method) {
7434                 minfo = mono_debug_lookup_method (method);
7435                 if (minfo) {
7436                         MonoSymSeqPoint *sps;
7437                         int i, n_il_offsets;
7438
7439                         mono_debug_get_seq_points (minfo, NULL, NULL, NULL, &sps, &n_il_offsets);
7440                         seq_point_locs = mono_bitset_mem_new (mono_mempool_alloc0 (cfg->mempool, mono_bitset_alloc_size (header->code_size, 0)), header->code_size, 0);
7441                         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);
7442                         sym_seq_points = TRUE;
7443                         for (i = 0; i < n_il_offsets; ++i) {
7444                                 if (sps [i].il_offset < header->code_size)
7445                                         mono_bitset_set_fast (seq_point_locs, sps [i].il_offset);
7446                         }
7447                         g_free (sps);
7448
7449                         MonoDebugMethodAsyncInfo* asyncMethod = mono_debug_lookup_method_async_debug_info (method);
7450                         if (asyncMethod) {
7451                                 for (i = 0; asyncMethod != NULL && i < asyncMethod->num_awaits; i++)
7452                                 {
7453                                         mono_bitset_set_fast (seq_point_locs, asyncMethod->resume_offsets[i]);
7454                                         mono_bitset_set_fast (seq_point_locs, asyncMethod->yield_offsets[i]);
7455                                 }
7456                                 mono_debug_free_method_async_debug_info (asyncMethod);
7457                         }
7458                 } else if (!method->wrapper_type && !method->dynamic && mono_debug_image_has_debug_info (method->klass->image)) {
7459                         /* Methods without line number info like auto-generated property accessors */
7460                         seq_point_locs = mono_bitset_mem_new (mono_mempool_alloc0 (cfg->mempool, mono_bitset_alloc_size (header->code_size, 0)), header->code_size, 0);
7461                         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);
7462                         sym_seq_points = TRUE;
7463                 }
7464         }
7465
7466         /* 
7467          * Methods without init_locals set could cause asserts in various passes
7468          * (#497220). To work around this, we emit dummy initialization opcodes
7469          * (OP_DUMMY_ICONST etc.) which generate no code. These are only supported
7470          * on some platforms.
7471          */
7472         if ((cfg->opt & MONO_OPT_UNSAFE) && cfg->backend->have_dummy_init)
7473                 init_locals = header->init_locals;
7474         else
7475                 init_locals = TRUE;
7476
7477         method_definition = method;
7478         while (method_definition->is_inflated) {
7479                 MonoMethodInflated *imethod = (MonoMethodInflated *) method_definition;
7480                 method_definition = imethod->declaring;
7481         }
7482
7483         /* SkipVerification is not allowed if core-clr is enabled */
7484         if (!dont_verify && mini_assembly_can_skip_verification (cfg->domain, method)) {
7485                 dont_verify = TRUE;
7486                 dont_verify_stloc = TRUE;
7487         }
7488
7489         if (sig->is_inflated)
7490                 generic_context = mono_method_get_context (method);
7491         else if (generic_container)
7492                 generic_context = &generic_container->context;
7493         cfg->generic_context = generic_context;
7494
7495         if (!cfg->gshared)
7496                 g_assert (!sig->has_type_parameters);
7497
7498         if (sig->generic_param_count && method->wrapper_type == MONO_WRAPPER_NONE) {
7499                 g_assert (method->is_inflated);
7500                 g_assert (mono_method_get_context (method)->method_inst);
7501         }
7502         if (method->is_inflated && mono_method_get_context (method)->method_inst)
7503                 g_assert (sig->generic_param_count);
7504
7505         if (cfg->method == method) {
7506                 cfg->real_offset = 0;
7507         } else {
7508                 cfg->real_offset = inline_offset;
7509         }
7510
7511         cfg->cil_offset_to_bb = (MonoBasicBlock **)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoBasicBlock*) * header->code_size);
7512         cfg->cil_offset_to_bb_len = header->code_size;
7513
7514         cfg->current_method = method;
7515
7516         if (cfg->verbose_level > 2)
7517                 printf ("method to IR %s\n", mono_method_full_name (method, TRUE));
7518
7519         param_types = (MonoType **)mono_mempool_alloc (cfg->mempool, sizeof (MonoType*) * num_args);
7520         if (sig->hasthis)
7521                 param_types [0] = method->klass->valuetype?&method->klass->this_arg:&method->klass->byval_arg;
7522         for (n = 0; n < sig->param_count; ++n)
7523                 param_types [n + sig->hasthis] = sig->params [n];
7524         cfg->arg_types = param_types;
7525
7526         cfg->dont_inline = g_list_prepend (cfg->dont_inline, method);
7527         if (cfg->method == method) {
7528
7529                 if (cfg->prof_options & MONO_PROFILE_INS_COVERAGE)
7530                         cfg->coverage_info = mono_profiler_coverage_alloc (cfg->method, header->code_size);
7531
7532                 /* ENTRY BLOCK */
7533                 NEW_BBLOCK (cfg, start_bblock);
7534                 cfg->bb_entry = start_bblock;
7535                 start_bblock->cil_code = NULL;
7536                 start_bblock->cil_length = 0;
7537
7538                 /* EXIT BLOCK */
7539                 NEW_BBLOCK (cfg, end_bblock);
7540                 cfg->bb_exit = end_bblock;
7541                 end_bblock->cil_code = NULL;
7542                 end_bblock->cil_length = 0;
7543                 end_bblock->flags |= BB_INDIRECT_JUMP_TARGET;
7544                 g_assert (cfg->num_bblocks == 2);
7545
7546                 arg_array = cfg->args;
7547
7548                 if (header->num_clauses) {
7549                         cfg->spvars = g_hash_table_new (NULL, NULL);
7550                         cfg->exvars = g_hash_table_new (NULL, NULL);
7551                 }
7552                 /* handle exception clauses */
7553                 for (i = 0; i < header->num_clauses; ++i) {
7554                         MonoBasicBlock *try_bb;
7555                         MonoExceptionClause *clause = &header->clauses [i];
7556                         GET_BBLOCK (cfg, try_bb, ip + clause->try_offset);
7557
7558                         try_bb->real_offset = clause->try_offset;
7559                         try_bb->try_start = TRUE;
7560                         try_bb->region = ((i + 1) << 8) | clause->flags;
7561                         GET_BBLOCK (cfg, tblock, ip + clause->handler_offset);
7562                         tblock->real_offset = clause->handler_offset;
7563                         tblock->flags |= BB_EXCEPTION_HANDLER;
7564
7565                         /*
7566                          * Linking the try block with the EH block hinders inlining as we won't be able to 
7567                          * merge the bblocks from inlining and produce an artificial hole for no good reason.
7568                          */
7569                         if (COMPILE_LLVM (cfg))
7570                                 link_bblock (cfg, try_bb, tblock);
7571
7572                         if (*(ip + clause->handler_offset) == CEE_POP)
7573                                 tblock->flags |= BB_EXCEPTION_DEAD_OBJ;
7574
7575                         if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY ||
7576                             clause->flags == MONO_EXCEPTION_CLAUSE_FILTER ||
7577                             clause->flags == MONO_EXCEPTION_CLAUSE_FAULT) {
7578                                 MONO_INST_NEW (cfg, ins, OP_START_HANDLER);
7579                                 MONO_ADD_INS (tblock, ins);
7580
7581                                 if (seq_points && clause->flags != MONO_EXCEPTION_CLAUSE_FINALLY && clause->flags != MONO_EXCEPTION_CLAUSE_FILTER) {
7582                                         /* finally clauses already have a seq point */
7583                                         /* seq points for filter clauses are emitted below */
7584                                         NEW_SEQ_POINT (cfg, ins, clause->handler_offset, TRUE);
7585                                         MONO_ADD_INS (tblock, ins);
7586                                 }
7587
7588                                 /* todo: is a fault block unsafe to optimize? */
7589                                 if (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT)
7590                                         tblock->flags |= BB_EXCEPTION_UNSAFE;
7591                         }
7592
7593                         /*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);
7594                           while (p < end) {
7595                           printf ("%s", mono_disasm_code_one (NULL, method, p, &p));
7596                           }*/
7597                         /* catch and filter blocks get the exception object on the stack */
7598                         if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE ||
7599                             clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
7600
7601                                 /* mostly like handle_stack_args (), but just sets the input args */
7602                                 /* printf ("handling clause at IL_%04x\n", clause->handler_offset); */
7603                                 tblock->in_scount = 1;
7604                                 tblock->in_stack = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*));
7605                                 tblock->in_stack [0] = mono_create_exvar_for_offset (cfg, clause->handler_offset);
7606
7607                                 cfg->cbb = tblock;
7608
7609 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
7610                                 /* The EH code passes in the exception in a register to both JITted and LLVM compiled code */
7611                                 if (!cfg->compile_llvm) {
7612                                         MONO_INST_NEW (cfg, ins, OP_GET_EX_OBJ);
7613                                         ins->dreg = tblock->in_stack [0]->dreg;
7614                                         MONO_ADD_INS (tblock, ins);
7615                                 }
7616 #else
7617                                 MonoInst *dummy_use;
7618
7619                                 /* 
7620                                  * Add a dummy use for the exvar so its liveness info will be
7621                                  * correct.
7622                                  */
7623                                 EMIT_NEW_DUMMY_USE (cfg, dummy_use, tblock->in_stack [0]);
7624 #endif
7625
7626                                 if (seq_points && clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
7627                                         NEW_SEQ_POINT (cfg, ins, clause->handler_offset, TRUE);
7628                                         MONO_ADD_INS (tblock, ins);
7629                                 }
7630                                 
7631                                 if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
7632                                         GET_BBLOCK (cfg, tblock, ip + clause->data.filter_offset);
7633                                         tblock->flags |= BB_EXCEPTION_HANDLER;
7634                                         tblock->real_offset = clause->data.filter_offset;
7635                                         tblock->in_scount = 1;
7636                                         tblock->in_stack = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*));
7637                                         /* The filter block shares the exvar with the handler block */
7638                                         tblock->in_stack [0] = mono_create_exvar_for_offset (cfg, clause->handler_offset);
7639                                         MONO_INST_NEW (cfg, ins, OP_START_HANDLER);
7640                                         MONO_ADD_INS (tblock, ins);
7641                                 }
7642                         }
7643
7644                         if (clause->flags != MONO_EXCEPTION_CLAUSE_FILTER &&
7645                                         clause->data.catch_class &&
7646                                         cfg->gshared &&
7647                                         mono_class_check_context_used (clause->data.catch_class)) {
7648                                 /*
7649                                  * In shared generic code with catch
7650                                  * clauses containing type variables
7651                                  * the exception handling code has to
7652                                  * be able to get to the rgctx.
7653                                  * Therefore we have to make sure that
7654                                  * the vtable/mrgctx argument (for
7655                                  * static or generic methods) or the
7656                                  * "this" argument (for non-static
7657                                  * methods) are live.
7658                                  */
7659                                 if ((method->flags & METHOD_ATTRIBUTE_STATIC) ||
7660                                                 mini_method_get_context (method)->method_inst ||
7661                                                 method->klass->valuetype) {
7662                                         mono_get_vtable_var (cfg);
7663                                 } else {
7664                                         MonoInst *dummy_use;
7665
7666                                         EMIT_NEW_DUMMY_USE (cfg, dummy_use, arg_array [0]);
7667                                 }
7668                         }
7669                 }
7670         } else {
7671                 arg_array = (MonoInst **) alloca (sizeof (MonoInst *) * num_args);
7672                 cfg->cbb = start_bblock;
7673                 cfg->args = arg_array;
7674                 mono_save_args (cfg, sig, inline_args);
7675         }
7676
7677         /* FIRST CODE BLOCK */
7678         NEW_BBLOCK (cfg, tblock);
7679         tblock->cil_code = ip;
7680         cfg->cbb = tblock;
7681         cfg->ip = ip;
7682
7683         ADD_BBLOCK (cfg, tblock);
7684
7685         if (cfg->method == method) {
7686                 breakpoint_id = mono_debugger_method_has_breakpoint (method);
7687                 if (breakpoint_id) {
7688                         MONO_INST_NEW (cfg, ins, OP_BREAK);
7689                         MONO_ADD_INS (cfg->cbb, ins);
7690                 }
7691         }
7692
7693         /* we use a separate basic block for the initialization code */
7694         NEW_BBLOCK (cfg, init_localsbb);
7695         if (cfg->method == method)
7696                 cfg->bb_init = init_localsbb;
7697         init_localsbb->real_offset = cfg->real_offset;
7698         start_bblock->next_bb = init_localsbb;
7699         init_localsbb->next_bb = cfg->cbb;
7700         link_bblock (cfg, start_bblock, init_localsbb);
7701         link_bblock (cfg, init_localsbb, cfg->cbb);
7702                 
7703         cfg->cbb = init_localsbb;
7704
7705         if (cfg->gsharedvt && cfg->method == method) {
7706                 MonoGSharedVtMethodInfo *info;
7707                 MonoInst *var, *locals_var;
7708                 int dreg;
7709
7710                 info = (MonoGSharedVtMethodInfo *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoGSharedVtMethodInfo));
7711                 info->method = cfg->method;
7712                 info->count_entries = 16;
7713                 info->entries = (MonoRuntimeGenericContextInfoTemplate *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoRuntimeGenericContextInfoTemplate) * info->count_entries);
7714                 cfg->gsharedvt_info = info;
7715
7716                 var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
7717                 /* prevent it from being register allocated */
7718                 //var->flags |= MONO_INST_VOLATILE;
7719                 cfg->gsharedvt_info_var = var;
7720
7721                 ins = emit_get_rgctx_gsharedvt_method (cfg, mini_method_check_context_used (cfg, method), method, info);
7722                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, var->dreg, ins->dreg);
7723
7724                 /* Allocate locals */
7725                 locals_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
7726                 /* prevent it from being register allocated */
7727                 //locals_var->flags |= MONO_INST_VOLATILE;
7728                 cfg->gsharedvt_locals_var = locals_var;
7729
7730                 dreg = alloc_ireg (cfg);
7731                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, dreg, var->dreg, MONO_STRUCT_OFFSET (MonoGSharedVtMethodRuntimeInfo, locals_size));
7732
7733                 MONO_INST_NEW (cfg, ins, OP_LOCALLOC);
7734                 ins->dreg = locals_var->dreg;
7735                 ins->sreg1 = dreg;
7736                 MONO_ADD_INS (cfg->cbb, ins);
7737                 cfg->gsharedvt_locals_var_ins = ins;
7738                 
7739                 cfg->flags |= MONO_CFG_HAS_ALLOCA;
7740                 /*
7741                 if (init_locals)
7742                         ins->flags |= MONO_INST_INIT;
7743                 */
7744         }
7745
7746         if (mono_security_core_clr_enabled ()) {
7747                 /* check if this is native code, e.g. an icall or a p/invoke */
7748                 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
7749                         MonoMethod *wrapped = mono_marshal_method_from_wrapper (method);
7750                         if (wrapped) {
7751                                 gboolean pinvk = (wrapped->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL);
7752                                 gboolean icall = (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL);
7753
7754                                 /* if this ia a native call then it can only be JITted from platform code */
7755                                 if ((icall || pinvk) && method->klass && method->klass->image) {
7756                                         if (!mono_security_core_clr_is_platform_image (method->klass->image)) {
7757                                                 MonoException *ex = icall ? mono_get_exception_security () : 
7758                                                         mono_get_exception_method_access ();
7759                                                 emit_throw_exception (cfg, ex);
7760                                         }
7761                                 }
7762                         }
7763                 }
7764         }
7765
7766         CHECK_CFG_EXCEPTION;
7767
7768         if (header->code_size == 0)
7769                 UNVERIFIED;
7770
7771         if (get_basic_blocks (cfg, header, cfg->real_offset, ip, end, &err_pos)) {
7772                 ip = err_pos;
7773                 UNVERIFIED;
7774         }
7775
7776         if (cfg->method == method)
7777                 mono_debug_init_method (cfg, cfg->cbb, breakpoint_id);
7778
7779         for (n = 0; n < header->num_locals; ++n) {
7780                 if (header->locals [n]->type == MONO_TYPE_VOID && !header->locals [n]->byref)
7781                         UNVERIFIED;
7782         }
7783         class_inits = NULL;
7784
7785         /* We force the vtable variable here for all shared methods
7786            for the possibility that they might show up in a stack
7787            trace where their exact instantiation is needed. */
7788         if (cfg->gshared && method == cfg->method) {
7789                 if ((method->flags & METHOD_ATTRIBUTE_STATIC) ||
7790                                 mini_method_get_context (method)->method_inst ||
7791                                 method->klass->valuetype) {
7792                         mono_get_vtable_var (cfg);
7793                 } else {
7794                         /* FIXME: Is there a better way to do this?
7795                            We need the variable live for the duration
7796                            of the whole method. */
7797                         cfg->args [0]->flags |= MONO_INST_VOLATILE;
7798                 }
7799         }
7800
7801         /* add a check for this != NULL to inlined methods */
7802         if (is_virtual_call) {
7803                 MonoInst *arg_ins;
7804
7805                 NEW_ARGLOAD (cfg, arg_ins, 0);
7806                 MONO_ADD_INS (cfg->cbb, arg_ins);
7807                 MONO_EMIT_NEW_CHECK_THIS (cfg, arg_ins->dreg);
7808         }
7809
7810         skip_dead_blocks = !dont_verify;
7811         if (skip_dead_blocks) {
7812                 original_bb = bb = mono_basic_block_split (method, &cfg->error, header);
7813                 CHECK_CFG_ERROR;
7814                 g_assert (bb);
7815         }
7816
7817         /* we use a spare stack slot in SWITCH and NEWOBJ and others */
7818         stack_start = sp = (MonoInst **)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst*) * (header->max_stack + 1));
7819
7820         ins_flag = 0;
7821         start_new_bblock = 0;
7822         while (ip < end) {
7823                 if (cfg->method == method)
7824                         cfg->real_offset = ip - header->code;
7825                 else
7826                         cfg->real_offset = inline_offset;
7827                 cfg->ip = ip;
7828
7829                 context_used = 0;
7830
7831                 if (start_new_bblock) {
7832                         cfg->cbb->cil_length = ip - cfg->cbb->cil_code;
7833                         if (start_new_bblock == 2) {
7834                                 g_assert (ip == tblock->cil_code);
7835                         } else {
7836                                 GET_BBLOCK (cfg, tblock, ip);
7837                         }
7838                         cfg->cbb->next_bb = tblock;
7839                         cfg->cbb = tblock;
7840                         start_new_bblock = 0;
7841                         for (i = 0; i < cfg->cbb->in_scount; ++i) {
7842                                 if (cfg->verbose_level > 3)
7843                                         printf ("loading %d from temp %d\n", i, (int)cfg->cbb->in_stack [i]->inst_c0);
7844                                 EMIT_NEW_TEMPLOAD (cfg, ins, cfg->cbb->in_stack [i]->inst_c0);
7845                                 *sp++ = ins;
7846                         }
7847                         if (class_inits)
7848                                 g_slist_free (class_inits);
7849                         class_inits = NULL;
7850                 } else {
7851                         if ((tblock = cfg->cil_offset_to_bb [ip - cfg->cil_start]) && (tblock != cfg->cbb)) {
7852                                 link_bblock (cfg, cfg->cbb, tblock);
7853                                 if (sp != stack_start) {
7854                                         handle_stack_args (cfg, stack_start, sp - stack_start);
7855                                         sp = stack_start;
7856                                         CHECK_UNVERIFIABLE (cfg);
7857                                 }
7858                                 cfg->cbb->next_bb = tblock;
7859                                 cfg->cbb = tblock;
7860                                 for (i = 0; i < cfg->cbb->in_scount; ++i) {
7861                                         if (cfg->verbose_level > 3)
7862                                                 printf ("loading %d from temp %d\n", i, (int)cfg->cbb->in_stack [i]->inst_c0);
7863                                         EMIT_NEW_TEMPLOAD (cfg, ins, cfg->cbb->in_stack [i]->inst_c0);
7864                                         *sp++ = ins;
7865                                 }
7866                                 g_slist_free (class_inits);
7867                                 class_inits = NULL;
7868                         }
7869                 }
7870
7871                 if (skip_dead_blocks) {
7872                         int ip_offset = ip - header->code;
7873
7874                         if (ip_offset == bb->end)
7875                                 bb = bb->next;
7876
7877                         if (bb->dead) {
7878                                 int op_size = mono_opcode_size (ip, end);
7879                                 g_assert (op_size > 0); /*The BB formation pass must catch all bad ops*/
7880
7881                                 if (cfg->verbose_level > 3) printf ("SKIPPING DEAD OP at %x\n", ip_offset);
7882
7883                                 if (ip_offset + op_size == bb->end) {
7884                                         MONO_INST_NEW (cfg, ins, OP_NOP);
7885                                         MONO_ADD_INS (cfg->cbb, ins);
7886                                         start_new_bblock = 1;
7887                                 }
7888
7889                                 ip += op_size;
7890                                 continue;
7891                         }
7892                 }
7893                 /*
7894                  * Sequence points are points where the debugger can place a breakpoint.
7895                  * Currently, we generate these automatically at points where the IL
7896                  * stack is empty.
7897                  */
7898                 if (seq_points && ((!sym_seq_points && (sp == stack_start)) || (sym_seq_points && mono_bitset_test_fast (seq_point_locs, ip - header->code)))) {
7899                         /*
7900                          * Make methods interruptable at the beginning, and at the targets of
7901                          * backward branches.
7902                          * Also, do this at the start of every bblock in methods with clauses too,
7903                          * to be able to handle instructions with inprecise control flow like
7904                          * throw/endfinally.
7905                          * Backward branches are handled at the end of method-to-ir ().
7906                          */
7907                         gboolean intr_loc = ip == header->code || (!cfg->cbb->last_ins && cfg->header->num_clauses);
7908                         gboolean sym_seq_point = sym_seq_points && mono_bitset_test_fast (seq_point_locs, ip - header->code);
7909
7910                         /* Avoid sequence points on empty IL like .volatile */
7911                         // FIXME: Enable this
7912                         //if (!(cfg->cbb->last_ins && cfg->cbb->last_ins->opcode == OP_SEQ_POINT)) {
7913                         NEW_SEQ_POINT (cfg, ins, ip - header->code, intr_loc);
7914                         if ((sp != stack_start) && !sym_seq_point)
7915                                 ins->flags |= MONO_INST_NONEMPTY_STACK;
7916                         MONO_ADD_INS (cfg->cbb, ins);
7917
7918                         if (sym_seq_points)
7919                                 mono_bitset_set_fast (seq_point_set_locs, ip - header->code);
7920                 }
7921
7922                 cfg->cbb->real_offset = cfg->real_offset;
7923
7924                 if ((cfg->method == method) && cfg->coverage_info) {
7925                         guint32 cil_offset = ip - header->code;
7926                         cfg->coverage_info->data [cil_offset].cil_code = ip;
7927
7928                         /* TODO: Use an increment here */
7929 #if defined(TARGET_X86)
7930                         MONO_INST_NEW (cfg, ins, OP_STORE_MEM_IMM);
7931                         ins->inst_p0 = &(cfg->coverage_info->data [cil_offset].count);
7932                         ins->inst_imm = 1;
7933                         MONO_ADD_INS (cfg->cbb, ins);
7934 #else
7935                         EMIT_NEW_PCONST (cfg, ins, &(cfg->coverage_info->data [cil_offset].count));
7936                         MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STORE_MEMBASE_IMM, ins->dreg, 0, 1);
7937 #endif
7938                 }
7939
7940                 if (cfg->verbose_level > 3)
7941                         printf ("converting (in B%d: stack: %d) %s", cfg->cbb->block_num, (int)(sp - stack_start), mono_disasm_code_one (NULL, method, ip, NULL));
7942
7943                 switch (*ip) {
7944                 case CEE_NOP:
7945                         if (seq_points && !sym_seq_points && sp != stack_start) {
7946                                 /*
7947                                  * The C# compiler uses these nops to notify the JIT that it should
7948                                  * insert seq points.
7949                                  */
7950                                 NEW_SEQ_POINT (cfg, ins, ip - header->code, FALSE);
7951                                 MONO_ADD_INS (cfg->cbb, ins);
7952                         }
7953                         if (cfg->keep_cil_nops)
7954                                 MONO_INST_NEW (cfg, ins, OP_HARD_NOP);
7955                         else
7956                                 MONO_INST_NEW (cfg, ins, OP_NOP);
7957                         ip++;
7958                         MONO_ADD_INS (cfg->cbb, ins);
7959                         break;
7960                 case CEE_BREAK:
7961                         if (should_insert_brekpoint (cfg->method)) {
7962                                 ins = mono_emit_jit_icall (cfg, mono_debugger_agent_user_break, NULL);
7963                         } else {
7964                                 MONO_INST_NEW (cfg, ins, OP_NOP);
7965                         }
7966                         ip++;
7967                         MONO_ADD_INS (cfg->cbb, ins);
7968                         break;
7969                 case CEE_LDARG_0:
7970                 case CEE_LDARG_1:
7971                 case CEE_LDARG_2:
7972                 case CEE_LDARG_3:
7973                         CHECK_STACK_OVF (1);
7974                         n = (*ip)-CEE_LDARG_0;
7975                         CHECK_ARG (n);
7976                         EMIT_NEW_ARGLOAD (cfg, ins, n);
7977                         ip++;
7978                         *sp++ = ins;
7979                         break;
7980                 case CEE_LDLOC_0:
7981                 case CEE_LDLOC_1:
7982                 case CEE_LDLOC_2:
7983                 case CEE_LDLOC_3:
7984                         CHECK_STACK_OVF (1);
7985                         n = (*ip)-CEE_LDLOC_0;
7986                         CHECK_LOCAL (n);
7987                         EMIT_NEW_LOCLOAD (cfg, ins, n);
7988                         ip++;
7989                         *sp++ = ins;
7990                         break;
7991                 case CEE_STLOC_0:
7992                 case CEE_STLOC_1:
7993                 case CEE_STLOC_2:
7994                 case CEE_STLOC_3: {
7995                         CHECK_STACK (1);
7996                         n = (*ip)-CEE_STLOC_0;
7997                         CHECK_LOCAL (n);
7998                         --sp;
7999                         if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [n], *sp))
8000                                 UNVERIFIED;
8001                         emit_stloc_ir (cfg, sp, header, n);
8002                         ++ip;
8003                         inline_costs += 1;
8004                         break;
8005                         }
8006                 case CEE_LDARG_S:
8007                         CHECK_OPSIZE (2);
8008                         CHECK_STACK_OVF (1);
8009                         n = ip [1];
8010                         CHECK_ARG (n);
8011                         EMIT_NEW_ARGLOAD (cfg, ins, n);
8012                         *sp++ = ins;
8013                         ip += 2;
8014                         break;
8015                 case CEE_LDARGA_S:
8016                         CHECK_OPSIZE (2);
8017                         CHECK_STACK_OVF (1);
8018                         n = ip [1];
8019                         CHECK_ARG (n);
8020                         NEW_ARGLOADA (cfg, ins, n);
8021                         MONO_ADD_INS (cfg->cbb, ins);
8022                         *sp++ = ins;
8023                         ip += 2;
8024                         break;
8025                 case CEE_STARG_S:
8026                         CHECK_OPSIZE (2);
8027                         CHECK_STACK (1);
8028                         --sp;
8029                         n = ip [1];
8030                         CHECK_ARG (n);
8031                         if (!dont_verify_stloc && target_type_is_incompatible (cfg, param_types [ip [1]], *sp))
8032                                 UNVERIFIED;
8033                         EMIT_NEW_ARGSTORE (cfg, ins, n, *sp);
8034                         ip += 2;
8035                         break;
8036                 case CEE_LDLOC_S:
8037                         CHECK_OPSIZE (2);
8038                         CHECK_STACK_OVF (1);
8039                         n = ip [1];
8040                         CHECK_LOCAL (n);
8041                         EMIT_NEW_LOCLOAD (cfg, ins, n);
8042                         *sp++ = ins;
8043                         ip += 2;
8044                         break;
8045                 case CEE_LDLOCA_S: {
8046                         unsigned char *tmp_ip;
8047                         CHECK_OPSIZE (2);
8048                         CHECK_STACK_OVF (1);
8049                         CHECK_LOCAL (ip [1]);
8050
8051                         if ((tmp_ip = emit_optimized_ldloca_ir (cfg, ip, end, 1))) {
8052                                 ip = tmp_ip;
8053                                 inline_costs += 1;
8054                                 break;
8055                         }
8056
8057                         EMIT_NEW_LOCLOADA (cfg, ins, ip [1]);
8058                         *sp++ = ins;
8059                         ip += 2;
8060                         break;
8061                 }
8062                 case CEE_STLOC_S:
8063                         CHECK_OPSIZE (2);
8064                         CHECK_STACK (1);
8065                         --sp;
8066                         CHECK_LOCAL (ip [1]);
8067                         if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [ip [1]], *sp))
8068                                 UNVERIFIED;
8069                         emit_stloc_ir (cfg, sp, header, ip [1]);
8070                         ip += 2;
8071                         inline_costs += 1;
8072                         break;
8073                 case CEE_LDNULL:
8074                         CHECK_STACK_OVF (1);
8075                         EMIT_NEW_PCONST (cfg, ins, NULL);
8076                         ins->type = STACK_OBJ;
8077                         ++ip;
8078                         *sp++ = ins;
8079                         break;
8080                 case CEE_LDC_I4_M1:
8081                         CHECK_STACK_OVF (1);
8082                         EMIT_NEW_ICONST (cfg, ins, -1);
8083                         ++ip;
8084                         *sp++ = ins;
8085                         break;
8086                 case CEE_LDC_I4_0:
8087                 case CEE_LDC_I4_1:
8088                 case CEE_LDC_I4_2:
8089                 case CEE_LDC_I4_3:
8090                 case CEE_LDC_I4_4:
8091                 case CEE_LDC_I4_5:
8092                 case CEE_LDC_I4_6:
8093                 case CEE_LDC_I4_7:
8094                 case CEE_LDC_I4_8:
8095                         CHECK_STACK_OVF (1);
8096                         EMIT_NEW_ICONST (cfg, ins, (*ip) - CEE_LDC_I4_0);
8097                         ++ip;
8098                         *sp++ = ins;
8099                         break;
8100                 case CEE_LDC_I4_S:
8101                         CHECK_OPSIZE (2);
8102                         CHECK_STACK_OVF (1);
8103                         ++ip;
8104                         EMIT_NEW_ICONST (cfg, ins, *((signed char*)ip));
8105                         ++ip;
8106                         *sp++ = ins;
8107                         break;
8108                 case CEE_LDC_I4:
8109                         CHECK_OPSIZE (5);
8110                         CHECK_STACK_OVF (1);
8111                         EMIT_NEW_ICONST (cfg, ins, (gint32)read32 (ip + 1));
8112                         ip += 5;
8113                         *sp++ = ins;
8114                         break;
8115                 case CEE_LDC_I8:
8116                         CHECK_OPSIZE (9);
8117                         CHECK_STACK_OVF (1);
8118                         MONO_INST_NEW (cfg, ins, OP_I8CONST);
8119                         ins->type = STACK_I8;
8120                         ins->dreg = alloc_dreg (cfg, STACK_I8);
8121                         ++ip;
8122                         ins->inst_l = (gint64)read64 (ip);
8123                         MONO_ADD_INS (cfg->cbb, ins);
8124                         ip += 8;
8125                         *sp++ = ins;
8126                         break;
8127                 case CEE_LDC_R4: {
8128                         float *f;
8129                         gboolean use_aotconst = FALSE;
8130
8131 #ifdef TARGET_POWERPC
8132                         /* FIXME: Clean this up */
8133                         if (cfg->compile_aot)
8134                                 use_aotconst = TRUE;
8135 #endif
8136
8137                         /* FIXME: we should really allocate this only late in the compilation process */
8138                         f = (float *)mono_domain_alloc (cfg->domain, sizeof (float));
8139                         CHECK_OPSIZE (5);
8140                         CHECK_STACK_OVF (1);
8141
8142                         if (use_aotconst) {
8143                                 MonoInst *cons;
8144                                 int dreg;
8145
8146                                 EMIT_NEW_AOTCONST (cfg, cons, MONO_PATCH_INFO_R4, f);
8147
8148                                 dreg = alloc_freg (cfg);
8149                                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADR4_MEMBASE, dreg, cons->dreg, 0);
8150                                 ins->type = cfg->r4_stack_type;
8151                         } else {
8152                                 MONO_INST_NEW (cfg, ins, OP_R4CONST);
8153                                 ins->type = cfg->r4_stack_type;
8154                                 ins->dreg = alloc_dreg (cfg, STACK_R8);
8155                                 ins->inst_p0 = f;
8156                                 MONO_ADD_INS (cfg->cbb, ins);
8157                         }
8158                         ++ip;
8159                         readr4 (ip, f);
8160                         ip += 4;
8161                         *sp++ = ins;                    
8162                         break;
8163                 }
8164                 case CEE_LDC_R8: {
8165                         double *d;
8166                         gboolean use_aotconst = FALSE;
8167
8168 #ifdef TARGET_POWERPC
8169                         /* FIXME: Clean this up */
8170                         if (cfg->compile_aot)
8171                                 use_aotconst = TRUE;
8172 #endif
8173
8174                         /* FIXME: we should really allocate this only late in the compilation process */
8175                         d = (double *)mono_domain_alloc (cfg->domain, sizeof (double));
8176                         CHECK_OPSIZE (9);
8177                         CHECK_STACK_OVF (1);
8178
8179                         if (use_aotconst) {
8180                                 MonoInst *cons;
8181                                 int dreg;
8182
8183                                 EMIT_NEW_AOTCONST (cfg, cons, MONO_PATCH_INFO_R8, d);
8184
8185                                 dreg = alloc_freg (cfg);
8186                                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADR8_MEMBASE, dreg, cons->dreg, 0);
8187                                 ins->type = STACK_R8;
8188                         } else {
8189                                 MONO_INST_NEW (cfg, ins, OP_R8CONST);
8190                                 ins->type = STACK_R8;
8191                                 ins->dreg = alloc_dreg (cfg, STACK_R8);
8192                                 ins->inst_p0 = d;
8193                                 MONO_ADD_INS (cfg->cbb, ins);
8194                         }
8195                         ++ip;
8196                         readr8 (ip, d);
8197                         ip += 8;
8198                         *sp++ = ins;
8199                         break;
8200                 }
8201                 case CEE_DUP: {
8202                         MonoInst *temp, *store;
8203                         CHECK_STACK (1);
8204                         CHECK_STACK_OVF (1);
8205                         sp--;
8206                         ins = *sp;
8207
8208                         temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
8209                         EMIT_NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
8210
8211                         EMIT_NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
8212                         *sp++ = ins;
8213
8214                         EMIT_NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
8215                         *sp++ = ins;
8216
8217                         ++ip;
8218                         inline_costs += 2;
8219                         break;
8220                 }
8221                 case CEE_POP:
8222                         CHECK_STACK (1);
8223                         ip++;
8224                         --sp;
8225
8226 #ifdef TARGET_X86
8227                         if (sp [0]->type == STACK_R8)
8228                                 /* we need to pop the value from the x86 FP stack */
8229                                 MONO_EMIT_NEW_UNALU (cfg, OP_X86_FPOP, -1, sp [0]->dreg);
8230 #endif
8231                         break;
8232                 case CEE_JMP: {
8233                         MonoCallInst *call;
8234                         MonoMethodSignature *fsig;
8235                         int i, n;
8236
8237                         INLINE_FAILURE ("jmp");
8238                         GSHAREDVT_FAILURE (*ip);
8239
8240                         CHECK_OPSIZE (5);
8241                         if (stack_start != sp)
8242                                 UNVERIFIED;
8243                         token = read32 (ip + 1);
8244                         /* FIXME: check the signature matches */
8245                         cmethod = mini_get_method (cfg, method, token, NULL, generic_context);
8246                         CHECK_CFG_ERROR;
8247  
8248                         if (cfg->gshared && mono_method_check_context_used (cmethod))
8249                                 GENERIC_SHARING_FAILURE (CEE_JMP);
8250
8251                         emit_instrumentation_call (cfg, mono_profiler_method_leave);
8252
8253                         fsig = mono_method_signature (cmethod);
8254                         n = fsig->param_count + fsig->hasthis;
8255                         if (cfg->llvm_only) {
8256                                 MonoInst **args;
8257
8258                                 args = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * n);
8259                                 for (i = 0; i < n; ++i)
8260                                         EMIT_NEW_ARGLOAD (cfg, args [i], i);
8261                                 ins = mono_emit_method_call_full (cfg, cmethod, fsig, TRUE, args, NULL, NULL, NULL);
8262                                 /*
8263                                  * The code in mono-basic-block.c treats the rest of the code as dead, but we
8264                                  * have to emit a normal return since llvm expects it.
8265                                  */
8266                                 if (cfg->ret)
8267                                         emit_setret (cfg, ins);
8268                                 MONO_INST_NEW (cfg, ins, OP_BR);
8269                                 ins->inst_target_bb = end_bblock;
8270                                 MONO_ADD_INS (cfg->cbb, ins);
8271                                 link_bblock (cfg, cfg->cbb, end_bblock);
8272                                 ip += 5;
8273                                 break;
8274                         } else if (cfg->backend->have_op_tail_call) {
8275                                 /* Handle tail calls similarly to calls */
8276                                 DISABLE_AOT (cfg);
8277
8278                                 MONO_INST_NEW_CALL (cfg, call, OP_TAILCALL);
8279                                 call->method = cmethod;
8280                                 call->tail_call = TRUE;
8281                                 call->signature = mono_method_signature (cmethod);
8282                                 call->args = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * n);
8283                                 call->inst.inst_p0 = cmethod;
8284                                 for (i = 0; i < n; ++i)
8285                                         EMIT_NEW_ARGLOAD (cfg, call->args [i], i);
8286
8287                                 if (mini_type_is_vtype (mini_get_underlying_type (call->signature->ret)))
8288                                         call->vret_var = cfg->vret_addr;
8289
8290                                 mono_arch_emit_call (cfg, call);
8291                                 cfg->param_area = MAX(cfg->param_area, call->stack_usage);
8292                                 MONO_ADD_INS (cfg->cbb, (MonoInst*)call);
8293                         } else {
8294                                 for (i = 0; i < num_args; ++i)
8295                                         /* Prevent arguments from being optimized away */
8296                                         arg_array [i]->flags |= MONO_INST_VOLATILE;
8297
8298                                 MONO_INST_NEW_CALL (cfg, call, OP_JMP);
8299                                 ins = (MonoInst*)call;
8300                                 ins->inst_p0 = cmethod;
8301                                 MONO_ADD_INS (cfg->cbb, ins);
8302                         }
8303
8304                         ip += 5;
8305                         start_new_bblock = 1;
8306                         break;
8307                 }
8308                 case CEE_CALLI: {
8309                         MonoInst *addr;
8310                         MonoMethodSignature *fsig;
8311
8312                         CHECK_OPSIZE (5);
8313                         token = read32 (ip + 1);
8314
8315                         ins = NULL;
8316
8317                         //GSHAREDVT_FAILURE (*ip);
8318                         cmethod = NULL;
8319                         CHECK_STACK (1);
8320                         --sp;
8321                         addr = *sp;
8322                         fsig = mini_get_signature (method, token, generic_context, &cfg->error);
8323                         CHECK_CFG_ERROR;
8324
8325                         if (method->dynamic && fsig->pinvoke) {
8326                                 MonoInst *args [3];
8327
8328                                 /*
8329                                  * This is a call through a function pointer using a pinvoke
8330                                  * signature. Have to create a wrapper and call that instead.
8331                                  * FIXME: This is very slow, need to create a wrapper at JIT time
8332                                  * instead based on the signature.
8333                                  */
8334                                 EMIT_NEW_IMAGECONST (cfg, args [0], method->klass->image);
8335                                 EMIT_NEW_PCONST (cfg, args [1], fsig);
8336                                 args [2] = addr;
8337                                 addr = mono_emit_jit_icall (cfg, mono_get_native_calli_wrapper, args);
8338                         }
8339
8340                         n = fsig->param_count + fsig->hasthis;
8341
8342                         CHECK_STACK (n);
8343
8344                         //g_assert (!virtual_ || fsig->hasthis);
8345
8346                         sp -= n;
8347
8348                         inline_costs += 10 * num_calls++;
8349
8350                         /*
8351                          * Making generic calls out of gsharedvt methods.
8352                          * This needs to be used for all generic calls, not just ones with a gsharedvt signature, to avoid
8353                          * patching gshared method addresses into a gsharedvt method.
8354                          */
8355                         if (cfg->gsharedvt && mini_is_gsharedvt_signature (fsig)) {
8356                                 /*
8357                                  * We pass the address to the gsharedvt trampoline in the rgctx reg
8358                                  */
8359                                 MonoInst *callee = addr;
8360
8361                                 if (method->wrapper_type != MONO_WRAPPER_DELEGATE_INVOKE)
8362                                         /* Not tested */
8363                                         GSHAREDVT_FAILURE (*ip);
8364
8365                                 if (cfg->llvm_only)
8366                                         // FIXME:
8367                                         GSHAREDVT_FAILURE (*ip);
8368
8369                                 addr = emit_get_rgctx_sig (cfg, context_used,
8370                                                                                           fsig, MONO_RGCTX_INFO_SIG_GSHAREDVT_OUT_TRAMPOLINE_CALLI);
8371                                 ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, NULL, callee);
8372                                 goto calli_end;
8373                         }
8374
8375                         /* Prevent inlining of methods with indirect calls */
8376                         INLINE_FAILURE ("indirect call");
8377
8378                         if (addr->opcode == OP_PCONST || addr->opcode == OP_AOTCONST || addr->opcode == OP_GOT_ENTRY) {
8379                                 MonoJumpInfoType info_type;
8380                                 gpointer info_data;
8381
8382                                 /*
8383                                  * Instead of emitting an indirect call, emit a direct call
8384                                  * with the contents of the aotconst as the patch info.
8385                                  */
8386                                 if (addr->opcode == OP_PCONST || addr->opcode == OP_AOTCONST) {
8387                                         info_type = (MonoJumpInfoType)addr->inst_c1;
8388                                         info_data = addr->inst_p0;
8389                                 } else {
8390                                         info_type = (MonoJumpInfoType)addr->inst_right->inst_c1;
8391                                         info_data = addr->inst_right->inst_left;
8392                                 }
8393
8394                                 if (info_type == MONO_PATCH_INFO_ICALL_ADDR) {
8395                                         ins = (MonoInst*)mono_emit_abs_call (cfg, MONO_PATCH_INFO_ICALL_ADDR_CALL, info_data, fsig, sp);
8396                                         NULLIFY_INS (addr);
8397                                         goto calli_end;
8398                                 } else if (info_type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
8399                                         ins = (MonoInst*)mono_emit_abs_call (cfg, info_type, info_data, fsig, sp);
8400                                         NULLIFY_INS (addr);
8401                                         goto calli_end;
8402                                 }
8403                         }
8404                         ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
8405
8406                         calli_end:
8407
8408                         /* End of call, INS should contain the result of the call, if any */
8409
8410                         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
8411                                 g_assert (ins);
8412                                 *sp++ = mono_emit_widen_call_res (cfg, ins, fsig);
8413                         }
8414
8415                         CHECK_CFG_EXCEPTION;
8416
8417                         ip += 5;
8418                         ins_flag = 0;
8419                         constrained_class = NULL;
8420                         break;
8421                 }
8422                 case CEE_CALL:
8423                 case CEE_CALLVIRT: {
8424                         MonoInst *addr = NULL;
8425                         MonoMethodSignature *fsig = NULL;
8426                         int array_rank = 0;
8427                         int virtual_ = *ip == CEE_CALLVIRT;
8428                         gboolean pass_imt_from_rgctx = FALSE;
8429                         MonoInst *imt_arg = NULL;
8430                         MonoInst *keep_this_alive = NULL;
8431                         gboolean pass_vtable = FALSE;
8432                         gboolean pass_mrgctx = FALSE;
8433                         MonoInst *vtable_arg = NULL;
8434                         gboolean check_this = FALSE;
8435                         gboolean supported_tail_call = FALSE;
8436                         gboolean tail_call = FALSE;
8437                         gboolean need_seq_point = FALSE;
8438                         guint32 call_opcode = *ip;
8439                         gboolean emit_widen = TRUE;
8440                         gboolean push_res = TRUE;
8441                         gboolean skip_ret = FALSE;
8442                         gboolean delegate_invoke = FALSE;
8443                         gboolean direct_icall = FALSE;
8444                         gboolean constrained_partial_call = FALSE;
8445                         MonoMethod *cil_method;
8446
8447                         CHECK_OPSIZE (5);
8448                         token = read32 (ip + 1);
8449
8450                         ins = NULL;
8451
8452                         cmethod = mini_get_method (cfg, method, token, NULL, generic_context);
8453                         CHECK_CFG_ERROR;
8454
8455                         cil_method = cmethod;
8456                                 
8457                         if (constrained_class) {
8458                                 if ((constrained_class->byval_arg.type == MONO_TYPE_VAR || constrained_class->byval_arg.type == MONO_TYPE_MVAR) && cfg->gshared) {
8459                                         if (!mini_is_gsharedvt_klass (constrained_class)) {
8460                                                 g_assert (!cmethod->klass->valuetype);
8461                                                 if (!mini_type_is_reference (&constrained_class->byval_arg))
8462                                                         constrained_partial_call = TRUE;
8463                                         }
8464                                 }
8465
8466                                 if (method->wrapper_type != MONO_WRAPPER_NONE) {
8467                                         if (cfg->verbose_level > 2)
8468                                                 printf ("DM Constrained call to %s\n", mono_type_get_full_name (constrained_class));
8469                                         if (!((constrained_class->byval_arg.type == MONO_TYPE_VAR ||
8470                                                    constrained_class->byval_arg.type == MONO_TYPE_MVAR) &&
8471                                                   cfg->gshared)) {
8472                                                 cmethod = mono_get_method_constrained_with_method (image, cil_method, constrained_class, generic_context, &cfg->error);
8473                                                 CHECK_CFG_ERROR;
8474                                         }
8475                                 } else {
8476                                         if (cfg->verbose_level > 2)
8477                                                 printf ("Constrained call to %s\n", mono_type_get_full_name (constrained_class));
8478
8479                                         if ((constrained_class->byval_arg.type == MONO_TYPE_VAR || constrained_class->byval_arg.type == MONO_TYPE_MVAR) && cfg->gshared) {
8480                                                 /* 
8481                                                  * This is needed since get_method_constrained can't find 
8482                                                  * the method in klass representing a type var.
8483                                                  * The type var is guaranteed to be a reference type in this
8484                                                  * case.
8485                                                  */
8486                                                 if (!mini_is_gsharedvt_klass (constrained_class))
8487                                                         g_assert (!cmethod->klass->valuetype);
8488                                         } else {
8489                                                 cmethod = mono_get_method_constrained_checked (image, token, constrained_class, generic_context, &cil_method, &cfg->error);
8490                                                 CHECK_CFG_ERROR;
8491                                         }
8492                                 }
8493
8494                                 if (constrained_class->enumtype && !strcmp (cmethod->name, "GetHashCode")) {
8495                                         /* Use the corresponding method from the base type to avoid boxing */
8496                                         MonoType *base_type = mono_class_enum_basetype (constrained_class);
8497                                         g_assert (base_type);
8498                                         constrained_class = mono_class_from_mono_type (base_type);
8499                                         cmethod = mono_class_get_method_from_name (constrained_class, cmethod->name, 0);
8500                                         g_assert (cmethod);
8501                                 }
8502                         }
8503                                         
8504                         if (!dont_verify && !cfg->skip_visibility) {
8505                                 MonoMethod *target_method = cil_method;
8506                                 if (method->is_inflated) {
8507                                         target_method = mini_get_method_allow_open (method, token, NULL, &(mono_method_get_generic_container (method_definition)->context), &cfg->error);
8508                                         CHECK_CFG_ERROR;
8509                                 }
8510                                 if (!mono_method_can_access_method (method_definition, target_method) &&
8511                                         !mono_method_can_access_method (method, cil_method))
8512                                         emit_method_access_failure (cfg, method, cil_method);
8513                         }
8514
8515                         if (mono_security_core_clr_enabled ())
8516                                 ensure_method_is_allowed_to_call_method (cfg, method, cil_method);
8517
8518                         if (!virtual_ && (cmethod->flags & METHOD_ATTRIBUTE_ABSTRACT))
8519                                 /* MS.NET seems to silently convert this to a callvirt */
8520                                 virtual_ = 1;
8521
8522                         {
8523                                 /*
8524                                  * MS.NET accepts non virtual calls to virtual final methods of transparent proxy classes and
8525                                  * converts to a callvirt.
8526                                  *
8527                                  * tests/bug-515884.il is an example of this behavior
8528                                  */
8529                                 const int test_flags = METHOD_ATTRIBUTE_VIRTUAL | METHOD_ATTRIBUTE_FINAL | METHOD_ATTRIBUTE_STATIC;
8530                                 const int expected_flags = METHOD_ATTRIBUTE_VIRTUAL | METHOD_ATTRIBUTE_FINAL;
8531                                 if (!virtual_ && mono_class_is_marshalbyref (cmethod->klass) && (cmethod->flags & test_flags) == expected_flags && cfg->method->wrapper_type == MONO_WRAPPER_NONE)
8532                                         virtual_ = 1;
8533                         }
8534
8535                         if (!cmethod->klass->inited)
8536                                 if (!mono_class_init (cmethod->klass))
8537                                         TYPE_LOAD_ERROR (cmethod->klass);
8538
8539                         fsig = mono_method_signature (cmethod);
8540                         if (!fsig)
8541                                 LOAD_ERROR;
8542                         if (cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL &&
8543                                 mini_class_is_system_array (cmethod->klass)) {
8544                                 array_rank = cmethod->klass->rank;
8545                         } else if ((cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && icall_is_direct_callable (cfg, cmethod)) {
8546                                 direct_icall = TRUE;
8547                         } else if (fsig->pinvoke) {
8548                                 MonoMethod *wrapper = mono_marshal_get_native_wrapper (cmethod, TRUE, cfg->compile_aot);
8549                                 fsig = mono_method_signature (wrapper);
8550                         } else if (constrained_class) {
8551                         } else {
8552                                 fsig = mono_method_get_signature_checked (cmethod, image, token, generic_context, &cfg->error);
8553                                 CHECK_CFG_ERROR;
8554                         }
8555
8556                         if (cfg->llvm_only && !cfg->method->wrapper_type && (!cmethod || cmethod->is_inflated))
8557                                 cfg->signatures = g_slist_prepend_mempool (cfg->mempool, cfg->signatures, fsig);
8558
8559                         /* See code below */
8560                         if (cmethod->klass == mono_defaults.monitor_class && !strcmp (cmethod->name, "Enter") && mono_method_signature (cmethod)->param_count == 1) {
8561                                 MonoBasicBlock *tbb;
8562
8563                                 GET_BBLOCK (cfg, tbb, ip + 5);
8564                                 if (tbb->try_start && MONO_REGION_FLAGS(tbb->region) == MONO_EXCEPTION_CLAUSE_FINALLY) {
8565                                         /*
8566                                          * We want to extend the try block to cover the call, but we can't do it if the
8567                                          * call is made directly since its followed by an exception check.
8568                                          */
8569                                         direct_icall = FALSE;
8570                                 }
8571                         }
8572
8573                         mono_save_token_info (cfg, image, token, cil_method);
8574
8575                         if (!(seq_point_locs && mono_bitset_test_fast (seq_point_locs, ip + 5 - header->code)))
8576                                 need_seq_point = TRUE;
8577
8578                         /* Don't support calls made using type arguments for now */
8579                         /*
8580                           if (cfg->gsharedvt) {
8581                           if (mini_is_gsharedvt_signature (fsig))
8582                           GSHAREDVT_FAILURE (*ip);
8583                           }
8584                         */
8585
8586                         if (cmethod->string_ctor && method->wrapper_type != MONO_WRAPPER_RUNTIME_INVOKE)
8587                                 g_assert_not_reached ();
8588
8589                         n = fsig->param_count + fsig->hasthis;
8590
8591                         if (!cfg->gshared && mono_class_is_gtd (cmethod->klass))
8592                                 UNVERIFIED;
8593
8594                         if (!cfg->gshared)
8595                                 g_assert (!mono_method_check_context_used (cmethod));
8596
8597                         CHECK_STACK (n);
8598
8599                         //g_assert (!virtual_ || fsig->hasthis);
8600
8601                         sp -= n;
8602
8603                         /*
8604                          * We have the `constrained.' prefix opcode.
8605                          */
8606                         if (constrained_class) {
8607                                 if (mini_is_gsharedvt_klass (constrained_class)) {
8608                                         if ((cmethod->klass != mono_defaults.object_class) && constrained_class->valuetype && cmethod->klass->valuetype) {
8609                                                 /* The 'Own method' case below */
8610                                         } else if (cmethod->klass->image != mono_defaults.corlib && !mono_class_is_interface (cmethod->klass) && !cmethod->klass->valuetype) {
8611                                                 /* 'The type parameter is instantiated as a reference type' case below. */
8612                                         } else {
8613                                                 ins = handle_constrained_gsharedvt_call (cfg, cmethod, fsig, sp, constrained_class, &emit_widen);
8614                                                 CHECK_CFG_EXCEPTION;
8615                                                 g_assert (ins);
8616                                                 goto call_end;
8617                                         }
8618                                 }
8619
8620                                 if (constrained_partial_call) {
8621                                         gboolean need_box = TRUE;
8622
8623                                         /*
8624                                          * The receiver is a valuetype, but the exact type is not known at compile time. This means the
8625                                          * called method is not known at compile time either. The called method could end up being
8626                                          * one of the methods on the parent classes (object/valuetype/enum), in which case we need
8627                                          * to box the receiver.
8628                                          * A simple solution would be to box always and make a normal virtual call, but that would
8629                                          * be bad performance wise.
8630                                          */
8631                                         if (mono_class_is_interface (cmethod->klass) && mono_class_is_ginst (cmethod->klass)) {
8632                                                 /*
8633                                                  * The parent classes implement no generic interfaces, so the called method will be a vtype method, so no boxing neccessary.
8634                                                  */
8635                                                 need_box = FALSE;
8636                                         }
8637
8638                                         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)) {
8639                                                 /* The called method is not virtual, i.e. Object:GetType (), the receiver is a vtype, has to box */
8640                                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &constrained_class->byval_arg, sp [0]->dreg, 0);
8641                                                 ins->klass = constrained_class;
8642                                                 sp [0] = handle_box (cfg, ins, constrained_class, mono_class_check_context_used (constrained_class));
8643                                                 CHECK_CFG_EXCEPTION;
8644                                         } else if (need_box) {
8645                                                 MonoInst *box_type;
8646                                                 MonoBasicBlock *is_ref_bb, *end_bb;
8647                                                 MonoInst *nonbox_call;
8648
8649                                                 /*
8650                                                  * Determine at runtime whenever the called method is defined on object/valuetype/enum, and emit a boxing call
8651                                                  * if needed.
8652                                                  * FIXME: It is possible to inline the called method in a lot of cases, i.e. for T_INT,
8653                                                  * the no-box case goes to a method in Int32, while the box case goes to a method in Enum.
8654                                                  */
8655                                                 addr = emit_get_rgctx_virt_method (cfg, mono_class_check_context_used (constrained_class), constrained_class, cmethod, MONO_RGCTX_INFO_VIRT_METHOD_CODE);
8656
8657                                                 NEW_BBLOCK (cfg, is_ref_bb);
8658                                                 NEW_BBLOCK (cfg, end_bb);
8659
8660                                                 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);
8661                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, box_type->dreg, MONO_GSHAREDVT_BOX_TYPE_REF);
8662                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, is_ref_bb);
8663
8664                                                 /* Non-ref case */
8665                                                 nonbox_call = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
8666
8667                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
8668
8669                                                 /* Ref case */
8670                                                 MONO_START_BB (cfg, is_ref_bb);
8671                                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &constrained_class->byval_arg, sp [0]->dreg, 0);
8672                                                 ins->klass = constrained_class;
8673                                                 sp [0] = handle_box (cfg, ins, constrained_class, mono_class_check_context_used (constrained_class));
8674                                                 ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
8675
8676                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
8677
8678                                                 MONO_START_BB (cfg, end_bb);
8679                                                 cfg->cbb = end_bb;
8680
8681                                                 nonbox_call->dreg = ins->dreg;
8682                                                 goto call_end;
8683                                         } else {
8684                                                 g_assert (mono_class_is_interface (cmethod->klass));
8685                                                 addr = emit_get_rgctx_virt_method (cfg, mono_class_check_context_used (constrained_class), constrained_class, cmethod, MONO_RGCTX_INFO_VIRT_METHOD_CODE);
8686                                                 ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
8687                                                 goto call_end;
8688                                         }
8689                                 } else if (constrained_class->valuetype && (cmethod->klass == mono_defaults.object_class || cmethod->klass == mono_defaults.enum_class->parent || cmethod->klass == mono_defaults.enum_class)) {
8690                                         /*
8691                                          * The type parameter is instantiated as a valuetype,
8692                                          * but that type doesn't override the method we're
8693                                          * calling, so we need to box `this'.
8694                                          */
8695                                         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &constrained_class->byval_arg, sp [0]->dreg, 0);
8696                                         ins->klass = constrained_class;
8697                                         sp [0] = handle_box (cfg, ins, constrained_class, mono_class_check_context_used (constrained_class));
8698                                         CHECK_CFG_EXCEPTION;
8699                                 } else if (!constrained_class->valuetype) {
8700                                         int dreg = alloc_ireg_ref (cfg);
8701
8702                                         /*
8703                                          * The type parameter is instantiated as a reference
8704                                          * type.  We have a managed pointer on the stack, so
8705                                          * we need to dereference it here.
8706                                          */
8707                                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, dreg, sp [0]->dreg, 0);
8708                                         ins->type = STACK_OBJ;
8709                                         sp [0] = ins;
8710                                 } else {
8711                                         if (cmethod->klass->valuetype) {
8712                                                 /* Own method */
8713                                         } else {
8714                                                 /* Interface method */
8715                                                 int ioffset, slot;
8716
8717                                                 mono_class_setup_vtable (constrained_class);
8718                                                 CHECK_TYPELOAD (constrained_class);
8719                                                 ioffset = mono_class_interface_offset (constrained_class, cmethod->klass);
8720                                                 if (ioffset == -1)
8721                                                         TYPE_LOAD_ERROR (constrained_class);
8722                                                 slot = mono_method_get_vtable_slot (cmethod);
8723                                                 if (slot == -1)
8724                                                         TYPE_LOAD_ERROR (cmethod->klass);
8725                                                 cmethod = constrained_class->vtable [ioffset + slot];
8726
8727                                                 if (cmethod->klass == mono_defaults.enum_class) {
8728                                                         /* Enum implements some interfaces, so treat this as the first case */
8729                                                         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &constrained_class->byval_arg, sp [0]->dreg, 0);
8730                                                         ins->klass = constrained_class;
8731                                                         sp [0] = handle_box (cfg, ins, constrained_class, mono_class_check_context_used (constrained_class));
8732                                                         CHECK_CFG_EXCEPTION;
8733                                                 }
8734                                         }
8735                                         virtual_ = 0;
8736                                 }
8737                                 constrained_class = NULL;
8738                         }
8739
8740                         if (check_call_signature (cfg, fsig, sp))
8741                                 UNVERIFIED;
8742
8743                         if ((cmethod->klass->parent == mono_defaults.multicastdelegate_class) && !strcmp (cmethod->name, "Invoke"))
8744                                 delegate_invoke = TRUE;
8745
8746                         if ((cfg->opt & MONO_OPT_INTRINS) && (ins = mini_emit_inst_for_sharable_method (cfg, cmethod, fsig, sp))) {
8747                                 if (!MONO_TYPE_IS_VOID (fsig->ret)) {
8748                                         type_to_eval_stack_type ((cfg), fsig->ret, ins);
8749                                         emit_widen = FALSE;
8750                                 }
8751
8752                                 goto call_end;
8753                         }
8754
8755                         /* 
8756                          * If the callee is a shared method, then its static cctor
8757                          * might not get called after the call was patched.
8758                          */
8759                         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)) {
8760                                 emit_class_init (cfg, cmethod->klass);
8761                                 CHECK_TYPELOAD (cmethod->klass);
8762                         }
8763
8764                         check_method_sharing (cfg, cmethod, &pass_vtable, &pass_mrgctx);
8765
8766                         if (cfg->gshared) {
8767                                 MonoGenericContext *cmethod_context = mono_method_get_context (cmethod);
8768
8769                                 context_used = mini_method_check_context_used (cfg, cmethod);
8770
8771                                 if (context_used && mono_class_is_interface (cmethod->klass)) {
8772                                         /* Generic method interface
8773                                            calls are resolved via a
8774                                            helper function and don't
8775                                            need an imt. */
8776                                         if (!cmethod_context || !cmethod_context->method_inst)
8777                                                 pass_imt_from_rgctx = TRUE;
8778                                 }
8779
8780                                 /*
8781                                  * If a shared method calls another
8782                                  * shared method then the caller must
8783                                  * have a generic sharing context
8784                                  * because the magic trampoline
8785                                  * requires it.  FIXME: We shouldn't
8786                                  * have to force the vtable/mrgctx
8787                                  * variable here.  Instead there
8788                                  * should be a flag in the cfg to
8789                                  * request a generic sharing context.
8790                                  */
8791                                 if (context_used &&
8792                                                 ((cfg->method->flags & METHOD_ATTRIBUTE_STATIC) || cfg->method->klass->valuetype))
8793                                         mono_get_vtable_var (cfg);
8794                         }
8795
8796                         if (pass_vtable) {
8797                                 if (context_used) {
8798                                         vtable_arg = mini_emit_get_rgctx_klass (cfg, context_used, cmethod->klass, MONO_RGCTX_INFO_VTABLE);
8799                                 } else {
8800                                         MonoVTable *vtable = mono_class_vtable (cfg->domain, cmethod->klass);
8801
8802                                         CHECK_TYPELOAD (cmethod->klass);
8803                                         EMIT_NEW_VTABLECONST (cfg, vtable_arg, vtable);
8804                                 }
8805                         }
8806
8807                         if (pass_mrgctx) {
8808                                 g_assert (!vtable_arg);
8809
8810                                 if (!cfg->compile_aot) {
8811                                         /* 
8812                                          * emit_get_rgctx_method () calls mono_class_vtable () so check 
8813                                          * for type load errors before.
8814                                          */
8815                                         mono_class_setup_vtable (cmethod->klass);
8816                                         CHECK_TYPELOAD (cmethod->klass);
8817                                 }
8818
8819                                 vtable_arg = emit_get_rgctx_method (cfg, context_used, cmethod, MONO_RGCTX_INFO_METHOD_RGCTX);
8820
8821                                 /* !marshalbyref is needed to properly handle generic methods + remoting */
8822                                 if ((!(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) ||
8823                                          MONO_METHOD_IS_FINAL (cmethod)) &&
8824                                         !mono_class_is_marshalbyref (cmethod->klass)) {
8825                                         if (virtual_)
8826                                                 check_this = TRUE;
8827                                         virtual_ = 0;
8828                                 }
8829                         }
8830
8831                         if (pass_imt_from_rgctx) {
8832                                 g_assert (!pass_vtable);
8833
8834                                 imt_arg = emit_get_rgctx_method (cfg, context_used,
8835                                         cmethod, MONO_RGCTX_INFO_METHOD);
8836                         }
8837
8838                         if (check_this)
8839                                 MONO_EMIT_NEW_CHECK_THIS (cfg, sp [0]->dreg);
8840
8841                         /* Calling virtual generic methods */
8842                         if (virtual_ && (cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) &&
8843                             !(MONO_METHOD_IS_FINAL (cmethod) && 
8844                               cmethod->wrapper_type != MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK) &&
8845                             fsig->generic_param_count && 
8846                                 !(cfg->gsharedvt && mini_is_gsharedvt_signature (fsig)) &&
8847                                 !cfg->llvm_only) {
8848                                 MonoInst *this_temp, *this_arg_temp, *store;
8849                                 MonoInst *iargs [4];
8850
8851                                 g_assert (fsig->is_inflated);
8852
8853                                 /* Prevent inlining of methods that contain indirect calls */
8854                                 INLINE_FAILURE ("virtual generic call");
8855
8856                                 if (cfg->gsharedvt && mini_is_gsharedvt_signature (fsig))
8857                                         GSHAREDVT_FAILURE (*ip);
8858
8859                                 if (cfg->backend->have_generalized_imt_trampoline && cfg->backend->gshared_supported && cmethod->wrapper_type == MONO_WRAPPER_NONE) {
8860                                         g_assert (!imt_arg);
8861                                         if (!context_used)
8862                                                 g_assert (cmethod->is_inflated);
8863                                         imt_arg = emit_get_rgctx_method (cfg, context_used,
8864                                                                                                          cmethod, MONO_RGCTX_INFO_METHOD);
8865                                         ins = mono_emit_method_call_full (cfg, cmethod, fsig, FALSE, sp, sp [0], imt_arg, NULL);
8866                                 } else {
8867                                         this_temp = mono_compile_create_var (cfg, type_from_stack_type (sp [0]), OP_LOCAL);
8868                                         NEW_TEMPSTORE (cfg, store, this_temp->inst_c0, sp [0]);
8869                                         MONO_ADD_INS (cfg->cbb, store);
8870
8871                                         /* FIXME: This should be a managed pointer */
8872                                         this_arg_temp = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
8873
8874                                         EMIT_NEW_TEMPLOAD (cfg, iargs [0], this_temp->inst_c0);
8875                                         iargs [1] = emit_get_rgctx_method (cfg, context_used,
8876                                                                                                            cmethod, MONO_RGCTX_INFO_METHOD);
8877                                         EMIT_NEW_TEMPLOADA (cfg, iargs [2], this_arg_temp->inst_c0);
8878                                         addr = mono_emit_jit_icall (cfg,
8879                                                                                                 mono_helper_compile_generic_method, iargs);
8880
8881                                         EMIT_NEW_TEMPLOAD (cfg, sp [0], this_arg_temp->inst_c0);
8882
8883                                         ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
8884                                 }
8885
8886                                 goto call_end;
8887                         }
8888
8889                         /*
8890                          * Implement a workaround for the inherent races involved in locking:
8891                          * Monitor.Enter ()
8892                          * try {
8893                          * } finally {
8894                          *    Monitor.Exit ()
8895                          * }
8896                          * If a thread abort happens between the call to Monitor.Enter () and the start of the
8897                          * try block, the Exit () won't be executed, see:
8898                          * http://www.bluebytesoftware.com/blog/2007/01/30/MonitorEnterThreadAbortsAndOrphanedLocks.aspx
8899                          * To work around this, we extend such try blocks to include the last x bytes
8900                          * of the Monitor.Enter () call.
8901                          */
8902                         if (cmethod->klass == mono_defaults.monitor_class && !strcmp (cmethod->name, "Enter") && mono_method_signature (cmethod)->param_count == 1) {
8903                                 MonoBasicBlock *tbb;
8904
8905                                 GET_BBLOCK (cfg, tbb, ip + 5);
8906                                 /* 
8907                                  * Only extend try blocks with a finally, to avoid catching exceptions thrown
8908                                  * from Monitor.Enter like ArgumentNullException.
8909                                  */
8910                                 if (tbb->try_start && MONO_REGION_FLAGS(tbb->region) == MONO_EXCEPTION_CLAUSE_FINALLY) {
8911                                         /* Mark this bblock as needing to be extended */
8912                                         tbb->extend_try_block = TRUE;
8913                                 }
8914                         }
8915
8916                         /* Conversion to a JIT intrinsic */
8917                         if ((cfg->opt & MONO_OPT_INTRINS) && (ins = mini_emit_inst_for_method (cfg, cmethod, fsig, sp))) {
8918                                 if (!MONO_TYPE_IS_VOID (fsig->ret)) {
8919                                         type_to_eval_stack_type ((cfg), fsig->ret, ins);
8920                                         emit_widen = FALSE;
8921                                 }
8922                                 goto call_end;
8923                         }
8924                         CHECK_CFG_ERROR;
8925                         
8926                         /* Inlining */
8927                         if ((cfg->opt & MONO_OPT_INLINE) &&
8928                                 (!virtual_ || !(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) || MONO_METHOD_IS_FINAL (cmethod)) &&
8929                             mono_method_check_inlining (cfg, cmethod)) {
8930                                 int costs;
8931                                 gboolean always = FALSE;
8932
8933                                 if ((cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
8934                                         (cmethod->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
8935                                         /* Prevent inlining of methods that call wrappers */
8936                                         INLINE_FAILURE ("wrapper call");
8937                                         cmethod = mono_marshal_get_native_wrapper (cmethod, TRUE, FALSE);
8938                                         always = TRUE;
8939                                 }
8940
8941                                 costs = inline_method (cfg, cmethod, fsig, sp, ip, cfg->real_offset, always);
8942                                 if (costs) {
8943                                         cfg->real_offset += 5;
8944
8945                                         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
8946                                                 /* *sp is already set by inline_method */
8947                                                 sp++;
8948                                                 push_res = FALSE;
8949                                         }
8950
8951                                         inline_costs += costs;
8952
8953                                         goto call_end;
8954                                 }
8955                         }
8956
8957                         /* Tail recursion elimination */
8958                         if ((cfg->opt & MONO_OPT_TAILC) && call_opcode == CEE_CALL && cmethod == method && ip [5] == CEE_RET && !vtable_arg) {
8959                                 gboolean has_vtargs = FALSE;
8960                                 int i;
8961
8962                                 /* Prevent inlining of methods with tail calls (the call stack would be altered) */
8963                                 INLINE_FAILURE ("tail call");
8964
8965                                 /* keep it simple */
8966                                 for (i =  fsig->param_count - 1; i >= 0; i--) {
8967                                         if (MONO_TYPE_ISSTRUCT (mono_method_signature (cmethod)->params [i])) 
8968                                                 has_vtargs = TRUE;
8969                                 }
8970
8971                                 if (!has_vtargs) {
8972                                         if (need_seq_point) {
8973                                                 emit_seq_point (cfg, method, ip, FALSE, TRUE);
8974                                                 need_seq_point = FALSE;
8975                                         }
8976                                         for (i = 0; i < n; ++i)
8977                                                 EMIT_NEW_ARGSTORE (cfg, ins, i, sp [i]);
8978                                         MONO_INST_NEW (cfg, ins, OP_BR);
8979                                         MONO_ADD_INS (cfg->cbb, ins);
8980                                         tblock = start_bblock->out_bb [0];
8981                                         link_bblock (cfg, cfg->cbb, tblock);
8982                                         ins->inst_target_bb = tblock;
8983                                         start_new_bblock = 1;
8984
8985                                         /* skip the CEE_RET, too */
8986                                         if (ip_in_bb (cfg, cfg->cbb, ip + 5))
8987                                                 skip_ret = TRUE;
8988                                         push_res = FALSE;
8989                                         goto call_end;
8990                                 }
8991                         }
8992
8993                         inline_costs += 10 * num_calls++;
8994
8995                         /*
8996                          * Synchronized wrappers.
8997                          * Its hard to determine where to replace a method with its synchronized
8998                          * wrapper without causing an infinite recursion. The current solution is
8999                          * to add the synchronized wrapper in the trampolines, and to
9000                          * change the called method to a dummy wrapper, and resolve that wrapper
9001                          * to the real method in mono_jit_compile_method ().
9002                          */
9003                         if (cfg->method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED) {
9004                                 MonoMethod *orig = mono_marshal_method_from_wrapper (cfg->method);
9005                                 if (cmethod == orig || (cmethod->is_inflated && mono_method_get_declaring_generic_method (cmethod) == orig))
9006                                         cmethod = mono_marshal_get_synchronized_inner_wrapper (cmethod);
9007                         }
9008
9009                         /*
9010                          * Making generic calls out of gsharedvt methods.
9011                          * This needs to be used for all generic calls, not just ones with a gsharedvt signature, to avoid
9012                          * patching gshared method addresses into a gsharedvt method.
9013                          */
9014                         if (cfg->gsharedvt && (mini_is_gsharedvt_signature (fsig) || cmethod->is_inflated || mono_class_is_ginst (cmethod->klass)) &&
9015                                 !(cmethod->klass->rank && cmethod->klass->byval_arg.type != MONO_TYPE_SZARRAY) &&
9016                                 (!(cfg->llvm_only && virtual_ && (cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL)))) {
9017                                 MonoRgctxInfoType info_type;
9018
9019                                 if (virtual_) {
9020                                         //if (mono_class_is_interface (cmethod->klass))
9021                                                 //GSHAREDVT_FAILURE (*ip);
9022                                         // disable for possible remoting calls
9023                                         if (fsig->hasthis && (mono_class_is_marshalbyref (method->klass) || method->klass == mono_defaults.object_class))
9024                                                 GSHAREDVT_FAILURE (*ip);
9025                                         if (fsig->generic_param_count) {
9026                                                 /* virtual generic call */
9027                                                 g_assert (!imt_arg);
9028                                                 /* Same as the virtual generic case above */
9029                                                 imt_arg = emit_get_rgctx_method (cfg, context_used,
9030                                                                                                                  cmethod, MONO_RGCTX_INFO_METHOD);
9031                                                 /* This is not needed, as the trampoline code will pass one, and it might be passed in the same reg as the imt arg */
9032                                                 vtable_arg = NULL;
9033                                         } else if (mono_class_is_interface (cmethod->klass) && !imt_arg) {
9034                                                 /* This can happen when we call a fully instantiated iface method */
9035                                                 imt_arg = emit_get_rgctx_method (cfg, context_used,
9036                                                                                                                  cmethod, MONO_RGCTX_INFO_METHOD);
9037                                                 vtable_arg = NULL;
9038                                         }
9039                                 }
9040
9041                                 if ((cmethod->klass->parent == mono_defaults.multicastdelegate_class) && (!strcmp (cmethod->name, "Invoke")))
9042                                         keep_this_alive = sp [0];
9043
9044                                 if (virtual_ && (cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL))
9045                                         info_type = MONO_RGCTX_INFO_METHOD_GSHAREDVT_OUT_TRAMPOLINE_VIRT;
9046                                 else
9047                                         info_type = MONO_RGCTX_INFO_METHOD_GSHAREDVT_OUT_TRAMPOLINE;
9048                                 addr = emit_get_rgctx_gsharedvt_call (cfg, context_used, fsig, cmethod, info_type);
9049
9050                                 if (cfg->llvm_only) {
9051                                         // FIXME: Avoid initializing vtable_arg
9052                                         ins = emit_llvmonly_calli (cfg, fsig, sp, addr);
9053                                 } else {
9054                                         ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, imt_arg, vtable_arg);
9055                                 }
9056                                 goto call_end;
9057                         }
9058
9059                         /* Generic sharing */
9060
9061                         /*
9062                          * Use this if the callee is gsharedvt sharable too, since
9063                          * at runtime we might find an instantiation so the call cannot
9064                          * be patched (the 'no_patch' code path in mini-trampolines.c).
9065                          */
9066                         if (context_used && !imt_arg && !array_rank && !delegate_invoke &&
9067                                 (!mono_method_is_generic_sharable_full (cmethod, TRUE, FALSE, FALSE) ||
9068                                  !mono_class_generic_sharing_enabled (cmethod->klass)) &&
9069                                 (!virtual_ || MONO_METHOD_IS_FINAL (cmethod) ||
9070                                  !(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL))) {
9071                                 INLINE_FAILURE ("gshared");
9072
9073                                 g_assert (cfg->gshared && cmethod);
9074                                 g_assert (!addr);
9075
9076                                 /*
9077                                  * We are compiling a call to a
9078                                  * generic method from shared code,
9079                                  * which means that we have to look up
9080                                  * the method in the rgctx and do an
9081                                  * indirect call.
9082                                  */
9083                                 if (fsig->hasthis)
9084                                         MONO_EMIT_NEW_CHECK_THIS (cfg, sp [0]->dreg);
9085
9086                                 if (cfg->llvm_only) {
9087                                         if (cfg->gsharedvt && mini_is_gsharedvt_variable_signature (fsig))
9088                                                 addr = emit_get_rgctx_method (cfg, context_used, cmethod, MONO_RGCTX_INFO_GSHAREDVT_OUT_WRAPPER);
9089                                         else
9090                                                 addr = emit_get_rgctx_method (cfg, context_used, cmethod, MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
9091                                         // FIXME: Avoid initializing imt_arg/vtable_arg
9092                                         ins = emit_llvmonly_calli (cfg, fsig, sp, addr);
9093                                 } else {
9094                                         addr = emit_get_rgctx_method (cfg, context_used, cmethod, MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
9095                                         ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, imt_arg, vtable_arg);
9096                                 }
9097                                 goto call_end;
9098                         }
9099
9100                         /* Direct calls to icalls */
9101                         if (direct_icall) {
9102                                 MonoMethod *wrapper;
9103                                 int costs;
9104
9105                                 /* Inline the wrapper */
9106                                 wrapper = mono_marshal_get_native_wrapper (cmethod, TRUE, cfg->compile_aot);
9107
9108                                 costs = inline_method (cfg, wrapper, fsig, sp, ip, cfg->real_offset, TRUE);
9109                                 g_assert (costs > 0);
9110                                 cfg->real_offset += 5;
9111
9112                                 if (!MONO_TYPE_IS_VOID (fsig->ret)) {
9113                                         /* *sp is already set by inline_method */
9114                                         sp++;
9115                                         push_res = FALSE;
9116                                 }
9117
9118                                 inline_costs += costs;
9119
9120                                 goto call_end;
9121                         }
9122                                         
9123                         /* Array methods */
9124                         if (array_rank) {
9125                                 MonoInst *addr;
9126
9127                                 if (strcmp (cmethod->name, "Set") == 0) { /* array Set */ 
9128                                         MonoInst *val = sp [fsig->param_count];
9129
9130                                         if (val->type == STACK_OBJ) {
9131                                                 MonoInst *iargs [2];
9132
9133                                                 iargs [0] = sp [0];
9134                                                 iargs [1] = val;
9135                                                 
9136                                                 mono_emit_jit_icall (cfg, mono_helper_stelem_ref_check, iargs);
9137                                         }
9138                                         
9139                                         addr = mini_emit_ldelema_ins (cfg, cmethod, sp, ip, TRUE);
9140                                         EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, fsig->params [fsig->param_count - 1], addr->dreg, 0, val->dreg);
9141                                         if (cfg->gen_write_barriers && val->type == STACK_OBJ && !MONO_INS_IS_PCONST_NULL (val))
9142                                                 mini_emit_write_barrier (cfg, addr, val);
9143                                         if (cfg->gen_write_barriers && mini_is_gsharedvt_klass (cmethod->klass))
9144                                                 GSHAREDVT_FAILURE (*ip);
9145                                 } else if (strcmp (cmethod->name, "Get") == 0) { /* array Get */
9146                                         addr = mini_emit_ldelema_ins (cfg, cmethod, sp, ip, FALSE);
9147
9148                                         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, fsig->ret, addr->dreg, 0);
9149                                 } else if (strcmp (cmethod->name, "Address") == 0) { /* array Address */
9150                                         if (!cmethod->klass->element_class->valuetype && !readonly)
9151                                                 mini_emit_check_array_type (cfg, sp [0], cmethod->klass);
9152                                         CHECK_TYPELOAD (cmethod->klass);
9153                                         
9154                                         readonly = FALSE;
9155                                         addr = mini_emit_ldelema_ins (cfg, cmethod, sp, ip, FALSE);
9156                                         ins = addr;
9157                                 } else {
9158                                         g_assert_not_reached ();
9159                                 }
9160
9161                                 emit_widen = FALSE;
9162                                 goto call_end;
9163                         }
9164
9165                         ins = mini_redirect_call (cfg, cmethod, fsig, sp, virtual_ ? sp [0] : NULL);
9166                         if (ins)
9167                                 goto call_end;
9168
9169                         /* Tail prefix / tail call optimization */
9170
9171                         /* FIXME: Enabling TAILC breaks some inlining/stack trace/etc tests */
9172                         /* FIXME: runtime generic context pointer for jumps? */
9173                         /* FIXME: handle this for generic sharing eventually */
9174                         if ((ins_flag & MONO_INST_TAILCALL) &&
9175                                 !vtable_arg && !cfg->gshared && is_supported_tail_call (cfg, method, cmethod, fsig, call_opcode))
9176                                 supported_tail_call = TRUE;
9177
9178                         if (supported_tail_call) {
9179                                 MonoCallInst *call;
9180
9181                                 /* Prevent inlining of methods with tail calls (the call stack would be altered) */
9182                                 INLINE_FAILURE ("tail call");
9183
9184                                 //printf ("HIT: %s -> %s\n", mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
9185
9186                                 if (cfg->backend->have_op_tail_call) {
9187                                         /* Handle tail calls similarly to normal calls */
9188                                         tail_call = TRUE;
9189                                 } else {
9190                                         emit_instrumentation_call (cfg, mono_profiler_method_leave);
9191
9192                                         MONO_INST_NEW_CALL (cfg, call, OP_JMP);
9193                                         call->tail_call = TRUE;
9194                                         call->method = cmethod;
9195                                         call->signature = mono_method_signature (cmethod);
9196
9197                                         /*
9198                                          * We implement tail calls by storing the actual arguments into the 
9199                                          * argument variables, then emitting a CEE_JMP.
9200                                          */
9201                                         for (i = 0; i < n; ++i) {
9202                                                 /* Prevent argument from being register allocated */
9203                                                 arg_array [i]->flags |= MONO_INST_VOLATILE;
9204                                                 EMIT_NEW_ARGSTORE (cfg, ins, i, sp [i]);
9205                                         }
9206                                         ins = (MonoInst*)call;
9207                                         ins->inst_p0 = cmethod;
9208                                         ins->inst_p1 = arg_array [0];
9209                                         MONO_ADD_INS (cfg->cbb, ins);
9210                                         link_bblock (cfg, cfg->cbb, end_bblock);
9211                                         start_new_bblock = 1;
9212
9213                                         // FIXME: Eliminate unreachable epilogs
9214
9215                                         /*
9216                                          * OP_TAILCALL has no return value, so skip the CEE_RET if it is
9217                                          * only reachable from this call.
9218                                          */
9219                                         GET_BBLOCK (cfg, tblock, ip + 5);
9220                                         if (tblock == cfg->cbb || tblock->in_count == 0)
9221                                                 skip_ret = TRUE;
9222                                         push_res = FALSE;
9223
9224                                         goto call_end;
9225                                 }
9226                         }
9227
9228                         /*
9229                          * Virtual calls in llvm-only mode.
9230                          */
9231                         if (cfg->llvm_only && virtual_ && cmethod && (cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
9232                                 ins = emit_llvmonly_virtual_call (cfg, cmethod, fsig, context_used, sp);
9233                                 goto call_end;
9234                         }
9235
9236                         /* Common call */
9237                         if (!(cmethod->iflags & METHOD_IMPL_ATTRIBUTE_AGGRESSIVE_INLINING))
9238                                 INLINE_FAILURE ("call");
9239                         ins = mono_emit_method_call_full (cfg, cmethod, fsig, tail_call, sp, virtual_ ? sp [0] : NULL,
9240                                                                                           imt_arg, vtable_arg);
9241
9242                         if (tail_call && !cfg->llvm_only) {
9243                                 link_bblock (cfg, cfg->cbb, end_bblock);
9244                                 start_new_bblock = 1;
9245
9246                                 // FIXME: Eliminate unreachable epilogs
9247
9248                                 /*
9249                                  * OP_TAILCALL has no return value, so skip the CEE_RET if it is
9250                                  * only reachable from this call.
9251                                  */
9252                                 GET_BBLOCK (cfg, tblock, ip + 5);
9253                                 if (tblock == cfg->cbb || tblock->in_count == 0)
9254                                         skip_ret = TRUE;
9255                                 push_res = FALSE;
9256                         }
9257
9258                         call_end:
9259
9260                         /* End of call, INS should contain the result of the call, if any */
9261
9262                         if (push_res && !MONO_TYPE_IS_VOID (fsig->ret)) {
9263                                 g_assert (ins);
9264                                 if (emit_widen)
9265                                         *sp++ = mono_emit_widen_call_res (cfg, ins, fsig);
9266                                 else
9267                                         *sp++ = ins;
9268                         }
9269
9270                         if (keep_this_alive) {
9271                                 MonoInst *dummy_use;
9272
9273                                 /* See mono_emit_method_call_full () */
9274                                 EMIT_NEW_DUMMY_USE (cfg, dummy_use, keep_this_alive);
9275                         }
9276
9277                         if (cfg->llvm_only && cmethod && method_needs_stack_walk (cfg, cmethod)) {
9278                                 /*
9279                                  * Clang can convert these calls to tail calls which screw up the stack
9280                                  * walk. This happens even when the -fno-optimize-sibling-calls
9281                                  * option is passed to clang.
9282                                  * Work around this by emitting a dummy call.
9283                                  */
9284                                 mono_emit_jit_icall (cfg, mono_dummy_jit_icall, NULL);
9285                         }
9286
9287                         CHECK_CFG_EXCEPTION;
9288
9289                         ip += 5;
9290                         if (skip_ret) {
9291                                 g_assert (*ip == CEE_RET);
9292                                 ip += 1;
9293                         }
9294                         ins_flag = 0;
9295                         constrained_class = NULL;
9296                         if (need_seq_point)
9297                                 emit_seq_point (cfg, method, ip, FALSE, TRUE);
9298                         break;
9299                 }
9300                 case CEE_RET:
9301                         if (cfg->method != method) {
9302                                 /* return from inlined method */
9303                                 /* 
9304                                  * If in_count == 0, that means the ret is unreachable due to
9305                                  * being preceeded by a throw. In that case, inline_method () will
9306                                  * handle setting the return value 
9307                                  * (test case: test_0_inline_throw ()).
9308                                  */
9309                                 if (return_var && cfg->cbb->in_count) {
9310                                         MonoType *ret_type = mono_method_signature (method)->ret;
9311
9312                                         MonoInst *store;
9313                                         CHECK_STACK (1);
9314                                         --sp;
9315
9316                                         if ((method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD || method->wrapper_type == MONO_WRAPPER_NONE) && target_type_is_incompatible (cfg, ret_type, *sp))
9317                                                 UNVERIFIED;
9318
9319                                         //g_assert (returnvar != -1);
9320                                         EMIT_NEW_TEMPSTORE (cfg, store, return_var->inst_c0, *sp);
9321                                         cfg->ret_var_set = TRUE;
9322                                 } 
9323                         } else {
9324                                 emit_instrumentation_call (cfg, mono_profiler_method_leave);
9325
9326                                 if (cfg->lmf_var && cfg->cbb->in_count && !cfg->llvm_only)
9327                                         emit_pop_lmf (cfg);
9328
9329                                 if (cfg->ret) {
9330                                         MonoType *ret_type = mini_get_underlying_type (mono_method_signature (method)->ret);
9331
9332                                         if (seq_points && !sym_seq_points) {
9333                                                 /* 
9334                                                  * Place a seq point here too even through the IL stack is not
9335                                                  * empty, so a step over on
9336                                                  * call <FOO>
9337                                                  * ret
9338                                                  * will work correctly.
9339                                                  */
9340                                                 NEW_SEQ_POINT (cfg, ins, ip - header->code, TRUE);
9341                                                 MONO_ADD_INS (cfg->cbb, ins);
9342                                         }
9343
9344                                         g_assert (!return_var);
9345                                         CHECK_STACK (1);
9346                                         --sp;
9347
9348                                         if ((method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD || method->wrapper_type == MONO_WRAPPER_NONE) && target_type_is_incompatible (cfg, ret_type, *sp))
9349                                                 UNVERIFIED;
9350
9351                                         emit_setret (cfg, *sp);
9352                                 }
9353                         }
9354                         if (sp != stack_start)
9355                                 UNVERIFIED;
9356                         MONO_INST_NEW (cfg, ins, OP_BR);
9357                         ip++;
9358                         ins->inst_target_bb = end_bblock;
9359                         MONO_ADD_INS (cfg->cbb, ins);
9360                         link_bblock (cfg, cfg->cbb, end_bblock);
9361                         start_new_bblock = 1;
9362                         break;
9363                 case CEE_BR_S:
9364                         CHECK_OPSIZE (2);
9365                         MONO_INST_NEW (cfg, ins, OP_BR);
9366                         ip++;
9367                         target = ip + 1 + (signed char)(*ip);
9368                         ++ip;
9369                         GET_BBLOCK (cfg, tblock, target);
9370                         link_bblock (cfg, cfg->cbb, tblock);
9371                         ins->inst_target_bb = tblock;
9372                         if (sp != stack_start) {
9373                                 handle_stack_args (cfg, stack_start, sp - stack_start);
9374                                 sp = stack_start;
9375                                 CHECK_UNVERIFIABLE (cfg);
9376                         }
9377                         MONO_ADD_INS (cfg->cbb, ins);
9378                         start_new_bblock = 1;
9379                         inline_costs += BRANCH_COST;
9380                         break;
9381                 case CEE_BEQ_S:
9382                 case CEE_BGE_S:
9383                 case CEE_BGT_S:
9384                 case CEE_BLE_S:
9385                 case CEE_BLT_S:
9386                 case CEE_BNE_UN_S:
9387                 case CEE_BGE_UN_S:
9388                 case CEE_BGT_UN_S:
9389                 case CEE_BLE_UN_S:
9390                 case CEE_BLT_UN_S:
9391                         CHECK_OPSIZE (2);
9392                         CHECK_STACK (2);
9393                         MONO_INST_NEW (cfg, ins, *ip + BIG_BRANCH_OFFSET);
9394                         ip++;
9395                         target = ip + 1 + *(signed char*)ip;
9396                         ip++;
9397
9398                         ADD_BINCOND (NULL);
9399
9400                         sp = stack_start;
9401                         inline_costs += BRANCH_COST;
9402                         break;
9403                 case CEE_BR:
9404                         CHECK_OPSIZE (5);
9405                         MONO_INST_NEW (cfg, ins, OP_BR);
9406                         ip++;
9407
9408                         target = ip + 4 + (gint32)read32(ip);
9409                         ip += 4;
9410                         GET_BBLOCK (cfg, tblock, target);
9411                         link_bblock (cfg, cfg->cbb, tblock);
9412                         ins->inst_target_bb = tblock;
9413                         if (sp != stack_start) {
9414                                 handle_stack_args (cfg, stack_start, sp - stack_start);
9415                                 sp = stack_start;
9416                                 CHECK_UNVERIFIABLE (cfg);
9417                         }
9418
9419                         MONO_ADD_INS (cfg->cbb, ins);
9420
9421                         start_new_bblock = 1;
9422                         inline_costs += BRANCH_COST;
9423                         break;
9424                 case CEE_BRFALSE_S:
9425                 case CEE_BRTRUE_S:
9426                 case CEE_BRFALSE:
9427                 case CEE_BRTRUE: {
9428                         MonoInst *cmp;
9429                         gboolean is_short = ((*ip) == CEE_BRFALSE_S) || ((*ip) == CEE_BRTRUE_S);
9430                         gboolean is_true = ((*ip) == CEE_BRTRUE_S) || ((*ip) == CEE_BRTRUE);
9431                         guint32 opsize = is_short ? 1 : 4;
9432
9433                         CHECK_OPSIZE (opsize);
9434                         CHECK_STACK (1);
9435                         if (sp [-1]->type == STACK_VTYPE || sp [-1]->type == STACK_R8)
9436                                 UNVERIFIED;
9437                         ip ++;
9438                         target = ip + opsize + (is_short ? *(signed char*)ip : (gint32)read32(ip));
9439                         ip += opsize;
9440
9441                         sp--;
9442
9443                         GET_BBLOCK (cfg, tblock, target);
9444                         link_bblock (cfg, cfg->cbb, tblock);
9445                         GET_BBLOCK (cfg, tblock, ip);
9446                         link_bblock (cfg, cfg->cbb, tblock);
9447
9448                         if (sp != stack_start) {
9449                                 handle_stack_args (cfg, stack_start, sp - stack_start);
9450                                 CHECK_UNVERIFIABLE (cfg);
9451                         }
9452
9453                         MONO_INST_NEW(cfg, cmp, OP_ICOMPARE_IMM);
9454                         cmp->sreg1 = sp [0]->dreg;
9455                         type_from_op (cfg, cmp, sp [0], NULL);
9456                         CHECK_TYPE (cmp);
9457
9458 #if SIZEOF_REGISTER == 4
9459                         if (cmp->opcode == OP_LCOMPARE_IMM) {
9460                                 /* Convert it to OP_LCOMPARE */
9461                                 MONO_INST_NEW (cfg, ins, OP_I8CONST);
9462                                 ins->type = STACK_I8;
9463                                 ins->dreg = alloc_dreg (cfg, STACK_I8);
9464                                 ins->inst_l = 0;
9465                                 MONO_ADD_INS (cfg->cbb, ins);
9466                                 cmp->opcode = OP_LCOMPARE;
9467                                 cmp->sreg2 = ins->dreg;
9468                         }
9469 #endif
9470                         MONO_ADD_INS (cfg->cbb, cmp);
9471
9472                         MONO_INST_NEW (cfg, ins, is_true ? CEE_BNE_UN : CEE_BEQ);
9473                         type_from_op (cfg, ins, sp [0], NULL);
9474                         MONO_ADD_INS (cfg->cbb, ins);
9475                         ins->inst_many_bb = (MonoBasicBlock **)mono_mempool_alloc (cfg->mempool, sizeof(gpointer)*2);
9476                         GET_BBLOCK (cfg, tblock, target);
9477                         ins->inst_true_bb = tblock;
9478                         GET_BBLOCK (cfg, tblock, ip);
9479                         ins->inst_false_bb = tblock;
9480                         start_new_bblock = 2;
9481
9482                         sp = stack_start;
9483                         inline_costs += BRANCH_COST;
9484                         break;
9485                 }
9486                 case CEE_BEQ:
9487                 case CEE_BGE:
9488                 case CEE_BGT:
9489                 case CEE_BLE:
9490                 case CEE_BLT:
9491                 case CEE_BNE_UN:
9492                 case CEE_BGE_UN:
9493                 case CEE_BGT_UN:
9494                 case CEE_BLE_UN:
9495                 case CEE_BLT_UN:
9496                         CHECK_OPSIZE (5);
9497                         CHECK_STACK (2);
9498                         MONO_INST_NEW (cfg, ins, *ip);
9499                         ip++;
9500                         target = ip + 4 + (gint32)read32(ip);
9501                         ip += 4;
9502
9503                         ADD_BINCOND (NULL);
9504
9505                         sp = stack_start;
9506                         inline_costs += BRANCH_COST;
9507                         break;
9508                 case CEE_SWITCH: {
9509                         MonoInst *src1;
9510                         MonoBasicBlock **targets;
9511                         MonoBasicBlock *default_bblock;
9512                         MonoJumpInfoBBTable *table;
9513                         int offset_reg = alloc_preg (cfg);
9514                         int target_reg = alloc_preg (cfg);
9515                         int table_reg = alloc_preg (cfg);
9516                         int sum_reg = alloc_preg (cfg);
9517                         gboolean use_op_switch;
9518
9519                         CHECK_OPSIZE (5);
9520                         CHECK_STACK (1);
9521                         n = read32 (ip + 1);
9522                         --sp;
9523                         src1 = sp [0];
9524                         if ((src1->type != STACK_I4) && (src1->type != STACK_PTR)) 
9525                                 UNVERIFIED;
9526
9527                         ip += 5;
9528                         CHECK_OPSIZE (n * sizeof (guint32));
9529                         target = ip + n * sizeof (guint32);
9530
9531                         GET_BBLOCK (cfg, default_bblock, target);
9532                         default_bblock->flags |= BB_INDIRECT_JUMP_TARGET;
9533
9534                         targets = (MonoBasicBlock **)mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * n);
9535                         for (i = 0; i < n; ++i) {
9536                                 GET_BBLOCK (cfg, tblock, target + (gint32)read32(ip));
9537                                 targets [i] = tblock;
9538                                 targets [i]->flags |= BB_INDIRECT_JUMP_TARGET;
9539                                 ip += 4;
9540                         }
9541
9542                         if (sp != stack_start) {
9543                                 /* 
9544                                  * Link the current bb with the targets as well, so handle_stack_args
9545                                  * will set their in_stack correctly.
9546                                  */
9547                                 link_bblock (cfg, cfg->cbb, default_bblock);
9548                                 for (i = 0; i < n; ++i)
9549                                         link_bblock (cfg, cfg->cbb, targets [i]);
9550
9551                                 handle_stack_args (cfg, stack_start, sp - stack_start);
9552                                 sp = stack_start;
9553                                 CHECK_UNVERIFIABLE (cfg);
9554
9555                                 /* Undo the links */
9556                                 mono_unlink_bblock (cfg, cfg->cbb, default_bblock);
9557                                 for (i = 0; i < n; ++i)
9558                                         mono_unlink_bblock (cfg, cfg->cbb, targets [i]);
9559                         }
9560
9561                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ICOMPARE_IMM, -1, src1->dreg, n);
9562                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBGE_UN, default_bblock);
9563
9564                         for (i = 0; i < n; ++i)
9565                                 link_bblock (cfg, cfg->cbb, targets [i]);
9566
9567                         table = (MonoJumpInfoBBTable *)mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfoBBTable));
9568                         table->table = targets;
9569                         table->table_size = n;
9570
9571                         use_op_switch = FALSE;
9572 #ifdef TARGET_ARM
9573                         /* ARM implements SWITCH statements differently */
9574                         /* FIXME: Make it use the generic implementation */
9575                         if (!cfg->compile_aot)
9576                                 use_op_switch = TRUE;
9577 #endif
9578
9579                         if (COMPILE_LLVM (cfg))
9580                                 use_op_switch = TRUE;
9581
9582                         cfg->cbb->has_jump_table = 1;
9583
9584                         if (use_op_switch) {
9585                                 MONO_INST_NEW (cfg, ins, OP_SWITCH);
9586                                 ins->sreg1 = src1->dreg;
9587                                 ins->inst_p0 = table;
9588                                 ins->inst_many_bb = targets;
9589                                 ins->klass = (MonoClass *)GUINT_TO_POINTER (n);
9590                                 MONO_ADD_INS (cfg->cbb, ins);
9591                         } else {
9592                                 if (sizeof (gpointer) == 8)
9593                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHL_IMM, offset_reg, src1->dreg, 3);
9594                                 else
9595                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHL_IMM, offset_reg, src1->dreg, 2);
9596
9597 #if SIZEOF_REGISTER == 8
9598                                 /* The upper word might not be zero, and we add it to a 64 bit address later */
9599                                 MONO_EMIT_NEW_UNALU (cfg, OP_ZEXT_I4, offset_reg, offset_reg);
9600 #endif
9601
9602                                 if (cfg->compile_aot) {
9603                                         MONO_EMIT_NEW_AOTCONST (cfg, table_reg, table, MONO_PATCH_INFO_SWITCH);
9604                                 } else {
9605                                         MONO_INST_NEW (cfg, ins, OP_JUMP_TABLE);
9606                                         ins->inst_c1 = MONO_PATCH_INFO_SWITCH;
9607                                         ins->inst_p0 = table;
9608                                         ins->dreg = table_reg;
9609                                         MONO_ADD_INS (cfg->cbb, ins);
9610                                 }
9611
9612                                 /* FIXME: Use load_memindex */
9613                                 MONO_EMIT_NEW_BIALU (cfg, OP_PADD, sum_reg, table_reg, offset_reg);
9614                                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, target_reg, sum_reg, 0);
9615                                 MONO_EMIT_NEW_UNALU (cfg, OP_BR_REG, -1, target_reg);
9616                         }
9617                         start_new_bblock = 1;
9618                         inline_costs += (BRANCH_COST * 2);
9619                         break;
9620                 }
9621                 case CEE_LDIND_I1:
9622                 case CEE_LDIND_U1:
9623                 case CEE_LDIND_I2:
9624                 case CEE_LDIND_U2:
9625                 case CEE_LDIND_I4:
9626                 case CEE_LDIND_U4:
9627                 case CEE_LDIND_I8:
9628                 case CEE_LDIND_I:
9629                 case CEE_LDIND_R4:
9630                 case CEE_LDIND_R8:
9631                 case CEE_LDIND_REF:
9632                         CHECK_STACK (1);
9633                         --sp;
9634
9635                         ins = mini_emit_memory_load (cfg, &ldind_to_type (*ip)->byval_arg, sp [0], 0, ins_flag);
9636                         *sp++ = ins;
9637                         ins_flag = 0;
9638                         ++ip;
9639                         break;
9640                 case CEE_STIND_REF:
9641                 case CEE_STIND_I1:
9642                 case CEE_STIND_I2:
9643                 case CEE_STIND_I4:
9644                 case CEE_STIND_I8:
9645                 case CEE_STIND_R4:
9646                 case CEE_STIND_R8:
9647                 case CEE_STIND_I:
9648                         CHECK_STACK (2);
9649                         sp -= 2;
9650
9651                         if (ins_flag & MONO_INST_VOLATILE) {
9652                                 /* Volatile stores have release semantics, see 12.6.7 in Ecma 335 */
9653                                 mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_REL);
9654                         }
9655
9656                         NEW_STORE_MEMBASE (cfg, ins, stind_to_store_membase (*ip), sp [0]->dreg, 0, sp [1]->dreg);
9657                         ins->flags |= ins_flag;
9658                         ins_flag = 0;
9659
9660                         MONO_ADD_INS (cfg->cbb, ins);
9661
9662                         if (cfg->gen_write_barriers && *ip == CEE_STIND_REF && method->wrapper_type != MONO_WRAPPER_WRITE_BARRIER && !MONO_INS_IS_PCONST_NULL (sp [1]))
9663                                 mini_emit_write_barrier (cfg, sp [0], sp [1]);
9664
9665                         inline_costs += 1;
9666                         ++ip;
9667                         break;
9668
9669                 case CEE_MUL:
9670                         CHECK_STACK (2);
9671
9672                         MONO_INST_NEW (cfg, ins, (*ip));
9673                         sp -= 2;
9674                         ins->sreg1 = sp [0]->dreg;
9675                         ins->sreg2 = sp [1]->dreg;
9676                         type_from_op (cfg, ins, sp [0], sp [1]);
9677                         CHECK_TYPE (ins);
9678                         ins->dreg = alloc_dreg ((cfg), (MonoStackType)(ins)->type);
9679
9680                         /* Use the immediate opcodes if possible */
9681                         if ((sp [1]->opcode == OP_ICONST) && mono_arch_is_inst_imm (sp [1]->inst_c0)) {
9682                                 int imm_opcode = mono_op_to_op_imm_noemul (ins->opcode);
9683                                 if (imm_opcode != -1) {
9684                                         ins->opcode = imm_opcode;
9685                                         ins->inst_p1 = (gpointer)(gssize)(sp [1]->inst_c0);
9686                                         ins->sreg2 = -1;
9687
9688                                         NULLIFY_INS (sp [1]);
9689                                 }
9690                         }
9691
9692                         MONO_ADD_INS ((cfg)->cbb, (ins));
9693
9694                         *sp++ = mono_decompose_opcode (cfg, ins);
9695                         ip++;
9696                         break;
9697                 case CEE_ADD:
9698                 case CEE_SUB:
9699                 case CEE_DIV:
9700                 case CEE_DIV_UN:
9701                 case CEE_REM:
9702                 case CEE_REM_UN:
9703                 case CEE_AND:
9704                 case CEE_OR:
9705                 case CEE_XOR:
9706                 case CEE_SHL:
9707                 case CEE_SHR:
9708                 case CEE_SHR_UN:
9709                         CHECK_STACK (2);
9710
9711                         MONO_INST_NEW (cfg, ins, (*ip));
9712                         sp -= 2;
9713                         ins->sreg1 = sp [0]->dreg;
9714                         ins->sreg2 = sp [1]->dreg;
9715                         type_from_op (cfg, ins, sp [0], sp [1]);
9716                         CHECK_TYPE (ins);
9717                         add_widen_op (cfg, ins, &sp [0], &sp [1]);
9718                         ins->dreg = alloc_dreg ((cfg), (MonoStackType)(ins)->type);
9719
9720                         /* FIXME: Pass opcode to is_inst_imm */
9721
9722                         /* Use the immediate opcodes if possible */
9723                         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)) {
9724                                 int imm_opcode = mono_op_to_op_imm_noemul (ins->opcode);
9725                                 if (imm_opcode != -1) {
9726                                         ins->opcode = imm_opcode;
9727                                         if (sp [1]->opcode == OP_I8CONST) {
9728 #if SIZEOF_REGISTER == 8
9729                                                 ins->inst_imm = sp [1]->inst_l;
9730 #else
9731                                                 ins->inst_ls_word = sp [1]->inst_ls_word;
9732                                                 ins->inst_ms_word = sp [1]->inst_ms_word;
9733 #endif
9734                                         }
9735                                         else
9736                                                 ins->inst_imm = (gssize)(sp [1]->inst_c0);
9737                                         ins->sreg2 = -1;
9738
9739                                         /* Might be followed by an instruction added by add_widen_op */
9740                                         if (sp [1]->next == NULL)
9741                                                 NULLIFY_INS (sp [1]);
9742                                 }
9743                         }
9744                         MONO_ADD_INS ((cfg)->cbb, (ins));
9745
9746                         *sp++ = mono_decompose_opcode (cfg, ins);
9747                         ip++;
9748                         break;
9749                 case CEE_NEG:
9750                 case CEE_NOT:
9751                 case CEE_CONV_I1:
9752                 case CEE_CONV_I2:
9753                 case CEE_CONV_I4:
9754                 case CEE_CONV_R4:
9755                 case CEE_CONV_R8:
9756                 case CEE_CONV_U4:
9757                 case CEE_CONV_I8:
9758                 case CEE_CONV_U8:
9759                 case CEE_CONV_OVF_I8:
9760                 case CEE_CONV_OVF_U8:
9761                 case CEE_CONV_R_UN:
9762                         CHECK_STACK (1);
9763
9764                         /* Special case this earlier so we have long constants in the IR */
9765                         if ((((*ip) == CEE_CONV_I8) || ((*ip) == CEE_CONV_U8)) && (sp [-1]->opcode == OP_ICONST)) {
9766                                 int data = sp [-1]->inst_c0;
9767                                 sp [-1]->opcode = OP_I8CONST;
9768                                 sp [-1]->type = STACK_I8;
9769 #if SIZEOF_REGISTER == 8
9770                                 if ((*ip) == CEE_CONV_U8)
9771                                         sp [-1]->inst_c0 = (guint32)data;
9772                                 else
9773                                         sp [-1]->inst_c0 = data;
9774 #else
9775                                 sp [-1]->inst_ls_word = data;
9776                                 if ((*ip) == CEE_CONV_U8)
9777                                         sp [-1]->inst_ms_word = 0;
9778                                 else
9779                                         sp [-1]->inst_ms_word = (data < 0) ? -1 : 0;
9780 #endif
9781                                 sp [-1]->dreg = alloc_dreg (cfg, STACK_I8);
9782                         }
9783                         else {
9784                                 ADD_UNOP (*ip);
9785                         }
9786                         ip++;
9787                         break;
9788                 case CEE_CONV_OVF_I4:
9789                 case CEE_CONV_OVF_I1:
9790                 case CEE_CONV_OVF_I2:
9791                 case CEE_CONV_OVF_I:
9792                 case CEE_CONV_OVF_U:
9793                         CHECK_STACK (1);
9794
9795                         if (sp [-1]->type == STACK_R8 || sp [-1]->type == STACK_R4) {
9796                                 ADD_UNOP (CEE_CONV_OVF_I8);
9797                                 ADD_UNOP (*ip);
9798                         } else {
9799                                 ADD_UNOP (*ip);
9800                         }
9801                         ip++;
9802                         break;
9803                 case CEE_CONV_OVF_U1:
9804                 case CEE_CONV_OVF_U2:
9805                 case CEE_CONV_OVF_U4:
9806                         CHECK_STACK (1);
9807
9808                         if (sp [-1]->type == STACK_R8 || sp [-1]->type == STACK_R4) {
9809                                 ADD_UNOP (CEE_CONV_OVF_U8);
9810                                 ADD_UNOP (*ip);
9811                         } else {
9812                                 ADD_UNOP (*ip);
9813                         }
9814                         ip++;
9815                         break;
9816                 case CEE_CONV_OVF_I1_UN:
9817                 case CEE_CONV_OVF_I2_UN:
9818                 case CEE_CONV_OVF_I4_UN:
9819                 case CEE_CONV_OVF_I8_UN:
9820                 case CEE_CONV_OVF_U1_UN:
9821                 case CEE_CONV_OVF_U2_UN:
9822                 case CEE_CONV_OVF_U4_UN:
9823                 case CEE_CONV_OVF_U8_UN:
9824                 case CEE_CONV_OVF_I_UN:
9825                 case CEE_CONV_OVF_U_UN:
9826                 case CEE_CONV_U2:
9827                 case CEE_CONV_U1:
9828                 case CEE_CONV_I:
9829                 case CEE_CONV_U:
9830                         CHECK_STACK (1);
9831                         ADD_UNOP (*ip);
9832                         CHECK_CFG_EXCEPTION;
9833                         ip++;
9834                         break;
9835                 case CEE_ADD_OVF:
9836                 case CEE_ADD_OVF_UN:
9837                 case CEE_MUL_OVF:
9838                 case CEE_MUL_OVF_UN:
9839                 case CEE_SUB_OVF:
9840                 case CEE_SUB_OVF_UN:
9841                         CHECK_STACK (2);
9842                         ADD_BINOP (*ip);
9843                         ip++;
9844                         break;
9845                 case CEE_CPOBJ:
9846                         GSHAREDVT_FAILURE (*ip);
9847                         CHECK_OPSIZE (5);
9848                         CHECK_STACK (2);
9849                         token = read32 (ip + 1);
9850                         klass = mini_get_class (method, token, generic_context);
9851                         CHECK_TYPELOAD (klass);
9852                         sp -= 2;
9853                         if (generic_class_is_reference_type (cfg, klass)) {
9854                                 MonoInst *store, *load;
9855                                 int dreg = alloc_ireg_ref (cfg);
9856
9857                                 NEW_LOAD_MEMBASE (cfg, load, OP_LOAD_MEMBASE, dreg, sp [1]->dreg, 0);
9858                                 load->flags |= ins_flag;
9859                                 MONO_ADD_INS (cfg->cbb, load);
9860
9861                                 NEW_STORE_MEMBASE (cfg, store, OP_STORE_MEMBASE_REG, sp [0]->dreg, 0, dreg);
9862                                 store->flags |= ins_flag;
9863                                 MONO_ADD_INS (cfg->cbb, store);
9864
9865                                 if (cfg->gen_write_barriers && cfg->method->wrapper_type != MONO_WRAPPER_WRITE_BARRIER)
9866                                         mini_emit_write_barrier (cfg, sp [0], sp [1]);
9867                         } else {
9868                                 mini_emit_stobj (cfg, sp [0], sp [1], klass, FALSE);
9869                         }
9870                         ins_flag = 0;
9871                         ip += 5;
9872                         break;
9873                 case CEE_LDOBJ: {
9874                         int loc_index = -1;
9875                         int stloc_len = 0;
9876
9877                         CHECK_OPSIZE (5);
9878                         CHECK_STACK (1);
9879                         --sp;
9880                         token = read32 (ip + 1);
9881                         klass = mini_get_class (method, token, generic_context);
9882                         CHECK_TYPELOAD (klass);
9883
9884                         /* Optimize the common ldobj+stloc combination */
9885                         switch (ip [5]) {
9886                         case CEE_STLOC_S:
9887                                 loc_index = ip [6];
9888                                 stloc_len = 2;
9889                                 break;
9890                         case CEE_STLOC_0:
9891                         case CEE_STLOC_1:
9892                         case CEE_STLOC_2:
9893                         case CEE_STLOC_3:
9894                                 loc_index = ip [5] - CEE_STLOC_0;
9895                                 stloc_len = 1;
9896                                 break;
9897                         default:
9898                                 break;
9899                         }
9900
9901                         if ((loc_index != -1) && ip_in_bb (cfg, cfg->cbb, ip + 5)) {
9902                                 CHECK_LOCAL (loc_index);
9903
9904                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, sp [0]->dreg, 0);
9905                                 ins->dreg = cfg->locals [loc_index]->dreg;
9906                                 ins->flags |= ins_flag;
9907                                 ip += 5;
9908                                 ip += stloc_len;
9909                                 if (ins_flag & MONO_INST_VOLATILE) {
9910                                         /* Volatile loads have acquire semantics, see 12.6.7 in Ecma 335 */
9911                                         mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_ACQ);
9912                                 }
9913                                 ins_flag = 0;
9914                                 break;
9915                         }
9916
9917                         /* Optimize the ldobj+stobj combination */
9918                         /* The reference case ends up being a load+store anyway */
9919                         /* Skip this if the operation is volatile. */
9920                         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)) {
9921                                 CHECK_STACK (1);
9922
9923                                 sp --;
9924
9925                                 mini_emit_stobj (cfg, sp [0], sp [1], klass, FALSE);
9926
9927                                 ip += 5 + 5;
9928                                 ins_flag = 0;
9929                                 break;
9930                         }
9931
9932                         ins = mini_emit_memory_load (cfg, &klass->byval_arg, sp [0], 0, ins_flag);
9933                         *sp++ = ins;
9934
9935                         ip += 5;
9936                         ins_flag = 0;
9937                         inline_costs += 1;
9938                         break;
9939                 }
9940                 case CEE_LDSTR:
9941                         CHECK_STACK_OVF (1);
9942                         CHECK_OPSIZE (5);
9943                         n = read32 (ip + 1);
9944
9945                         if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
9946                                 EMIT_NEW_PCONST (cfg, ins, mono_method_get_wrapper_data (method, n));
9947                                 ins->type = STACK_OBJ;
9948                                 *sp = ins;
9949                         }
9950                         else if (method->wrapper_type != MONO_WRAPPER_NONE) {
9951                                 MonoInst *iargs [1];
9952                                 char *str = (char *)mono_method_get_wrapper_data (method, n);
9953
9954                                 if (cfg->compile_aot)
9955                                         EMIT_NEW_LDSTRLITCONST (cfg, iargs [0], str);
9956                                 else
9957                                         EMIT_NEW_PCONST (cfg, iargs [0], str);
9958                                 *sp = mono_emit_jit_icall (cfg, mono_string_new_wrapper, iargs);
9959                         } else {
9960                                 if (cfg->opt & MONO_OPT_SHARED) {
9961                                         MonoInst *iargs [3];
9962
9963                                         if (cfg->compile_aot) {
9964                                                 cfg->ldstr_list = g_list_prepend (cfg->ldstr_list, GINT_TO_POINTER (n));
9965                                         }
9966                                         EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
9967                                         EMIT_NEW_IMAGECONST (cfg, iargs [1], image);
9968                                         EMIT_NEW_ICONST (cfg, iargs [2], mono_metadata_token_index (n));
9969                                         *sp = mono_emit_jit_icall (cfg, ves_icall_mono_ldstr, iargs);
9970                                         mono_ldstr_checked (cfg->domain, image, mono_metadata_token_index (n), &cfg->error);
9971                                         CHECK_CFG_ERROR;
9972                                 } else {
9973                                         if (cfg->cbb->out_of_line) {
9974                                                 MonoInst *iargs [2];
9975
9976                                                 if (image == mono_defaults.corlib) {
9977                                                         /* 
9978                                                          * Avoid relocations in AOT and save some space by using a 
9979                                                          * version of helper_ldstr specialized to mscorlib.
9980                                                          */
9981                                                         EMIT_NEW_ICONST (cfg, iargs [0], mono_metadata_token_index (n));
9982                                                         *sp = mono_emit_jit_icall (cfg, mono_helper_ldstr_mscorlib, iargs);
9983                                                 } else {
9984                                                         /* Avoid creating the string object */
9985                                                         EMIT_NEW_IMAGECONST (cfg, iargs [0], image);
9986                                                         EMIT_NEW_ICONST (cfg, iargs [1], mono_metadata_token_index (n));
9987                                                         *sp = mono_emit_jit_icall (cfg, mono_helper_ldstr, iargs);
9988                                                 }
9989                                         } 
9990                                         else
9991                                         if (cfg->compile_aot) {
9992                                                 NEW_LDSTRCONST (cfg, ins, image, n);
9993                                                 *sp = ins;
9994                                                 MONO_ADD_INS (cfg->cbb, ins);
9995                                         } 
9996                                         else {
9997                                                 NEW_PCONST (cfg, ins, NULL);
9998                                                 ins->type = STACK_OBJ;
9999                                                 ins->inst_p0 = mono_ldstr_checked (cfg->domain, image, mono_metadata_token_index (n), &cfg->error);
10000                                                 CHECK_CFG_ERROR;
10001                                                 
10002                                                 if (!ins->inst_p0)
10003                                                         OUT_OF_MEMORY_FAILURE;
10004
10005                                                 *sp = ins;
10006                                                 MONO_ADD_INS (cfg->cbb, ins);
10007                                         }
10008                                 }
10009                         }
10010
10011                         sp++;
10012                         ip += 5;
10013                         break;
10014                 case CEE_NEWOBJ: {
10015                         MonoInst *iargs [2];
10016                         MonoMethodSignature *fsig;
10017                         MonoInst this_ins;
10018                         MonoInst *alloc;
10019                         MonoInst *vtable_arg = NULL;
10020
10021                         CHECK_OPSIZE (5);
10022                         token = read32 (ip + 1);
10023                         cmethod = mini_get_method (cfg, method, token, NULL, generic_context);
10024                         CHECK_CFG_ERROR;
10025
10026                         fsig = mono_method_get_signature_checked (cmethod, image, token, generic_context, &cfg->error);
10027                         CHECK_CFG_ERROR;
10028
10029                         mono_save_token_info (cfg, image, token, cmethod);
10030
10031                         if (!mono_class_init (cmethod->klass))
10032                                 TYPE_LOAD_ERROR (cmethod->klass);
10033
10034                         context_used = mini_method_check_context_used (cfg, cmethod);
10035
10036                         if (mono_security_core_clr_enabled ())
10037                                 ensure_method_is_allowed_to_call_method (cfg, method, cmethod);
10038
10039                         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)) {
10040                                 emit_class_init (cfg, cmethod->klass);
10041                                 CHECK_TYPELOAD (cmethod->klass);
10042                         }
10043
10044                         /*
10045                         if (cfg->gsharedvt) {
10046                                 if (mini_is_gsharedvt_variable_signature (sig))
10047                                         GSHAREDVT_FAILURE (*ip);
10048                         }
10049                         */
10050
10051                         n = fsig->param_count;
10052                         CHECK_STACK (n);
10053
10054                         /* 
10055                          * Generate smaller code for the common newobj <exception> instruction in
10056                          * argument checking code.
10057                          */
10058                         if (cfg->cbb->out_of_line && cmethod->klass->image == mono_defaults.corlib &&
10059                                 is_exception_class (cmethod->klass) && n <= 2 &&
10060                                 ((n < 1) || (!fsig->params [0]->byref && fsig->params [0]->type == MONO_TYPE_STRING)) && 
10061                                 ((n < 2) || (!fsig->params [1]->byref && fsig->params [1]->type == MONO_TYPE_STRING))) {
10062                                 MonoInst *iargs [3];
10063
10064                                 sp -= n;
10065
10066                                 EMIT_NEW_ICONST (cfg, iargs [0], cmethod->klass->type_token);
10067                                 switch (n) {
10068                                 case 0:
10069                                         *sp ++ = mono_emit_jit_icall (cfg, mono_create_corlib_exception_0, iargs);
10070                                         break;
10071                                 case 1:
10072                                         iargs [1] = sp [0];
10073                                         *sp ++ = mono_emit_jit_icall (cfg, mono_create_corlib_exception_1, iargs);
10074                                         break;
10075                                 case 2:
10076                                         iargs [1] = sp [0];
10077                                         iargs [2] = sp [1];
10078                                         *sp ++ = mono_emit_jit_icall (cfg, mono_create_corlib_exception_2, iargs);
10079                                         break;
10080                                 default:
10081                                         g_assert_not_reached ();
10082                                 }
10083
10084                                 ip += 5;
10085                                 inline_costs += 5;
10086                                 break;
10087                         }
10088
10089                         /* move the args to allow room for 'this' in the first position */
10090                         while (n--) {
10091                                 --sp;
10092                                 sp [1] = sp [0];
10093                         }
10094
10095                         /* check_call_signature () requires sp[0] to be set */
10096                         this_ins.type = STACK_OBJ;
10097                         sp [0] = &this_ins;
10098                         if (check_call_signature (cfg, fsig, sp))
10099                                 UNVERIFIED;
10100
10101                         iargs [0] = NULL;
10102
10103                         if (mini_class_is_system_array (cmethod->klass)) {
10104                                 *sp = emit_get_rgctx_method (cfg, context_used,
10105                                                                                          cmethod, MONO_RGCTX_INFO_METHOD);
10106
10107                                 /* Avoid varargs in the common case */
10108                                 if (fsig->param_count == 1)
10109                                         alloc = mono_emit_jit_icall (cfg, mono_array_new_1, sp);
10110                                 else if (fsig->param_count == 2)
10111                                         alloc = mono_emit_jit_icall (cfg, mono_array_new_2, sp);
10112                                 else if (fsig->param_count == 3)
10113                                         alloc = mono_emit_jit_icall (cfg, mono_array_new_3, sp);
10114                                 else if (fsig->param_count == 4)
10115                                         alloc = mono_emit_jit_icall (cfg, mono_array_new_4, sp);
10116                                 else
10117                                         alloc = handle_array_new (cfg, fsig->param_count, sp, ip);
10118                         } else if (cmethod->string_ctor) {
10119                                 g_assert (!context_used);
10120                                 g_assert (!vtable_arg);
10121                                 /* we simply pass a null pointer */
10122                                 EMIT_NEW_PCONST (cfg, *sp, NULL); 
10123                                 /* now call the string ctor */
10124                                 alloc = mono_emit_method_call_full (cfg, cmethod, fsig, FALSE, sp, NULL, NULL, NULL);
10125                         } else {
10126                                 if (cmethod->klass->valuetype) {
10127                                         iargs [0] = mono_compile_create_var (cfg, &cmethod->klass->byval_arg, OP_LOCAL);
10128                                         emit_init_rvar (cfg, iargs [0]->dreg, &cmethod->klass->byval_arg);
10129                                         EMIT_NEW_TEMPLOADA (cfg, *sp, iargs [0]->inst_c0);
10130
10131                                         alloc = NULL;
10132
10133                                         /* 
10134                                          * The code generated by mini_emit_virtual_call () expects
10135                                          * iargs [0] to be a boxed instance, but luckily the vcall
10136                                          * will be transformed into a normal call there.
10137                                          */
10138                                 } else if (context_used) {
10139                                         alloc = handle_alloc (cfg, cmethod->klass, FALSE, context_used);
10140                                         *sp = alloc;
10141                                 } else {
10142                                         MonoVTable *vtable = NULL;
10143
10144                                         if (!cfg->compile_aot)
10145                                                 vtable = mono_class_vtable (cfg->domain, cmethod->klass);
10146                                         CHECK_TYPELOAD (cmethod->klass);
10147
10148                                         /*
10149                                          * TypeInitializationExceptions thrown from the mono_runtime_class_init
10150                                          * call in mono_jit_runtime_invoke () can abort the finalizer thread.
10151                                          * As a workaround, we call class cctors before allocating objects.
10152                                          */
10153                                         if (mini_field_access_needs_cctor_run (cfg, method, cmethod->klass, vtable) && !(g_slist_find (class_inits, cmethod->klass))) {
10154                                                 emit_class_init (cfg, cmethod->klass);
10155                                                 if (cfg->verbose_level > 2)
10156                                                         printf ("class %s.%s needs init call for ctor\n", cmethod->klass->name_space, cmethod->klass->name);
10157                                                 class_inits = g_slist_prepend (class_inits, cmethod->klass);
10158                                         }
10159
10160                                         alloc = handle_alloc (cfg, cmethod->klass, FALSE, 0);
10161                                         *sp = alloc;
10162                                 }
10163                                 CHECK_CFG_EXCEPTION; /*for handle_alloc*/
10164
10165                                 if (alloc)
10166                                         MONO_EMIT_NEW_UNALU (cfg, OP_NOT_NULL, -1, alloc->dreg);
10167
10168                                 /* Now call the actual ctor */
10169                                 handle_ctor_call (cfg, cmethod, fsig, context_used, sp, ip, &inline_costs);
10170                                 CHECK_CFG_EXCEPTION;
10171                         }
10172
10173                         if (alloc == NULL) {
10174                                 /* Valuetype */
10175                                 EMIT_NEW_TEMPLOAD (cfg, ins, iargs [0]->inst_c0);
10176                                 type_to_eval_stack_type (cfg, &ins->klass->byval_arg, ins);
10177                                 *sp++= ins;
10178                         } else {
10179                                 *sp++ = alloc;
10180                         }
10181                         
10182                         ip += 5;
10183                         inline_costs += 5;
10184                         if (!(seq_point_locs && mono_bitset_test_fast (seq_point_locs, ip - header->code)))
10185                                 emit_seq_point (cfg, method, ip, FALSE, TRUE);
10186                         break;
10187                 }
10188                 case CEE_CASTCLASS:
10189                 case CEE_ISINST: {
10190                         CHECK_STACK (1);
10191                         --sp;
10192                         CHECK_OPSIZE (5);
10193                         token = read32 (ip + 1);
10194                         klass = mini_get_class (method, token, generic_context);
10195                         CHECK_TYPELOAD (klass);
10196                         if (sp [0]->type != STACK_OBJ)
10197                                 UNVERIFIED;
10198
10199                         MONO_INST_NEW (cfg, ins, *ip == CEE_ISINST ? OP_ISINST : OP_CASTCLASS);
10200                         ins->dreg = alloc_preg (cfg);
10201                         ins->sreg1 = (*sp)->dreg;
10202                         ins->klass = klass;
10203                         ins->type = STACK_OBJ;
10204                         MONO_ADD_INS (cfg->cbb, ins);
10205
10206                         CHECK_CFG_EXCEPTION;
10207                         *sp++ = ins;
10208                         ip += 5;
10209
10210                         cfg->flags |= MONO_CFG_HAS_TYPE_CHECK;
10211                         break;
10212                 }
10213                 case CEE_UNBOX_ANY: {
10214                         MonoInst *res, *addr;
10215
10216                         CHECK_STACK (1);
10217                         --sp;
10218                         CHECK_OPSIZE (5);
10219                         token = read32 (ip + 1);
10220                         klass = mini_get_class (method, token, generic_context);
10221                         CHECK_TYPELOAD (klass);
10222
10223                         mono_save_token_info (cfg, image, token, klass);
10224
10225                         context_used = mini_class_check_context_used (cfg, klass);
10226
10227                         if (mini_is_gsharedvt_klass (klass)) {
10228                                 res = handle_unbox_gsharedvt (cfg, klass, *sp);
10229                                 inline_costs += 2;
10230                         } else if (generic_class_is_reference_type (cfg, klass)) {
10231                                 if (MONO_INS_IS_PCONST_NULL (*sp)) {
10232                                         EMIT_NEW_PCONST (cfg, res, NULL);
10233                                         res->type = STACK_OBJ;
10234                                 } else {
10235                                         MONO_INST_NEW (cfg, res, OP_CASTCLASS);
10236                                         res->dreg = alloc_preg (cfg);
10237                                         res->sreg1 = (*sp)->dreg;
10238                                         res->klass = klass;
10239                                         res->type = STACK_OBJ;
10240                                         MONO_ADD_INS (cfg->cbb, res);
10241                                         cfg->flags |= MONO_CFG_HAS_TYPE_CHECK;
10242                                 }
10243                         } else if (mono_class_is_nullable (klass)) {
10244                                 res = handle_unbox_nullable (cfg, *sp, klass, context_used);
10245                         } else {
10246                                 addr = handle_unbox (cfg, klass, sp, context_used);
10247                                 /* LDOBJ */
10248                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr->dreg, 0);
10249                                 res = ins;
10250                                 inline_costs += 2;
10251                         }
10252
10253                         *sp ++ = res;
10254                         ip += 5;
10255                         break;
10256                 }
10257                 case CEE_BOX: {
10258                         MonoInst *val;
10259                         MonoClass *enum_class;
10260                         MonoMethod *has_flag;
10261
10262                         CHECK_STACK (1);
10263                         --sp;
10264                         val = *sp;
10265                         CHECK_OPSIZE (5);
10266                         token = read32 (ip + 1);
10267                         klass = mini_get_class (method, token, generic_context);
10268                         CHECK_TYPELOAD (klass);
10269
10270                         mono_save_token_info (cfg, image, token, klass);
10271
10272                         context_used = mini_class_check_context_used (cfg, klass);
10273
10274                         if (generic_class_is_reference_type (cfg, klass)) {
10275                                 *sp++ = val;
10276                                 ip += 5;
10277                                 break;
10278                         }
10279
10280                         if (klass == mono_defaults.void_class)
10281                                 UNVERIFIED;
10282                         if (target_type_is_incompatible (cfg, &klass->byval_arg, *sp))
10283                                 UNVERIFIED;
10284                         /* frequent check in generic code: box (struct), brtrue */
10285
10286                         /*
10287                          * Look for:
10288                          *
10289                          *   <push int/long ptr>
10290                          *   <push int/long>
10291                          *   box MyFlags
10292                          *   constrained. MyFlags
10293                          *   callvirt instace bool class [mscorlib] System.Enum::HasFlag (class [mscorlib] System.Enum)
10294                          *
10295                          * If we find this sequence and the operand types on box and constrained
10296                          * are equal, we can emit a specialized instruction sequence instead of
10297                          * the very slow HasFlag () call.
10298                          */
10299                         if ((cfg->opt & MONO_OPT_INTRINS) &&
10300                             /* Cheap checks first. */
10301                             ip + 5 + 6 + 5 < end &&
10302                             ip [5] == CEE_PREFIX1 &&
10303                             ip [6] == CEE_CONSTRAINED_ &&
10304                             ip [11] == CEE_CALLVIRT &&
10305                             ip_in_bb (cfg, cfg->cbb, ip + 5 + 6 + 5) &&
10306                             mono_class_is_enum (klass) &&
10307                             (enum_class = mini_get_class (method, read32 (ip + 7), generic_context)) &&
10308                             (has_flag = mini_get_method (cfg, method, read32 (ip + 12), NULL, generic_context)) &&
10309                             has_flag->klass == mono_defaults.enum_class &&
10310                             !strcmp (has_flag->name, "HasFlag") &&
10311                             has_flag->signature->hasthis &&
10312                             has_flag->signature->param_count == 1) {
10313                                 CHECK_TYPELOAD (enum_class);
10314
10315                                 if (enum_class == klass) {
10316                                         MonoInst *enum_this, *enum_flag;
10317
10318                                         ip += 5 + 6 + 5;
10319                                         --sp;
10320
10321                                         enum_this = sp [0];
10322                                         enum_flag = sp [1];
10323
10324                                         *sp++ = handle_enum_has_flag (cfg, klass, enum_this, enum_flag);
10325                                         break;
10326                                 }
10327                         }
10328
10329                         // FIXME: LLVM can't handle the inconsistent bb linking
10330                         if (!mono_class_is_nullable (klass) &&
10331                                 !mini_is_gsharedvt_klass (klass) &&
10332                                 ip + 5 < end && ip_in_bb (cfg, cfg->cbb, ip + 5) &&
10333                                 (ip [5] == CEE_BRTRUE || 
10334                                  ip [5] == CEE_BRTRUE_S ||
10335                                  ip [5] == CEE_BRFALSE ||
10336                                  ip [5] == CEE_BRFALSE_S)) {
10337                                 gboolean is_true = ip [5] == CEE_BRTRUE || ip [5] == CEE_BRTRUE_S;
10338                                 int dreg;
10339                                 MonoBasicBlock *true_bb, *false_bb;
10340
10341                                 ip += 5;
10342
10343                                 if (cfg->verbose_level > 3) {
10344                                         printf ("converting (in B%d: stack: %d) %s", cfg->cbb->block_num, (int)(sp - stack_start), mono_disasm_code_one (NULL, method, ip, NULL));
10345                                         printf ("<box+brtrue opt>\n");
10346                                 }
10347
10348                                 switch (*ip) {
10349                                 case CEE_BRTRUE_S:
10350                                 case CEE_BRFALSE_S:
10351                                         CHECK_OPSIZE (2);
10352                                         ip++;
10353                                         target = ip + 1 + (signed char)(*ip);
10354                                         ip++;
10355                                         break;
10356                                 case CEE_BRTRUE:
10357                                 case CEE_BRFALSE:
10358                                         CHECK_OPSIZE (5);
10359                                         ip++;
10360                                         target = ip + 4 + (gint)(read32 (ip));
10361                                         ip += 4;
10362                                         break;
10363                                 default:
10364                                         g_assert_not_reached ();
10365                                 }
10366
10367                                 /* 
10368                                  * We need to link both bblocks, since it is needed for handling stack
10369                                  * arguments correctly (See test_0_box_brtrue_opt_regress_81102).
10370                                  * Branching to only one of them would lead to inconsistencies, so
10371                                  * generate an ICONST+BRTRUE, the branch opts will get rid of them.
10372                                  */
10373                                 GET_BBLOCK (cfg, true_bb, target);
10374                                 GET_BBLOCK (cfg, false_bb, ip);
10375
10376                                 mono_link_bblock (cfg, cfg->cbb, true_bb);
10377                                 mono_link_bblock (cfg, cfg->cbb, false_bb);
10378
10379                                 if (sp != stack_start) {
10380                                         handle_stack_args (cfg, stack_start, sp - stack_start);
10381                                         sp = stack_start;
10382                                         CHECK_UNVERIFIABLE (cfg);
10383                                 }
10384
10385                                 if (COMPILE_LLVM (cfg)) {
10386                                         dreg = alloc_ireg (cfg);
10387                                         MONO_EMIT_NEW_ICONST (cfg, dreg, 0);
10388                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, dreg, is_true ? 0 : 1);
10389
10390                                         MONO_EMIT_NEW_BRANCH_BLOCK2 (cfg, OP_IBEQ, true_bb, false_bb);
10391                                 } else {
10392                                         /* The JIT can't eliminate the iconst+compare */
10393                                         MONO_INST_NEW (cfg, ins, OP_BR);
10394                                         ins->inst_target_bb = is_true ? true_bb : false_bb;
10395                                         MONO_ADD_INS (cfg->cbb, ins);
10396                                 }
10397
10398                                 start_new_bblock = 1;
10399                                 break;
10400                         }
10401
10402                         *sp++ = handle_box (cfg, val, klass, context_used);
10403
10404                         CHECK_CFG_EXCEPTION;
10405                         ip += 5;
10406                         inline_costs += 1;
10407                         break;
10408                 }
10409                 case CEE_UNBOX: {
10410                         CHECK_STACK (1);
10411                         --sp;
10412                         CHECK_OPSIZE (5);
10413                         token = read32 (ip + 1);
10414                         klass = mini_get_class (method, token, generic_context);
10415                         CHECK_TYPELOAD (klass);
10416
10417                         mono_save_token_info (cfg, image, token, klass);
10418
10419                         context_used = mini_class_check_context_used (cfg, klass);
10420
10421                         if (mono_class_is_nullable (klass)) {
10422                                 MonoInst *val;
10423
10424                                 val = handle_unbox_nullable (cfg, *sp, klass, context_used);
10425                                 EMIT_NEW_VARLOADA (cfg, ins, get_vreg_to_inst (cfg, val->dreg), &val->klass->byval_arg);
10426
10427                                 *sp++= ins;
10428                         } else {
10429                                 ins = handle_unbox (cfg, klass, sp, context_used);
10430                                 *sp++ = ins;
10431                         }
10432                         ip += 5;
10433                         inline_costs += 2;
10434                         break;
10435                 }
10436                 case CEE_LDFLD:
10437                 case CEE_LDFLDA:
10438                 case CEE_STFLD:
10439                 case CEE_LDSFLD:
10440                 case CEE_LDSFLDA:
10441                 case CEE_STSFLD: {
10442                         MonoClassField *field;
10443 #ifndef DISABLE_REMOTING
10444                         int costs;
10445 #endif
10446                         guint foffset;
10447                         gboolean is_instance;
10448                         int op;
10449                         gpointer addr = NULL;
10450                         gboolean is_special_static;
10451                         MonoType *ftype;
10452                         MonoInst *store_val = NULL;
10453                         MonoInst *thread_ins;
10454
10455                         op = *ip;
10456                         is_instance = (op == CEE_LDFLD || op == CEE_LDFLDA || op == CEE_STFLD);
10457                         if (is_instance) {
10458                                 if (op == CEE_STFLD) {
10459                                         CHECK_STACK (2);
10460                                         sp -= 2;
10461                                         store_val = sp [1];
10462                                 } else {
10463                                         CHECK_STACK (1);
10464                                         --sp;
10465                                 }
10466                                 if (sp [0]->type == STACK_I4 || sp [0]->type == STACK_I8 || sp [0]->type == STACK_R8)
10467                                         UNVERIFIED;
10468                                 if (*ip != CEE_LDFLD && sp [0]->type == STACK_VTYPE)
10469                                         UNVERIFIED;
10470                         } else {
10471                                 if (op == CEE_STSFLD) {
10472                                         CHECK_STACK (1);
10473                                         sp--;
10474                                         store_val = sp [0];
10475                                 }
10476                         }
10477
10478                         CHECK_OPSIZE (5);
10479                         token = read32 (ip + 1);
10480                         if (method->wrapper_type != MONO_WRAPPER_NONE) {
10481                                 field = (MonoClassField *)mono_method_get_wrapper_data (method, token);
10482                                 klass = field->parent;
10483                         }
10484                         else {
10485                                 field = mono_field_from_token_checked (image, token, &klass, generic_context, &cfg->error);
10486                                 CHECK_CFG_ERROR;
10487                         }
10488                         if (!dont_verify && !cfg->skip_visibility && !mono_method_can_access_field (method, field))
10489                                 FIELD_ACCESS_FAILURE (method, field);
10490                         mono_class_init (klass);
10491
10492                         /* if the class is Critical then transparent code cannot access it's fields */
10493                         if (!is_instance && mono_security_core_clr_enabled ())
10494                                 ensure_method_is_allowed_to_access_field (cfg, method, field);
10495
10496                         /* XXX this is technically required but, so far (SL2), no [SecurityCritical] types (not many exists) have
10497                            any visible *instance* field  (in fact there's a single case for a static field in Marshal) XXX
10498                         if (mono_security_core_clr_enabled ())
10499                                 ensure_method_is_allowed_to_access_field (cfg, method, field);
10500                         */
10501
10502                         ftype = mono_field_get_type (field);
10503
10504                         /*
10505                          * LDFLD etc. is usable on static fields as well, so convert those cases to
10506                          * the static case.
10507                          */
10508                         if (is_instance && ftype->attrs & FIELD_ATTRIBUTE_STATIC) {
10509                                 switch (op) {
10510                                 case CEE_LDFLD:
10511                                         op = CEE_LDSFLD;
10512                                         break;
10513                                 case CEE_STFLD:
10514                                         op = CEE_STSFLD;
10515                                         break;
10516                                 case CEE_LDFLDA:
10517                                         op = CEE_LDSFLDA;
10518                                         break;
10519                                 default:
10520                                         g_assert_not_reached ();
10521                                 }
10522                                 is_instance = FALSE;
10523                         }
10524
10525                         context_used = mini_class_check_context_used (cfg, klass);
10526
10527                         /* INSTANCE CASE */
10528
10529                         foffset = klass->valuetype? field->offset - sizeof (MonoObject): field->offset;
10530                         if (op == CEE_STFLD) {
10531                                 if (target_type_is_incompatible (cfg, field->type, sp [1]))
10532                                         UNVERIFIED;
10533 #ifndef DISABLE_REMOTING
10534                                 if ((mono_class_is_marshalbyref (klass) && !MONO_CHECK_THIS (sp [0])) || mono_class_is_contextbound (klass) || klass == mono_defaults.marshalbyrefobject_class) {
10535                                         MonoMethod *stfld_wrapper = mono_marshal_get_stfld_wrapper (field->type); 
10536                                         MonoInst *iargs [5];
10537
10538                                         GSHAREDVT_FAILURE (op);
10539
10540                                         iargs [0] = sp [0];
10541                                         EMIT_NEW_CLASSCONST (cfg, iargs [1], klass);
10542                                         EMIT_NEW_FIELDCONST (cfg, iargs [2], field);
10543                                         EMIT_NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) : 
10544                                                     field->offset);
10545                                         iargs [4] = sp [1];
10546
10547                                         if (cfg->opt & MONO_OPT_INLINE || cfg->compile_aot) {
10548                                                 costs = inline_method (cfg, stfld_wrapper, mono_method_signature (stfld_wrapper), 
10549                                                                                            iargs, ip, cfg->real_offset, TRUE);
10550                                                 CHECK_CFG_EXCEPTION;
10551                                                 g_assert (costs > 0);
10552                                                       
10553                                                 cfg->real_offset += 5;
10554
10555                                                 inline_costs += costs;
10556                                         } else {
10557                                                 mono_emit_method_call (cfg, stfld_wrapper, iargs, NULL);
10558                                         }
10559                                 } else
10560 #endif
10561                                 {
10562                                         MonoInst *store, *wbarrier_ptr_ins = NULL;
10563
10564                                         MONO_EMIT_NULL_CHECK (cfg, sp [0]->dreg);
10565
10566                                         if (ins_flag & MONO_INST_VOLATILE) {
10567                                                 /* Volatile stores have release semantics, see 12.6.7 in Ecma 335 */
10568                                                 mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_REL);
10569                                         }
10570
10571                                         if (mini_is_gsharedvt_klass (klass)) {
10572                                                 MonoInst *offset_ins;
10573
10574                                                 context_used = mini_class_check_context_used (cfg, klass);
10575
10576                                                 offset_ins = emit_get_gsharedvt_info (cfg, field, MONO_RGCTX_INFO_FIELD_OFFSET);
10577                                                 /* The value is offset by 1 */
10578                                                 EMIT_NEW_BIALU_IMM (cfg, ins, OP_PSUB_IMM, offset_ins->dreg, offset_ins->dreg, 1);
10579                                                 dreg = alloc_ireg_mp (cfg);
10580                                                 EMIT_NEW_BIALU (cfg, ins, OP_PADD, dreg, sp [0]->dreg, offset_ins->dreg);
10581                                                 wbarrier_ptr_ins = ins;
10582                                                 /* The decomposition will call mini_emit_stobj () which will emit a wbarrier if needed */
10583                                                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, store, field->type, dreg, 0, sp [1]->dreg);
10584                                         } else {
10585                                                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, store, field->type, sp [0]->dreg, foffset, sp [1]->dreg);
10586                                         }
10587                                         if (sp [0]->opcode != OP_LDADDR)
10588                                                 store->flags |= MONO_INST_FAULT;
10589
10590                                         if (cfg->gen_write_barriers && mini_type_to_stind (cfg, field->type) == CEE_STIND_REF && !MONO_INS_IS_PCONST_NULL (sp [1])) {
10591                                                 if (mini_is_gsharedvt_klass (klass)) {
10592                                                         g_assert (wbarrier_ptr_ins);
10593                                                         mini_emit_write_barrier (cfg, wbarrier_ptr_ins, sp [1]);
10594                                                 } else {
10595                                                         /* insert call to write barrier */
10596                                                         MonoInst *ptr;
10597                                                         int dreg;
10598
10599                                                         dreg = alloc_ireg_mp (cfg);
10600                                                         EMIT_NEW_BIALU_IMM (cfg, ptr, OP_PADD_IMM, dreg, sp [0]->dreg, foffset);
10601                                                         mini_emit_write_barrier (cfg, ptr, sp [1]);
10602                                                 }
10603                                         }
10604
10605                                         store->flags |= ins_flag;
10606                                 }
10607                                 ins_flag = 0;
10608                                 ip += 5;
10609                                 break;
10610                         }
10611
10612 #ifndef DISABLE_REMOTING
10613                         if (is_instance && ((mono_class_is_marshalbyref (klass) && !MONO_CHECK_THIS (sp [0])) || mono_class_is_contextbound (klass) || klass == mono_defaults.marshalbyrefobject_class)) {
10614                                 MonoMethod *wrapper = (op == CEE_LDFLDA) ? mono_marshal_get_ldflda_wrapper (field->type) : mono_marshal_get_ldfld_wrapper (field->type); 
10615                                 MonoInst *iargs [4];
10616
10617                                 GSHAREDVT_FAILURE (op);
10618
10619                                 iargs [0] = sp [0];
10620                                 EMIT_NEW_CLASSCONST (cfg, iargs [1], klass);
10621                                 EMIT_NEW_FIELDCONST (cfg, iargs [2], field);
10622                                 EMIT_NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) : field->offset);
10623                                 if (cfg->opt & MONO_OPT_INLINE || cfg->compile_aot) {
10624                                         costs = inline_method (cfg, wrapper, mono_method_signature (wrapper), 
10625                                                                                    iargs, ip, cfg->real_offset, TRUE);
10626                                         CHECK_CFG_EXCEPTION;
10627                                         g_assert (costs > 0);
10628                                                       
10629                                         cfg->real_offset += 5;
10630
10631                                         *sp++ = iargs [0];
10632
10633                                         inline_costs += costs;
10634                                 } else {
10635                                         ins = mono_emit_method_call (cfg, wrapper, iargs, NULL);
10636                                         *sp++ = ins;
10637                                 }
10638                         } else 
10639 #endif
10640                         if (is_instance) {
10641                                 if (sp [0]->type == STACK_VTYPE) {
10642                                         MonoInst *var;
10643
10644                                         /* Have to compute the address of the variable */
10645
10646                                         var = get_vreg_to_inst (cfg, sp [0]->dreg);
10647                                         if (!var)
10648                                                 var = mono_compile_create_var_for_vreg (cfg, &klass->byval_arg, OP_LOCAL, sp [0]->dreg);
10649                                         else
10650                                                 g_assert (var->klass == klass);
10651                                         
10652                                         EMIT_NEW_VARLOADA (cfg, ins, var, &var->klass->byval_arg);
10653                                         sp [0] = ins;
10654                                 }
10655
10656                                 if (op == CEE_LDFLDA) {
10657                                         if (sp [0]->type == STACK_OBJ) {
10658                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, sp [0]->dreg, 0);
10659                                                 MONO_EMIT_NEW_COND_EXC (cfg, EQ, "NullReferenceException");
10660                                         }
10661
10662                                         dreg = alloc_ireg_mp (cfg);
10663
10664                                         if (mini_is_gsharedvt_klass (klass)) {
10665                                                 MonoInst *offset_ins;
10666
10667                                                 offset_ins = emit_get_gsharedvt_info (cfg, field, MONO_RGCTX_INFO_FIELD_OFFSET);
10668                                                 /* The value is offset by 1 */
10669                                                 EMIT_NEW_BIALU_IMM (cfg, ins, OP_PSUB_IMM, offset_ins->dreg, offset_ins->dreg, 1);
10670                                                 EMIT_NEW_BIALU (cfg, ins, OP_PADD, dreg, sp [0]->dreg, offset_ins->dreg);
10671                                         } else {
10672                                                 EMIT_NEW_BIALU_IMM (cfg, ins, OP_PADD_IMM, dreg, sp [0]->dreg, foffset);
10673                                         }
10674                                         ins->klass = mono_class_from_mono_type (field->type);
10675                                         ins->type = STACK_MP;
10676                                         *sp++ = ins;
10677                                 } else {
10678                                         MonoInst *load;
10679
10680                                         MONO_EMIT_NULL_CHECK (cfg, sp [0]->dreg);
10681
10682                                         if (sp [0]->opcode == OP_LDADDR && klass->simd_type && cfg->opt & MONO_OPT_SIMD) {
10683                                                 ins = mono_emit_simd_field_load (cfg, field, sp [0]);
10684                                                 if (ins) {
10685                                                         *sp++ = ins;
10686                                                         ins_flag = 0;
10687                                                         ip += 5;
10688                                                         break;
10689                                                 }
10690                                         }
10691
10692                                         MonoInst *field_add_inst = sp [0];
10693                                         if (mini_is_gsharedvt_klass (klass)) {
10694                                                 MonoInst *offset_ins;
10695
10696                                                 offset_ins = emit_get_gsharedvt_info (cfg, field, MONO_RGCTX_INFO_FIELD_OFFSET);
10697                                                 /* The value is offset by 1 */
10698                                                 EMIT_NEW_BIALU_IMM (cfg, ins, OP_PSUB_IMM, offset_ins->dreg, offset_ins->dreg, 1);
10699                                                 EMIT_NEW_BIALU (cfg, field_add_inst, OP_PADD, alloc_ireg_mp (cfg), sp [0]->dreg, offset_ins->dreg);
10700                                                 foffset = 0;
10701                                         }
10702
10703                                         load = mini_emit_memory_load (cfg, field->type, field_add_inst, foffset, ins_flag);
10704
10705                                         if (sp [0]->opcode != OP_LDADDR)
10706                                                 load->flags |= MONO_INST_FAULT;
10707                                         *sp++ = load;
10708                                 }
10709                         }
10710
10711                         if (is_instance) {
10712                                 ins_flag = 0;
10713                                 ip += 5;
10714                                 break;
10715                         }
10716
10717                         /* STATIC CASE */
10718                         context_used = mini_class_check_context_used (cfg, klass);
10719
10720                         if (ftype->attrs & FIELD_ATTRIBUTE_LITERAL) {
10721                                 mono_error_set_field_load (&cfg->error, field->parent, field->name, "Using static instructions with literal field");
10722                                 CHECK_CFG_ERROR;
10723                         }
10724
10725                         /* The special_static_fields field is init'd in mono_class_vtable, so it needs
10726                          * to be called here.
10727                          */
10728                         if (!context_used && !(cfg->opt & MONO_OPT_SHARED)) {
10729                                 mono_class_vtable (cfg->domain, klass);
10730                                 CHECK_TYPELOAD (klass);
10731                         }
10732                         mono_domain_lock (cfg->domain);
10733                         if (cfg->domain->special_static_fields)
10734                                 addr = g_hash_table_lookup (cfg->domain->special_static_fields, field);
10735                         mono_domain_unlock (cfg->domain);
10736
10737                         is_special_static = mono_class_field_is_special_static (field);
10738
10739                         if (is_special_static && ((gsize)addr & 0x80000000) == 0)
10740                                 thread_ins = mono_create_tls_get (cfg, TLS_KEY_THREAD);
10741                         else
10742                                 thread_ins = NULL;
10743
10744                         /* Generate IR to compute the field address */
10745                         if (is_special_static && ((gsize)addr & 0x80000000) == 0 && thread_ins && !(cfg->opt & MONO_OPT_SHARED) && !context_used) {
10746                                 /*
10747                                  * Fast access to TLS data
10748                                  * Inline version of get_thread_static_data () in
10749                                  * threads.c.
10750                                  */
10751                                 guint32 offset;
10752                                 int idx, static_data_reg, array_reg, dreg;
10753
10754                                 if (context_used && cfg->gsharedvt && mini_is_gsharedvt_klass (klass))
10755                                         GSHAREDVT_FAILURE (op);
10756
10757                                 static_data_reg = alloc_ireg (cfg);
10758                                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, static_data_reg, thread_ins->dreg, MONO_STRUCT_OFFSET (MonoInternalThread, static_data));
10759
10760                                 if (cfg->compile_aot) {
10761                                         int offset_reg, offset2_reg, idx_reg;
10762
10763                                         /* For TLS variables, this will return the TLS offset */
10764                                         EMIT_NEW_SFLDACONST (cfg, ins, field);
10765                                         offset_reg = ins->dreg;
10766                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_IAND_IMM, offset_reg, offset_reg, 0x7fffffff);
10767                                         idx_reg = alloc_ireg (cfg);
10768                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_IAND_IMM, idx_reg, offset_reg, 0x3f);
10769                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ISHL_IMM, idx_reg, idx_reg, sizeof (gpointer) == 8 ? 3 : 2);
10770                                         MONO_EMIT_NEW_BIALU (cfg, OP_PADD, static_data_reg, static_data_reg, idx_reg);
10771                                         array_reg = alloc_ireg (cfg);
10772                                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, array_reg, static_data_reg, 0);
10773                                         offset2_reg = alloc_ireg (cfg);
10774                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ISHR_UN_IMM, offset2_reg, offset_reg, 6);
10775                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_IAND_IMM, offset2_reg, offset2_reg, 0x1ffffff);
10776                                         dreg = alloc_ireg (cfg);
10777                                         EMIT_NEW_BIALU (cfg, ins, OP_PADD, dreg, array_reg, offset2_reg);
10778                                 } else {
10779                                         offset = (gsize)addr & 0x7fffffff;
10780                                         idx = offset & 0x3f;
10781
10782                                         array_reg = alloc_ireg (cfg);
10783                                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, array_reg, static_data_reg, idx * sizeof (gpointer));
10784                                         dreg = alloc_ireg (cfg);
10785                                         EMIT_NEW_BIALU_IMM (cfg, ins, OP_ADD_IMM, dreg, array_reg, ((offset >> 6) & 0x1ffffff));
10786                                 }
10787                         } else if ((cfg->opt & MONO_OPT_SHARED) ||
10788                                         (cfg->compile_aot && is_special_static) ||
10789                                         (context_used && is_special_static)) {
10790                                 MonoInst *iargs [2];
10791
10792                                 g_assert (field->parent);
10793                                 EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
10794                                 if (context_used) {
10795                                         iargs [1] = emit_get_rgctx_field (cfg, context_used,
10796                                                 field, MONO_RGCTX_INFO_CLASS_FIELD);
10797                                 } else {
10798                                         EMIT_NEW_FIELDCONST (cfg, iargs [1], field);
10799                                 }
10800                                 ins = mono_emit_jit_icall (cfg, mono_class_static_field_address, iargs);
10801                         } else if (context_used) {
10802                                 MonoInst *static_data;
10803
10804                                 /*
10805                                 g_print ("sharing static field access in %s.%s.%s - depth %d offset %d\n",
10806                                         method->klass->name_space, method->klass->name, method->name,
10807                                         depth, field->offset);
10808                                 */
10809
10810                                 if (mono_class_needs_cctor_run (klass, method))
10811                                         emit_class_init (cfg, klass);
10812
10813                                 /*
10814                                  * The pointer we're computing here is
10815                                  *
10816                                  *   super_info.static_data + field->offset
10817                                  */
10818                                 static_data = mini_emit_get_rgctx_klass (cfg, context_used,
10819                                         klass, MONO_RGCTX_INFO_STATIC_DATA);
10820
10821                                 if (mini_is_gsharedvt_klass (klass)) {
10822                                         MonoInst *offset_ins;
10823
10824                                         offset_ins = emit_get_rgctx_field (cfg, context_used, field, MONO_RGCTX_INFO_FIELD_OFFSET);
10825                                         /* The value is offset by 1 */
10826                                         EMIT_NEW_BIALU_IMM (cfg, ins, OP_PSUB_IMM, offset_ins->dreg, offset_ins->dreg, 1);
10827                                         dreg = alloc_ireg_mp (cfg);
10828                                         EMIT_NEW_BIALU (cfg, ins, OP_PADD, dreg, static_data->dreg, offset_ins->dreg);
10829                                 } else if (field->offset == 0) {
10830                                         ins = static_data;
10831                                 } else {
10832                                         int addr_reg = mono_alloc_preg (cfg);
10833                                         EMIT_NEW_BIALU_IMM (cfg, ins, OP_PADD_IMM, addr_reg, static_data->dreg, field->offset);
10834                                 }
10835                                 } else if ((cfg->opt & MONO_OPT_SHARED) || (cfg->compile_aot && addr)) {
10836                                 MonoInst *iargs [2];
10837
10838                                 g_assert (field->parent);
10839                                 EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
10840                                 EMIT_NEW_FIELDCONST (cfg, iargs [1], field);
10841                                 ins = mono_emit_jit_icall (cfg, mono_class_static_field_address, iargs);
10842                         } else {
10843                                 MonoVTable *vtable = NULL;
10844
10845                                 if (!cfg->compile_aot)
10846                                         vtable = mono_class_vtable (cfg->domain, klass);
10847                                 CHECK_TYPELOAD (klass);
10848
10849                                 if (!addr) {
10850                                         if (mini_field_access_needs_cctor_run (cfg, method, klass, vtable)) {
10851                                                 if (!(g_slist_find (class_inits, klass))) {
10852                                                         emit_class_init (cfg, klass);
10853                                                         if (cfg->verbose_level > 2)
10854                                                                 printf ("class %s.%s needs init call for %s\n", klass->name_space, klass->name, mono_field_get_name (field));
10855                                                         class_inits = g_slist_prepend (class_inits, klass);
10856                                                 }
10857                                         } else {
10858                                                 if (cfg->run_cctors) {
10859                                                         /* This makes so that inline cannot trigger */
10860                                                         /* .cctors: too many apps depend on them */
10861                                                         /* running with a specific order... */
10862                                                         g_assert (vtable);
10863                                                         if (! vtable->initialized)
10864                                                                 INLINE_FAILURE ("class init");
10865                                                         if (!mono_runtime_class_init_full (vtable, &cfg->error)) {
10866                                                                 mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
10867                                                                 goto exception_exit;
10868                                                         }
10869                                                 }
10870                                         }
10871                                         if (cfg->compile_aot)
10872                                                 EMIT_NEW_SFLDACONST (cfg, ins, field);
10873                                         else {
10874                                                 g_assert (vtable);
10875                                                 addr = (char*)mono_vtable_get_static_field_data (vtable) + field->offset;
10876                                                 g_assert (addr);
10877                                                 EMIT_NEW_PCONST (cfg, ins, addr);
10878                                         }
10879                                 } else {
10880                                         MonoInst *iargs [1];
10881                                         EMIT_NEW_ICONST (cfg, iargs [0], GPOINTER_TO_UINT (addr));
10882                                         ins = mono_emit_jit_icall (cfg, mono_get_special_static_data, iargs);
10883                                 }
10884                         }
10885
10886                         /* Generate IR to do the actual load/store operation */
10887
10888                         if ((op == CEE_STFLD || op == CEE_STSFLD) && (ins_flag & MONO_INST_VOLATILE)) {
10889                                 /* Volatile stores have release semantics, see 12.6.7 in Ecma 335 */
10890                                 mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_REL);
10891                         }
10892
10893                         if (op == CEE_LDSFLDA) {
10894                                 ins->klass = mono_class_from_mono_type (ftype);
10895                                 ins->type = STACK_PTR;
10896                                 *sp++ = ins;
10897                         } else if (op == CEE_STSFLD) {
10898                                 MonoInst *store;
10899
10900                                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, store, ftype, ins->dreg, 0, store_val->dreg);
10901                                 store->flags |= ins_flag;
10902                         } else {
10903                                 gboolean is_const = FALSE;
10904                                 MonoVTable *vtable = NULL;
10905                                 gpointer addr = NULL;
10906
10907                                 if (!context_used) {
10908                                         vtable = mono_class_vtable (cfg->domain, klass);
10909                                         CHECK_TYPELOAD (klass);
10910                                 }
10911                                 if ((ftype->attrs & FIELD_ATTRIBUTE_INIT_ONLY) && (((addr = mono_aot_readonly_field_override (field)) != NULL) ||
10912                                                 (!context_used && !((cfg->opt & MONO_OPT_SHARED) || cfg->compile_aot) && vtable->initialized))) {
10913                                         int ro_type = ftype->type;
10914                                         if (!addr)
10915                                                 addr = (char*)mono_vtable_get_static_field_data (vtable) + field->offset;
10916                                         if (ro_type == MONO_TYPE_VALUETYPE && ftype->data.klass->enumtype) {
10917                                                 ro_type = mono_class_enum_basetype (ftype->data.klass)->type;
10918                                         }
10919
10920                                         GSHAREDVT_FAILURE (op);
10921
10922                                         /* printf ("RO-FIELD %s.%s:%s\n", klass->name_space, klass->name, mono_field_get_name (field));*/
10923                                         is_const = TRUE;
10924                                         switch (ro_type) {
10925                                         case MONO_TYPE_BOOLEAN:
10926                                         case MONO_TYPE_U1:
10927                                                 EMIT_NEW_ICONST (cfg, *sp, *((guint8 *)addr));
10928                                                 sp++;
10929                                                 break;
10930                                         case MONO_TYPE_I1:
10931                                                 EMIT_NEW_ICONST (cfg, *sp, *((gint8 *)addr));
10932                                                 sp++;
10933                                                 break;                                          
10934                                         case MONO_TYPE_CHAR:
10935                                         case MONO_TYPE_U2:
10936                                                 EMIT_NEW_ICONST (cfg, *sp, *((guint16 *)addr));
10937                                                 sp++;
10938                                                 break;
10939                                         case MONO_TYPE_I2:
10940                                                 EMIT_NEW_ICONST (cfg, *sp, *((gint16 *)addr));
10941                                                 sp++;
10942                                                 break;
10943                                                 break;
10944                                         case MONO_TYPE_I4:
10945                                                 EMIT_NEW_ICONST (cfg, *sp, *((gint32 *)addr));
10946                                                 sp++;
10947                                                 break;                                          
10948                                         case MONO_TYPE_U4:
10949                                                 EMIT_NEW_ICONST (cfg, *sp, *((guint32 *)addr));
10950                                                 sp++;
10951                                                 break;
10952                                         case MONO_TYPE_I:
10953                                         case MONO_TYPE_U:
10954                                         case MONO_TYPE_PTR:
10955                                         case MONO_TYPE_FNPTR:
10956                                                 EMIT_NEW_PCONST (cfg, *sp, *((gpointer *)addr));
10957                                                 type_to_eval_stack_type ((cfg), field->type, *sp);
10958                                                 sp++;
10959                                                 break;
10960                                         case MONO_TYPE_STRING:
10961                                         case MONO_TYPE_OBJECT:
10962                                         case MONO_TYPE_CLASS:
10963                                         case MONO_TYPE_SZARRAY:
10964                                         case MONO_TYPE_ARRAY:
10965                                                 if (!mono_gc_is_moving ()) {
10966                                                         EMIT_NEW_PCONST (cfg, *sp, *((gpointer *)addr));
10967                                                         type_to_eval_stack_type ((cfg), field->type, *sp);
10968                                                         sp++;
10969                                                 } else {
10970                                                         is_const = FALSE;
10971                                                 }
10972                                                 break;
10973                                         case MONO_TYPE_I8:
10974                                         case MONO_TYPE_U8:
10975                                                 EMIT_NEW_I8CONST (cfg, *sp, *((gint64 *)addr));
10976                                                 sp++;
10977                                                 break;
10978                                         case MONO_TYPE_R4:
10979                                         case MONO_TYPE_R8:
10980                                         case MONO_TYPE_VALUETYPE:
10981                                         default:
10982                                                 is_const = FALSE;
10983                                                 break;
10984                                         }
10985                                 }
10986
10987                                 if (!is_const) {
10988                                         MonoInst *load;
10989
10990                                         CHECK_STACK_OVF (1);
10991
10992                                         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, load, field->type, ins->dreg, 0);
10993                                         load->flags |= ins_flag;
10994                                         ins_flag = 0;
10995                                         *sp++ = load;
10996                                 }
10997                         }
10998
10999                         if ((op == CEE_LDFLD || op == CEE_LDSFLD) && (ins_flag & MONO_INST_VOLATILE)) {
11000                                 /* Volatile loads have acquire semantics, see 12.6.7 in Ecma 335 */
11001                                 mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_ACQ);
11002                         }
11003
11004                         ins_flag = 0;
11005                         ip += 5;
11006                         break;
11007                 }
11008                 case CEE_STOBJ:
11009                         CHECK_STACK (2);
11010                         sp -= 2;
11011                         CHECK_OPSIZE (5);
11012                         token = read32 (ip + 1);
11013                         klass = mini_get_class (method, token, generic_context);
11014                         CHECK_TYPELOAD (klass);
11015                         if (ins_flag & MONO_INST_VOLATILE) {
11016                                 /* Volatile stores have release semantics, see 12.6.7 in Ecma 335 */
11017                                 mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_REL);
11018                         }
11019                         /* FIXME: should check item at sp [1] is compatible with the type of the store. */
11020                         EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, sp [0]->dreg, 0, sp [1]->dreg);
11021                         ins->flags |= ins_flag;
11022                         if (cfg->gen_write_barriers && cfg->method->wrapper_type != MONO_WRAPPER_WRITE_BARRIER &&
11023                                 generic_class_is_reference_type (cfg, klass) && !MONO_INS_IS_PCONST_NULL (sp [1])) {
11024                                 /* insert call to write barrier */
11025                                 mini_emit_write_barrier (cfg, sp [0], sp [1]);
11026                         }
11027                         ins_flag = 0;
11028                         ip += 5;
11029                         inline_costs += 1;
11030                         break;
11031
11032                         /*
11033                          * Array opcodes
11034                          */
11035                 case CEE_NEWARR: {
11036                         MonoInst *len_ins;
11037                         const char *data_ptr;
11038                         int data_size = 0;
11039                         guint32 field_token;
11040
11041                         CHECK_STACK (1);
11042                         --sp;
11043
11044                         CHECK_OPSIZE (5);
11045                         token = read32 (ip + 1);
11046
11047                         klass = mini_get_class (method, token, generic_context);
11048                         CHECK_TYPELOAD (klass);
11049                         if (klass->byval_arg.type == MONO_TYPE_VOID)
11050                                 UNVERIFIED;
11051
11052                         context_used = mini_class_check_context_used (cfg, klass);
11053
11054                         if (sp [0]->type == STACK_I8 || (SIZEOF_VOID_P == 8 && sp [0]->type == STACK_PTR)) {
11055                                 MONO_INST_NEW (cfg, ins, OP_LCONV_TO_OVF_U4);
11056                                 ins->sreg1 = sp [0]->dreg;
11057                                 ins->type = STACK_I4;
11058                                 ins->dreg = alloc_ireg (cfg);
11059                                 MONO_ADD_INS (cfg->cbb, ins);
11060                                 *sp = mono_decompose_opcode (cfg, ins);
11061                         }
11062
11063                         if (context_used) {
11064                                 MonoInst *args [3];
11065                                 MonoClass *array_class = mono_array_class_get (klass, 1);
11066                                 MonoMethod *managed_alloc = mono_gc_get_managed_array_allocator (array_class);
11067
11068                                 /* FIXME: Use OP_NEWARR and decompose later to help abcrem */
11069
11070                                 /* vtable */
11071                                 args [0] = mini_emit_get_rgctx_klass (cfg, context_used,
11072                                         array_class, MONO_RGCTX_INFO_VTABLE);
11073                                 /* array len */
11074                                 args [1] = sp [0];
11075
11076                                 if (managed_alloc)
11077                                         ins = mono_emit_method_call (cfg, managed_alloc, args, NULL);
11078                                 else
11079                                         ins = mono_emit_jit_icall (cfg, ves_icall_array_new_specific, args);
11080                         } else {
11081                                 if (cfg->opt & MONO_OPT_SHARED) {
11082                                         /* Decompose now to avoid problems with references to the domainvar */
11083                                         MonoInst *iargs [3];
11084
11085                                         EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
11086                                         EMIT_NEW_CLASSCONST (cfg, iargs [1], klass);
11087                                         iargs [2] = sp [0];
11088
11089                                         ins = mono_emit_jit_icall (cfg, ves_icall_array_new, iargs);
11090                                 } else {
11091                                         /* Decompose later since it is needed by abcrem */
11092                                         MonoClass *array_type = mono_array_class_get (klass, 1);
11093                                         mono_class_vtable (cfg->domain, array_type);
11094                                         CHECK_TYPELOAD (array_type);
11095
11096                                         MONO_INST_NEW (cfg, ins, OP_NEWARR);
11097                                         ins->dreg = alloc_ireg_ref (cfg);
11098                                         ins->sreg1 = sp [0]->dreg;
11099                                         ins->inst_newa_class = klass;
11100                                         ins->type = STACK_OBJ;
11101                                         ins->klass = array_type;
11102                                         MONO_ADD_INS (cfg->cbb, ins);
11103                                         cfg->flags |= MONO_CFG_HAS_ARRAY_ACCESS;
11104                                         cfg->cbb->has_array_access = TRUE;
11105
11106                                         /* Needed so mono_emit_load_get_addr () gets called */
11107                                         mono_get_got_var (cfg);
11108                                 }
11109                         }
11110
11111                         len_ins = sp [0];
11112                         ip += 5;
11113                         *sp++ = ins;
11114                         inline_costs += 1;
11115
11116                         /* 
11117                          * we inline/optimize the initialization sequence if possible.
11118                          * we should also allocate the array as not cleared, since we spend as much time clearing to 0 as initializing
11119                          * for small sizes open code the memcpy
11120                          * ensure the rva field is big enough
11121                          */
11122                         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))) {
11123                                 MonoMethod *memcpy_method = mini_get_memcpy_method ();
11124                                 MonoInst *iargs [3];
11125                                 int add_reg = alloc_ireg_mp (cfg);
11126
11127                                 EMIT_NEW_BIALU_IMM (cfg, iargs [0], OP_PADD_IMM, add_reg, ins->dreg, MONO_STRUCT_OFFSET (MonoArray, vector));
11128                                 if (cfg->compile_aot) {
11129                                         EMIT_NEW_AOTCONST_TOKEN (cfg, iargs [1], MONO_PATCH_INFO_RVA, method->klass->image, GPOINTER_TO_UINT(field_token), STACK_PTR, NULL);
11130                                 } else {
11131                                         EMIT_NEW_PCONST (cfg, iargs [1], (char*)data_ptr);
11132                                 }
11133                                 EMIT_NEW_ICONST (cfg, iargs [2], data_size);
11134                                 mono_emit_method_call (cfg, memcpy_method, iargs, NULL);
11135                                 ip += 11;
11136                         }
11137
11138                         break;
11139                 }
11140                 case CEE_LDLEN:
11141                         CHECK_STACK (1);
11142                         --sp;
11143                         if (sp [0]->type != STACK_OBJ)
11144                                 UNVERIFIED;
11145
11146                         MONO_INST_NEW (cfg, ins, OP_LDLEN);
11147                         ins->dreg = alloc_preg (cfg);
11148                         ins->sreg1 = sp [0]->dreg;
11149                         ins->type = STACK_I4;
11150                         /* This flag will be inherited by the decomposition */
11151                         ins->flags |= MONO_INST_FAULT;
11152                         MONO_ADD_INS (cfg->cbb, ins);
11153                         cfg->flags |= MONO_CFG_HAS_ARRAY_ACCESS;
11154                         cfg->cbb->has_array_access = TRUE;
11155                         ip ++;
11156                         *sp++ = ins;
11157                         break;
11158                 case CEE_LDELEMA:
11159                         CHECK_STACK (2);
11160                         sp -= 2;
11161                         CHECK_OPSIZE (5);
11162                         if (sp [0]->type != STACK_OBJ)
11163                                 UNVERIFIED;
11164
11165                         cfg->flags |= MONO_CFG_HAS_LDELEMA;
11166
11167                         klass = mini_get_class (method, read32 (ip + 1), generic_context);
11168                         CHECK_TYPELOAD (klass);
11169                         /* we need to make sure that this array is exactly the type it needs
11170                          * to be for correctness. the wrappers are lax with their usage
11171                          * so we need to ignore them here
11172                          */
11173                         if (!klass->valuetype && method->wrapper_type == MONO_WRAPPER_NONE && !readonly) {
11174                                 MonoClass *array_class = mono_array_class_get (klass, 1);
11175                                 mini_emit_check_array_type (cfg, sp [0], array_class);
11176                                 CHECK_TYPELOAD (array_class);
11177                         }
11178
11179                         readonly = FALSE;
11180                         ins = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1], TRUE);
11181                         *sp++ = ins;
11182                         ip += 5;
11183                         break;
11184                 case CEE_LDELEM:
11185                 case CEE_LDELEM_I1:
11186                 case CEE_LDELEM_U1:
11187                 case CEE_LDELEM_I2:
11188                 case CEE_LDELEM_U2:
11189                 case CEE_LDELEM_I4:
11190                 case CEE_LDELEM_U4:
11191                 case CEE_LDELEM_I8:
11192                 case CEE_LDELEM_I:
11193                 case CEE_LDELEM_R4:
11194                 case CEE_LDELEM_R8:
11195                 case CEE_LDELEM_REF: {
11196                         MonoInst *addr;
11197
11198                         CHECK_STACK (2);
11199                         sp -= 2;
11200
11201                         if (*ip == CEE_LDELEM) {
11202                                 CHECK_OPSIZE (5);
11203                                 token = read32 (ip + 1);
11204                                 klass = mini_get_class (method, token, generic_context);
11205                                 CHECK_TYPELOAD (klass);
11206                                 mono_class_init (klass);
11207                         }
11208                         else
11209                                 klass = array_access_to_klass (*ip);
11210
11211                         if (sp [0]->type != STACK_OBJ)
11212                                 UNVERIFIED;
11213
11214                         cfg->flags |= MONO_CFG_HAS_LDELEMA;
11215
11216                         if (mini_is_gsharedvt_variable_klass (klass)) {
11217                                 // FIXME-VT: OP_ICONST optimization
11218                                 addr = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1], TRUE);
11219                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr->dreg, 0);
11220                                 ins->opcode = OP_LOADV_MEMBASE;
11221                         } else if (sp [1]->opcode == OP_ICONST) {
11222                                 int array_reg = sp [0]->dreg;
11223                                 int index_reg = sp [1]->dreg;
11224                                 int offset = (mono_class_array_element_size (klass) * sp [1]->inst_c0) + MONO_STRUCT_OFFSET (MonoArray, vector);
11225
11226                                 if (SIZEOF_REGISTER == 8 && COMPILE_LLVM (cfg))
11227                                         MONO_EMIT_NEW_UNALU (cfg, OP_ZEXT_I4, index_reg, index_reg);
11228
11229                                 MONO_EMIT_BOUNDS_CHECK (cfg, array_reg, MonoArray, max_length, index_reg);
11230                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, array_reg, offset);
11231                         } else {
11232                                 addr = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1], TRUE);
11233                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr->dreg, 0);
11234                         }
11235                         *sp++ = ins;
11236                         if (*ip == CEE_LDELEM)
11237                                 ip += 5;
11238                         else
11239                                 ++ip;
11240                         break;
11241                 }
11242                 case CEE_STELEM_I:
11243                 case CEE_STELEM_I1:
11244                 case CEE_STELEM_I2:
11245                 case CEE_STELEM_I4:
11246                 case CEE_STELEM_I8:
11247                 case CEE_STELEM_R4:
11248                 case CEE_STELEM_R8:
11249                 case CEE_STELEM_REF:
11250                 case CEE_STELEM: {
11251                         CHECK_STACK (3);
11252                         sp -= 3;
11253
11254                         cfg->flags |= MONO_CFG_HAS_LDELEMA;
11255
11256                         if (*ip == CEE_STELEM) {
11257                                 CHECK_OPSIZE (5);
11258                                 token = read32 (ip + 1);
11259                                 klass = mini_get_class (method, token, generic_context);
11260                                 CHECK_TYPELOAD (klass);
11261                                 mono_class_init (klass);
11262                         }
11263                         else
11264                                 klass = array_access_to_klass (*ip);
11265
11266                         if (sp [0]->type != STACK_OBJ)
11267                                 UNVERIFIED;
11268
11269                         emit_array_store (cfg, klass, sp, TRUE);
11270
11271                         if (*ip == CEE_STELEM)
11272                                 ip += 5;
11273                         else
11274                                 ++ip;
11275                         inline_costs += 1;
11276                         break;
11277                 }
11278                 case CEE_CKFINITE: {
11279                         CHECK_STACK (1);
11280                         --sp;
11281
11282                         if (cfg->llvm_only) {
11283                                 MonoInst *iargs [1];
11284
11285                                 iargs [0] = sp [0];
11286                                 *sp++ = mono_emit_jit_icall (cfg, mono_ckfinite, iargs);
11287                         } else  {
11288                                 MONO_INST_NEW (cfg, ins, OP_CKFINITE);
11289                                 ins->sreg1 = sp [0]->dreg;
11290                                 ins->dreg = alloc_freg (cfg);
11291                                 ins->type = STACK_R8;
11292                                 MONO_ADD_INS (cfg->cbb, ins);
11293
11294                                 *sp++ = mono_decompose_opcode (cfg, ins);
11295                         }
11296
11297                         ++ip;
11298                         break;
11299                 }
11300                 case CEE_REFANYVAL: {
11301                         MonoInst *src_var, *src;
11302
11303                         int klass_reg = alloc_preg (cfg);
11304                         int dreg = alloc_preg (cfg);
11305
11306                         GSHAREDVT_FAILURE (*ip);
11307
11308                         CHECK_STACK (1);
11309                         MONO_INST_NEW (cfg, ins, *ip);
11310                         --sp;
11311                         CHECK_OPSIZE (5);
11312                         klass = mini_get_class (method, read32 (ip + 1), generic_context);
11313                         CHECK_TYPELOAD (klass);
11314
11315                         context_used = mini_class_check_context_used (cfg, klass);
11316
11317                         // FIXME:
11318                         src_var = get_vreg_to_inst (cfg, sp [0]->dreg);
11319                         if (!src_var)
11320                                 src_var = mono_compile_create_var_for_vreg (cfg, &mono_defaults.typed_reference_class->byval_arg, OP_LOCAL, sp [0]->dreg);
11321                         EMIT_NEW_VARLOADA (cfg, src, src_var, src_var->inst_vtype);
11322                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, src->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, klass));
11323
11324                         if (context_used) {
11325                                 MonoInst *klass_ins;
11326
11327                                 klass_ins = mini_emit_get_rgctx_klass (cfg, context_used,
11328                                                 klass, MONO_RGCTX_INFO_KLASS);
11329
11330                                 // FIXME:
11331                                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, klass_reg, klass_ins->dreg);
11332                                 MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "InvalidCastException");
11333                         } else {
11334                                 mini_emit_class_check (cfg, klass_reg, klass);
11335                         }
11336                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, dreg, src->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, value));
11337                         ins->type = STACK_MP;
11338                         ins->klass = klass;
11339                         *sp++ = ins;
11340                         ip += 5;
11341                         break;
11342                 }
11343                 case CEE_MKREFANY: {
11344                         MonoInst *loc, *addr;
11345
11346                         GSHAREDVT_FAILURE (*ip);
11347
11348                         CHECK_STACK (1);
11349                         MONO_INST_NEW (cfg, ins, *ip);
11350                         --sp;
11351                         CHECK_OPSIZE (5);
11352                         klass = mini_get_class (method, read32 (ip + 1), generic_context);
11353                         CHECK_TYPELOAD (klass);
11354
11355                         context_used = mini_class_check_context_used (cfg, klass);
11356
11357                         loc = mono_compile_create_var (cfg, &mono_defaults.typed_reference_class->byval_arg, OP_LOCAL);
11358                         EMIT_NEW_TEMPLOADA (cfg, addr, loc->inst_c0);
11359
11360                         if (context_used) {
11361                                 MonoInst *const_ins;
11362                                 int type_reg = alloc_preg (cfg);
11363
11364                                 const_ins = mini_emit_get_rgctx_klass (cfg, context_used, klass, MONO_RGCTX_INFO_KLASS);
11365                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, klass), const_ins->dreg);
11366                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ADD_IMM, type_reg, const_ins->dreg, MONO_STRUCT_OFFSET (MonoClass, byval_arg));
11367                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, type), type_reg);
11368                         } else {
11369                                 int const_reg = alloc_preg (cfg);
11370                                 int type_reg = alloc_preg (cfg);
11371
11372                                 MONO_EMIT_NEW_CLASSCONST (cfg, const_reg, klass);
11373                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, klass), const_reg);
11374                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ADD_IMM, type_reg, const_reg, MONO_STRUCT_OFFSET (MonoClass, byval_arg));
11375                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, type), type_reg);
11376                         }
11377                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, value), sp [0]->dreg);
11378
11379                         EMIT_NEW_TEMPLOAD (cfg, ins, loc->inst_c0);
11380                         ins->type = STACK_VTYPE;
11381                         ins->klass = mono_defaults.typed_reference_class;
11382                         *sp++ = ins;
11383                         ip += 5;
11384                         break;
11385                 }
11386                 case CEE_LDTOKEN: {
11387                         gpointer handle;
11388                         MonoClass *handle_class;
11389
11390                         CHECK_STACK_OVF (1);
11391
11392                         CHECK_OPSIZE (5);
11393                         n = read32 (ip + 1);
11394
11395                         if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD ||
11396                                         method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED) {
11397                                 handle = mono_method_get_wrapper_data (method, n);
11398                                 handle_class = (MonoClass *)mono_method_get_wrapper_data (method, n + 1);
11399                                 if (handle_class == mono_defaults.typehandle_class)
11400                                         handle = &((MonoClass*)handle)->byval_arg;
11401                         }
11402                         else {
11403                                 handle = mono_ldtoken_checked (image, n, &handle_class, generic_context, &cfg->error);
11404                                 CHECK_CFG_ERROR;
11405                         }
11406                         if (!handle)
11407                                 LOAD_ERROR;
11408                         mono_class_init (handle_class);
11409                         if (cfg->gshared) {
11410                                 if (mono_metadata_token_table (n) == MONO_TABLE_TYPEDEF ||
11411                                                 mono_metadata_token_table (n) == MONO_TABLE_TYPEREF) {
11412                                         /* This case handles ldtoken
11413                                            of an open type, like for
11414                                            typeof(Gen<>). */
11415                                         context_used = 0;
11416                                 } else if (handle_class == mono_defaults.typehandle_class) {
11417                                         context_used = mini_class_check_context_used (cfg, mono_class_from_mono_type ((MonoType *)handle));
11418                                 } else if (handle_class == mono_defaults.fieldhandle_class)
11419                                         context_used = mini_class_check_context_used (cfg, ((MonoClassField*)handle)->parent);
11420                                 else if (handle_class == mono_defaults.methodhandle_class)
11421                                         context_used = mini_method_check_context_used (cfg, (MonoMethod *)handle);
11422                                 else
11423                                         g_assert_not_reached ();
11424                         }
11425
11426                         if ((cfg->opt & MONO_OPT_SHARED) &&
11427                                         method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD &&
11428                                         method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED) {
11429                                 MonoInst *addr, *vtvar, *iargs [3];
11430                                 int method_context_used;
11431
11432                                 method_context_used = mini_method_check_context_used (cfg, method);
11433
11434                                 vtvar = mono_compile_create_var (cfg, &handle_class->byval_arg, OP_LOCAL); 
11435
11436                                 EMIT_NEW_IMAGECONST (cfg, iargs [0], image);
11437                                 EMIT_NEW_ICONST (cfg, iargs [1], n);
11438                                 if (method_context_used) {
11439                                         iargs [2] = emit_get_rgctx_method (cfg, method_context_used,
11440                                                 method, MONO_RGCTX_INFO_METHOD);
11441                                         ins = mono_emit_jit_icall (cfg, mono_ldtoken_wrapper_generic_shared, iargs);
11442                                 } else {
11443                                         EMIT_NEW_PCONST (cfg, iargs [2], generic_context);
11444                                         ins = mono_emit_jit_icall (cfg, mono_ldtoken_wrapper, iargs);
11445                                 }
11446                                 EMIT_NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
11447
11448                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, addr->dreg, 0, ins->dreg);
11449
11450                                 EMIT_NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
11451                         } else {
11452                                 if ((ip + 5 < end) && ip_in_bb (cfg, cfg->cbb, ip + 5) && 
11453                                         ((ip [5] == CEE_CALL) || (ip [5] == CEE_CALLVIRT)) && 
11454                                         (cmethod = mini_get_method (cfg, method, read32 (ip + 6), NULL, generic_context)) &&
11455                                         (cmethod->klass == mono_defaults.systemtype_class) &&
11456                                         (strcmp (cmethod->name, "GetTypeFromHandle") == 0)) {
11457                                         MonoClass *tclass = mono_class_from_mono_type ((MonoType *)handle);
11458
11459                                         mono_class_init (tclass);
11460                                         if (context_used) {
11461                                                 ins = mini_emit_get_rgctx_klass (cfg, context_used,
11462                                                         tclass, MONO_RGCTX_INFO_REFLECTION_TYPE);
11463                                         } else if (cfg->compile_aot) {
11464                                                 if (method->wrapper_type) {
11465                                                         error_init (&error); //got to do it since there are multiple conditionals below
11466                                                         if (mono_class_get_checked (tclass->image, tclass->type_token, &error) == tclass && !generic_context) {
11467                                                                 /* Special case for static synchronized wrappers */
11468                                                                 EMIT_NEW_TYPE_FROM_HANDLE_CONST (cfg, ins, tclass->image, tclass->type_token, generic_context);
11469                                                         } else {
11470                                                                 mono_error_cleanup (&error); /* FIXME don't swallow the error */
11471                                                                 /* FIXME: n is not a normal token */
11472                                                                 DISABLE_AOT (cfg);
11473                                                                 EMIT_NEW_PCONST (cfg, ins, NULL);
11474                                                         }
11475                                                 } else {
11476                                                         EMIT_NEW_TYPE_FROM_HANDLE_CONST (cfg, ins, image, n, generic_context);
11477                                                 }
11478                                         } else {
11479                                                 MonoReflectionType *rt = mono_type_get_object_checked (cfg->domain, (MonoType *)handle, &cfg->error);
11480                                                 CHECK_CFG_ERROR;
11481                                                 EMIT_NEW_PCONST (cfg, ins, rt);
11482                                         }
11483                                         ins->type = STACK_OBJ;
11484                                         ins->klass = cmethod->klass;
11485                                         ip += 5;
11486                                 } else {
11487                                         MonoInst *addr, *vtvar;
11488
11489                                         vtvar = mono_compile_create_var (cfg, &handle_class->byval_arg, OP_LOCAL);
11490
11491                                         if (context_used) {
11492                                                 if (handle_class == mono_defaults.typehandle_class) {
11493                                                         ins = mini_emit_get_rgctx_klass (cfg, context_used,
11494                                                                         mono_class_from_mono_type ((MonoType *)handle),
11495                                                                         MONO_RGCTX_INFO_TYPE);
11496                                                 } else if (handle_class == mono_defaults.methodhandle_class) {
11497                                                         ins = emit_get_rgctx_method (cfg, context_used,
11498                                                                         (MonoMethod *)handle, MONO_RGCTX_INFO_METHOD);
11499                                                 } else if (handle_class == mono_defaults.fieldhandle_class) {
11500                                                         ins = emit_get_rgctx_field (cfg, context_used,
11501                                                                         (MonoClassField *)handle, MONO_RGCTX_INFO_CLASS_FIELD);
11502                                                 } else {
11503                                                         g_assert_not_reached ();
11504                                                 }
11505                                         } else if (cfg->compile_aot) {
11506                                                 EMIT_NEW_LDTOKENCONST (cfg, ins, image, n, generic_context);
11507                                         } else {
11508                                                 EMIT_NEW_PCONST (cfg, ins, handle);
11509                                         }
11510                                         EMIT_NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
11511                                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, addr->dreg, 0, ins->dreg);
11512                                         EMIT_NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
11513                                 }
11514                         }
11515
11516                         *sp++ = ins;
11517                         ip += 5;
11518                         break;
11519                 }
11520                 case CEE_THROW:
11521                         CHECK_STACK (1);
11522                         if (sp [-1]->type != STACK_OBJ)
11523                                 UNVERIFIED;
11524
11525                         MONO_INST_NEW (cfg, ins, OP_THROW);
11526                         --sp;
11527                         ins->sreg1 = sp [0]->dreg;
11528                         ip++;
11529                         cfg->cbb->out_of_line = TRUE;
11530                         MONO_ADD_INS (cfg->cbb, ins);
11531                         MONO_INST_NEW (cfg, ins, OP_NOT_REACHED);
11532                         MONO_ADD_INS (cfg->cbb, ins);
11533                         sp = stack_start;
11534                         
11535                         link_bblock (cfg, cfg->cbb, end_bblock);
11536                         start_new_bblock = 1;
11537                         /* This can complicate code generation for llvm since the return value might not be defined */
11538                         if (COMPILE_LLVM (cfg))
11539                                 INLINE_FAILURE ("throw");
11540                         break;
11541                 case CEE_ENDFINALLY:
11542                         if (!ip_in_finally_clause (cfg, ip - header->code))
11543                                 UNVERIFIED;
11544                         /* mono_save_seq_point_info () depends on this */
11545                         if (sp != stack_start)
11546                                 emit_seq_point (cfg, method, ip, FALSE, FALSE);
11547                         MONO_INST_NEW (cfg, ins, OP_ENDFINALLY);
11548                         MONO_ADD_INS (cfg->cbb, ins);
11549                         ip++;
11550                         start_new_bblock = 1;
11551
11552                         /*
11553                          * Control will leave the method so empty the stack, otherwise
11554                          * the next basic block will start with a nonempty stack.
11555                          */
11556                         while (sp != stack_start) {
11557                                 sp--;
11558                         }
11559                         break;
11560                 case CEE_LEAVE:
11561                 case CEE_LEAVE_S: {
11562                         GList *handlers;
11563
11564                         if (*ip == CEE_LEAVE) {
11565                                 CHECK_OPSIZE (5);
11566                                 target = ip + 5 + (gint32)read32(ip + 1);
11567                         } else {
11568                                 CHECK_OPSIZE (2);
11569                                 target = ip + 2 + (signed char)(ip [1]);
11570                         }
11571
11572                         /* empty the stack */
11573                         while (sp != stack_start) {
11574                                 sp--;
11575                         }
11576
11577                         /* 
11578                          * If this leave statement is in a catch block, check for a
11579                          * pending exception, and rethrow it if necessary.
11580                          * We avoid doing this in runtime invoke wrappers, since those are called
11581                          * by native code which excepts the wrapper to catch all exceptions.
11582                          */
11583                         for (i = 0; i < header->num_clauses; ++i) {
11584                                 MonoExceptionClause *clause = &header->clauses [i];
11585
11586                                 /* 
11587                                  * Use <= in the final comparison to handle clauses with multiple
11588                                  * leave statements, like in bug #78024.
11589                                  * The ordering of the exception clauses guarantees that we find the
11590                                  * innermost clause.
11591                                  */
11592                                 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) {
11593                                         MonoInst *exc_ins;
11594                                         MonoBasicBlock *dont_throw;
11595
11596                                         /*
11597                                           MonoInst *load;
11598
11599                                           NEW_TEMPLOAD (cfg, load, mono_find_exvar_for_offset (cfg, clause->handler_offset)->inst_c0);
11600                                         */
11601
11602                                         exc_ins = mono_emit_jit_icall (cfg, mono_thread_get_undeniable_exception, NULL);
11603
11604                                         NEW_BBLOCK (cfg, dont_throw);
11605
11606                                         /*
11607                                          * Currently, we always rethrow the abort exception, despite the 
11608                                          * fact that this is not correct. See thread6.cs for an example. 
11609                                          * But propagating the abort exception is more important than 
11610                                          * getting the sematics right.
11611                                          */
11612                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, exc_ins->dreg, 0);
11613                                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, dont_throw);
11614                                         MONO_EMIT_NEW_UNALU (cfg, OP_THROW, -1, exc_ins->dreg);
11615
11616                                         MONO_START_BB (cfg, dont_throw);
11617                                 }
11618                         }
11619
11620 #ifdef ENABLE_LLVM
11621                         cfg->cbb->try_end = (intptr_t)(ip - header->code);
11622 #endif
11623
11624                         if ((handlers = mono_find_final_block (cfg, ip, target, MONO_EXCEPTION_CLAUSE_FINALLY))) {
11625                                 GList *tmp;
11626                                 MonoExceptionClause *clause;
11627
11628                                 for (tmp = handlers; tmp; tmp = tmp->next) {
11629                                         clause = (MonoExceptionClause *)tmp->data;
11630                                         tblock = cfg->cil_offset_to_bb [clause->handler_offset];
11631                                         g_assert (tblock);
11632                                         link_bblock (cfg, cfg->cbb, tblock);
11633                                         MONO_INST_NEW (cfg, ins, OP_CALL_HANDLER);
11634                                         ins->inst_target_bb = tblock;
11635                                         ins->inst_eh_block = clause;
11636                                         MONO_ADD_INS (cfg->cbb, ins);
11637                                         cfg->cbb->has_call_handler = 1;
11638                                         if (COMPILE_LLVM (cfg)) {
11639                                                 MonoBasicBlock *target_bb;
11640
11641                                                 /* 
11642                                                  * Link the finally bblock with the target, since it will
11643                                                  * conceptually branch there.
11644                                                  */
11645                                                 GET_BBLOCK (cfg, tblock, cfg->cil_start + clause->handler_offset + clause->handler_len - 1);
11646                                                 GET_BBLOCK (cfg, target_bb, target);
11647                                                 link_bblock (cfg, tblock, target_bb);
11648                                         }
11649                                 }
11650                                 g_list_free (handlers);
11651                         } 
11652
11653                         MONO_INST_NEW (cfg, ins, OP_BR);
11654                         MONO_ADD_INS (cfg->cbb, ins);
11655                         GET_BBLOCK (cfg, tblock, target);
11656                         link_bblock (cfg, cfg->cbb, tblock);
11657                         ins->inst_target_bb = tblock;
11658
11659                         start_new_bblock = 1;
11660
11661                         if (*ip == CEE_LEAVE)
11662                                 ip += 5;
11663                         else
11664                                 ip += 2;
11665
11666                         break;
11667                 }
11668
11669                         /*
11670                          * Mono specific opcodes
11671                          */
11672                 case MONO_CUSTOM_PREFIX: {
11673
11674                         g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
11675
11676                         CHECK_OPSIZE (2);
11677                         switch (ip [1]) {
11678                         case CEE_MONO_ICALL: {
11679                                 gpointer func;
11680                                 MonoJitICallInfo *info;
11681
11682                                 token = read32 (ip + 2);
11683                                 func = mono_method_get_wrapper_data (method, token);
11684                                 info = mono_find_jit_icall_by_addr (func);
11685                                 if (!info)
11686                                         g_error ("Could not find icall address in wrapper %s", mono_method_full_name (method, 1));
11687                                 g_assert (info);
11688
11689                                 CHECK_STACK (info->sig->param_count);
11690                                 sp -= info->sig->param_count;
11691
11692                                 ins = mono_emit_jit_icall (cfg, info->func, sp);
11693                                 if (!MONO_TYPE_IS_VOID (info->sig->ret))
11694                                         *sp++ = ins;
11695
11696                                 ip += 6;
11697                                 inline_costs += 10 * num_calls++;
11698
11699                                 break;
11700                         }
11701                         case CEE_MONO_LDPTR_CARD_TABLE:
11702                         case CEE_MONO_LDPTR_NURSERY_START:
11703                         case CEE_MONO_LDPTR_NURSERY_BITS:
11704                         case CEE_MONO_LDPTR_INT_REQ_FLAG: {
11705                                 CHECK_STACK_OVF (1);
11706
11707                                 switch (ip [1]) {
11708                                         case CEE_MONO_LDPTR_CARD_TABLE:
11709                                                 ins = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_GC_CARD_TABLE_ADDR, NULL);
11710                                                 break;
11711                                         case CEE_MONO_LDPTR_NURSERY_START:
11712                                                 ins = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_GC_NURSERY_START, NULL);
11713                                                 break;
11714                                         case CEE_MONO_LDPTR_NURSERY_BITS:
11715                                                 ins = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_GC_NURSERY_BITS, NULL);
11716                                                 break;
11717                                         case CEE_MONO_LDPTR_INT_REQ_FLAG:
11718                                                 ins = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG, NULL);
11719                                                 break;
11720                                 }
11721
11722                                 *sp++ = ins;
11723                                 ip += 2;
11724                                 inline_costs += 10 * num_calls++;
11725                                 break;
11726                         }
11727                         case CEE_MONO_LDPTR: {
11728                                 gpointer ptr;
11729
11730                                 CHECK_STACK_OVF (1);
11731                                 CHECK_OPSIZE (6);
11732                                 token = read32 (ip + 2);
11733
11734                                 ptr = mono_method_get_wrapper_data (method, token);
11735                                 EMIT_NEW_PCONST (cfg, ins, ptr);
11736                                 *sp++ = ins;
11737                                 ip += 6;
11738                                 inline_costs += 10 * num_calls++;
11739                                 /* Can't embed random pointers into AOT code */
11740                                 DISABLE_AOT (cfg);
11741                                 break;
11742                         }
11743                         case CEE_MONO_JIT_ICALL_ADDR: {
11744                                 MonoJitICallInfo *callinfo;
11745                                 gpointer ptr;
11746
11747                                 CHECK_STACK_OVF (1);
11748                                 CHECK_OPSIZE (6);
11749                                 token = read32 (ip + 2);
11750
11751                                 ptr = mono_method_get_wrapper_data (method, token);
11752                                 callinfo = mono_find_jit_icall_by_addr (ptr);
11753                                 g_assert (callinfo);
11754                                 EMIT_NEW_JIT_ICALL_ADDRCONST (cfg, ins, (char*)callinfo->name);
11755                                 *sp++ = ins;
11756                                 ip += 6;
11757                                 inline_costs += 10 * num_calls++;
11758                                 break;
11759                         }
11760                         case CEE_MONO_ICALL_ADDR: {
11761                                 MonoMethod *cmethod;
11762                                 gpointer ptr;
11763
11764                                 CHECK_STACK_OVF (1);
11765                                 CHECK_OPSIZE (6);
11766                                 token = read32 (ip + 2);
11767
11768                                 cmethod = (MonoMethod *)mono_method_get_wrapper_data (method, token);
11769
11770                                 if (cfg->compile_aot) {
11771                                         if (cfg->direct_pinvoke && ip + 6 < end && (ip [6] == CEE_POP)) {
11772                                                 /*
11773                                                  * This is generated by emit_native_wrapper () to resolve the pinvoke address
11774                                                  * before the call, its not needed when using direct pinvoke.
11775                                                  * This is not an optimization, but its used to avoid looking up pinvokes
11776                                                  * on platforms which don't support dlopen ().
11777                                                  */
11778                                                 EMIT_NEW_PCONST (cfg, ins, NULL);
11779                                         } else {
11780                                                 EMIT_NEW_AOTCONST (cfg, ins, MONO_PATCH_INFO_ICALL_ADDR, cmethod);
11781                                         }
11782                                 } else {
11783                                         ptr = mono_lookup_internal_call (cmethod);
11784                                         g_assert (ptr);
11785                                         EMIT_NEW_PCONST (cfg, ins, ptr);
11786                                 }
11787                                 *sp++ = ins;
11788                                 ip += 6;
11789                                 break;
11790                         }
11791                         case CEE_MONO_VTADDR: {
11792                                 MonoInst *src_var, *src;
11793
11794                                 CHECK_STACK (1);
11795                                 --sp;
11796
11797                                 // FIXME:
11798                                 src_var = get_vreg_to_inst (cfg, sp [0]->dreg);
11799                                 EMIT_NEW_VARLOADA ((cfg), (src), src_var, src_var->inst_vtype);
11800                                 *sp++ = src;
11801                                 ip += 2;
11802                                 break;
11803                         }
11804                         case CEE_MONO_NEWOBJ: {
11805                                 MonoInst *iargs [2];
11806
11807                                 CHECK_STACK_OVF (1);
11808                                 CHECK_OPSIZE (6);
11809                                 token = read32 (ip + 2);
11810                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
11811                                 mono_class_init (klass);
11812                                 NEW_DOMAINCONST (cfg, iargs [0]);
11813                                 MONO_ADD_INS (cfg->cbb, iargs [0]);
11814                                 NEW_CLASSCONST (cfg, iargs [1], klass);
11815                                 MONO_ADD_INS (cfg->cbb, iargs [1]);
11816                                 *sp++ = mono_emit_jit_icall (cfg, ves_icall_object_new, iargs);
11817                                 ip += 6;
11818                                 inline_costs += 10 * num_calls++;
11819                                 break;
11820                         }
11821                         case CEE_MONO_OBJADDR:
11822                                 CHECK_STACK (1);
11823                                 --sp;
11824                                 MONO_INST_NEW (cfg, ins, OP_MOVE);
11825                                 ins->dreg = alloc_ireg_mp (cfg);
11826                                 ins->sreg1 = sp [0]->dreg;
11827                                 ins->type = STACK_MP;
11828                                 MONO_ADD_INS (cfg->cbb, ins);
11829                                 *sp++ = ins;
11830                                 ip += 2;
11831                                 break;
11832                         case CEE_MONO_LDNATIVEOBJ:
11833                                 /*
11834                                  * Similar to LDOBJ, but instead load the unmanaged 
11835                                  * representation of the vtype to the stack.
11836                                  */
11837                                 CHECK_STACK (1);
11838                                 CHECK_OPSIZE (6);
11839                                 --sp;
11840                                 token = read32 (ip + 2);
11841                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
11842                                 g_assert (klass->valuetype);
11843                                 mono_class_init (klass);
11844
11845                                 {
11846                                         MonoInst *src, *dest, *temp;
11847
11848                                         src = sp [0];
11849                                         temp = mono_compile_create_var (cfg, &klass->byval_arg, OP_LOCAL);
11850                                         temp->backend.is_pinvoke = 1;
11851                                         EMIT_NEW_TEMPLOADA (cfg, dest, temp->inst_c0);
11852                                         mini_emit_stobj (cfg, dest, src, klass, TRUE);
11853
11854                                         EMIT_NEW_TEMPLOAD (cfg, dest, temp->inst_c0);
11855                                         dest->type = STACK_VTYPE;
11856                                         dest->klass = klass;
11857
11858                                         *sp ++ = dest;
11859                                         ip += 6;
11860                                 }
11861                                 break;
11862                         case CEE_MONO_RETOBJ: {
11863                                 /*
11864                                  * Same as RET, but return the native representation of a vtype
11865                                  * to the caller.
11866                                  */
11867                                 g_assert (cfg->ret);
11868                                 g_assert (mono_method_signature (method)->pinvoke); 
11869                                 CHECK_STACK (1);
11870                                 --sp;
11871                                 
11872                                 CHECK_OPSIZE (6);
11873                                 token = read32 (ip + 2);    
11874                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
11875
11876                                 if (!cfg->vret_addr) {
11877                                         g_assert (cfg->ret_var_is_local);
11878
11879                                         EMIT_NEW_VARLOADA (cfg, ins, cfg->ret, cfg->ret->inst_vtype);
11880                                 } else {
11881                                         EMIT_NEW_RETLOADA (cfg, ins);
11882                                 }
11883                                 mini_emit_stobj (cfg, ins, sp [0], klass, TRUE);
11884                                 
11885                                 if (sp != stack_start)
11886                                         UNVERIFIED;
11887                                 
11888                                 MONO_INST_NEW (cfg, ins, OP_BR);
11889                                 ins->inst_target_bb = end_bblock;
11890                                 MONO_ADD_INS (cfg->cbb, ins);
11891                                 link_bblock (cfg, cfg->cbb, end_bblock);
11892                                 start_new_bblock = 1;
11893                                 ip += 6;
11894                                 break;
11895                         }
11896                         case CEE_MONO_SAVE_LMF:
11897                         case CEE_MONO_RESTORE_LMF:
11898                                 ip += 2;
11899                                 break;
11900                         case CEE_MONO_CLASSCONST:
11901                                 CHECK_STACK_OVF (1);
11902                                 CHECK_OPSIZE (6);
11903                                 token = read32 (ip + 2);
11904                                 EMIT_NEW_CLASSCONST (cfg, ins, mono_method_get_wrapper_data (method, token));
11905                                 *sp++ = ins;
11906                                 ip += 6;
11907                                 inline_costs += 10 * num_calls++;
11908                                 break;
11909                         case CEE_MONO_NOT_TAKEN:
11910                                 cfg->cbb->out_of_line = TRUE;
11911                                 ip += 2;
11912                                 break;
11913                         case CEE_MONO_TLS: {
11914                                 MonoTlsKey key;
11915
11916                                 CHECK_STACK_OVF (1);
11917                                 CHECK_OPSIZE (6);
11918                                 key = (MonoTlsKey)read32 (ip + 2);
11919                                 g_assert (key < TLS_KEY_NUM);
11920
11921                                 ins = mono_create_tls_get (cfg, key);
11922                                 g_assert (ins);
11923                                 ins->type = STACK_PTR;
11924                                 *sp++ = ins;
11925                                 ip += 6;
11926                                 break;
11927                         }
11928                         case CEE_MONO_DYN_CALL: {
11929                                 MonoCallInst *call;
11930
11931                                 /* It would be easier to call a trampoline, but that would put an
11932                                  * extra frame on the stack, confusing exception handling. So
11933                                  * implement it inline using an opcode for now.
11934                                  */
11935
11936                                 if (!cfg->dyn_call_var) {
11937                                         cfg->dyn_call_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
11938                                         /* prevent it from being register allocated */
11939                                         cfg->dyn_call_var->flags |= MONO_INST_VOLATILE;
11940                                 }
11941
11942                                 /* Has to use a call inst since it local regalloc expects it */
11943                                 MONO_INST_NEW_CALL (cfg, call, OP_DYN_CALL);
11944                                 ins = (MonoInst*)call;
11945                                 sp -= 2;
11946                                 ins->sreg1 = sp [0]->dreg;
11947                                 ins->sreg2 = sp [1]->dreg;
11948                                 MONO_ADD_INS (cfg->cbb, ins);
11949
11950                                 cfg->param_area = MAX (cfg->param_area, cfg->backend->dyn_call_param_area);
11951
11952                                 ip += 2;
11953                                 inline_costs += 10 * num_calls++;
11954
11955                                 break;
11956                         }
11957                         case CEE_MONO_MEMORY_BARRIER: {
11958                                 CHECK_OPSIZE (6);
11959                                 mini_emit_memory_barrier (cfg, (int)read32 (ip + 2));
11960                                 ip += 6;
11961                                 break;
11962                         }
11963                         case CEE_MONO_ATOMIC_STORE_I4: {
11964                                 g_assert (mono_arch_opcode_supported (OP_ATOMIC_STORE_I4));
11965
11966                                 CHECK_OPSIZE (6);
11967                                 CHECK_STACK (2);
11968                                 sp -= 2;
11969
11970                                 MONO_INST_NEW (cfg, ins, OP_ATOMIC_STORE_I4);
11971                                 ins->dreg = sp [0]->dreg;
11972                                 ins->sreg1 = sp [1]->dreg;
11973                                 ins->backend.memory_barrier_kind = (int) read32 (ip + 2);
11974                                 MONO_ADD_INS (cfg->cbb, ins);
11975
11976                                 ip += 6;
11977                                 break;
11978                         }
11979                         case CEE_MONO_JIT_ATTACH: {
11980                                 MonoInst *args [16], *domain_ins;
11981                                 MonoInst *ad_ins, *jit_tls_ins;
11982                                 MonoBasicBlock *next_bb = NULL, *call_bb = NULL;
11983
11984                                 g_assert (!mono_threads_is_coop_enabled ());
11985
11986                                 cfg->orig_domain_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
11987
11988                                 EMIT_NEW_PCONST (cfg, ins, NULL);
11989                                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, cfg->orig_domain_var->dreg, ins->dreg);
11990
11991                                 ad_ins = mono_create_tls_get (cfg, TLS_KEY_DOMAIN);
11992                                 jit_tls_ins = mono_create_tls_get (cfg, TLS_KEY_JIT_TLS);
11993
11994                                 if (ad_ins && jit_tls_ins) {
11995                                         NEW_BBLOCK (cfg, next_bb);
11996                                         NEW_BBLOCK (cfg, call_bb);
11997
11998                                         if (cfg->compile_aot) {
11999                                                 /* AOT code is only used in the root domain */
12000                                                 EMIT_NEW_PCONST (cfg, domain_ins, NULL);
12001                                         } else {
12002                                                 EMIT_NEW_PCONST (cfg, domain_ins, cfg->domain);
12003                                         }
12004                                         MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, ad_ins->dreg, domain_ins->dreg);
12005                                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, call_bb);
12006
12007                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, jit_tls_ins->dreg, 0);
12008                                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, call_bb);
12009
12010                                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, next_bb);
12011                                         MONO_START_BB (cfg, call_bb);
12012                                 }
12013
12014                                 /* AOT code is only used in the root domain */
12015                                 EMIT_NEW_PCONST (cfg, args [0], cfg->compile_aot ? NULL : cfg->domain);
12016                                 if (cfg->compile_aot) {
12017                                         MonoInst *addr;
12018
12019                                         /*
12020                                          * This is called on unattached threads, so it cannot go through the trampoline
12021                                          * infrastructure. Use an indirect call through a got slot initialized at load time
12022                                          * instead.
12023                                          */
12024                                         EMIT_NEW_AOTCONST (cfg, addr, MONO_PATCH_INFO_JIT_THREAD_ATTACH, NULL);
12025                                         ins = mini_emit_calli (cfg, helper_sig_jit_thread_attach, args, addr, NULL, NULL);
12026                                 } else {
12027                                         ins = mono_emit_jit_icall (cfg, mono_jit_thread_attach, args);
12028                                 }
12029                                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, cfg->orig_domain_var->dreg, ins->dreg);
12030
12031                                 if (next_bb)
12032                                         MONO_START_BB (cfg, next_bb);
12033
12034                                 ip += 2;
12035                                 break;
12036                         }
12037                         case CEE_MONO_JIT_DETACH: {
12038                                 MonoInst *args [16];
12039
12040                                 /* Restore the original domain */
12041                                 dreg = alloc_ireg (cfg);
12042                                 EMIT_NEW_UNALU (cfg, args [0], OP_MOVE, dreg, cfg->orig_domain_var->dreg);
12043                                 mono_emit_jit_icall (cfg, mono_jit_set_domain, args);
12044                                 ip += 2;
12045                                 break;
12046                         }
12047                         case CEE_MONO_CALLI_EXTRA_ARG: {
12048                                 MonoInst *addr;
12049                                 MonoMethodSignature *fsig;
12050                                 MonoInst *arg;
12051
12052                                 /*
12053                                  * This is the same as CEE_CALLI, but passes an additional argument
12054                                  * to the called method in llvmonly mode.
12055                                  * This is only used by delegate invoke wrappers to call the
12056                                  * actual delegate method.
12057                                  */
12058                                 g_assert (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE);
12059
12060                                 CHECK_OPSIZE (6);
12061                                 token = read32 (ip + 2);
12062
12063                                 ins = NULL;
12064
12065                                 cmethod = NULL;
12066                                 CHECK_STACK (1);
12067                                 --sp;
12068                                 addr = *sp;
12069                                 fsig = mini_get_signature (method, token, generic_context, &cfg->error);
12070                                 CHECK_CFG_ERROR;
12071
12072                                 if (cfg->llvm_only)
12073                                         cfg->signatures = g_slist_prepend_mempool (cfg->mempool, cfg->signatures, fsig);
12074
12075                                 n = fsig->param_count + fsig->hasthis + 1;
12076
12077                                 CHECK_STACK (n);
12078
12079                                 sp -= n;
12080                                 arg = sp [n - 1];
12081
12082                                 if (cfg->llvm_only) {
12083                                         /*
12084                                          * The lowest bit of 'arg' determines whenever the callee uses the gsharedvt
12085                                          * cconv. This is set by mono_init_delegate ().
12086                                          */
12087                                         if (cfg->gsharedvt && mini_is_gsharedvt_variable_signature (fsig)) {
12088                                                 MonoInst *callee = addr;
12089                                                 MonoInst *call, *localloc_ins;
12090                                                 MonoBasicBlock *is_gsharedvt_bb, *end_bb;
12091                                                 int low_bit_reg = alloc_preg (cfg);
12092
12093                                                 NEW_BBLOCK (cfg, is_gsharedvt_bb);
12094                                                 NEW_BBLOCK (cfg, end_bb);
12095
12096                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PAND_IMM, low_bit_reg, arg->dreg, 1);
12097                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, low_bit_reg, 0);
12098                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, is_gsharedvt_bb);
12099
12100                                                 /* Normal case: callee uses a normal cconv, have to add an out wrapper */
12101                                                 addr = emit_get_rgctx_sig (cfg, context_used,
12102                                                                                                    fsig, MONO_RGCTX_INFO_SIG_GSHAREDVT_OUT_TRAMPOLINE_CALLI);
12103                                                 /*
12104                                                  * ADDR points to a gsharedvt-out wrapper, have to pass <callee, arg> as an extra arg.
12105                                                  */
12106                                                 MONO_INST_NEW (cfg, ins, OP_LOCALLOC_IMM);
12107                                                 ins->dreg = alloc_preg (cfg);
12108                                                 ins->inst_imm = 2 * SIZEOF_VOID_P;
12109                                                 MONO_ADD_INS (cfg->cbb, ins);
12110                                                 localloc_ins = ins;
12111                                                 cfg->flags |= MONO_CFG_HAS_ALLOCA;
12112                                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, localloc_ins->dreg, 0, callee->dreg);
12113                                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, localloc_ins->dreg, SIZEOF_VOID_P, arg->dreg);
12114
12115                                                 call = emit_extra_arg_calli (cfg, fsig, sp, localloc_ins->dreg, addr);
12116                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
12117
12118                                                 /* Gsharedvt case: callee uses a gsharedvt cconv, no conversion is needed */
12119                                                 MONO_START_BB (cfg, is_gsharedvt_bb);
12120                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PXOR_IMM, arg->dreg, arg->dreg, 1);
12121                                                 ins = emit_extra_arg_calli (cfg, fsig, sp, arg->dreg, callee);
12122                                                 ins->dreg = call->dreg;
12123
12124                                                 MONO_START_BB (cfg, end_bb);
12125                                         } else {
12126                                                 /* Caller uses a normal calling conv */
12127
12128                                                 MonoInst *callee = addr;
12129                                                 MonoInst *call, *localloc_ins;
12130                                                 MonoBasicBlock *is_gsharedvt_bb, *end_bb;
12131                                                 int low_bit_reg = alloc_preg (cfg);
12132
12133                                                 NEW_BBLOCK (cfg, is_gsharedvt_bb);
12134                                                 NEW_BBLOCK (cfg, end_bb);
12135
12136                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PAND_IMM, low_bit_reg, arg->dreg, 1);
12137                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, low_bit_reg, 0);
12138                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, is_gsharedvt_bb);
12139
12140                                                 /* Normal case: callee uses a normal cconv, no conversion is needed */
12141                                                 call = emit_extra_arg_calli (cfg, fsig, sp, arg->dreg, callee);
12142                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
12143                                                 /* Gsharedvt case: callee uses a gsharedvt cconv, have to add an in wrapper */
12144                                                 MONO_START_BB (cfg, is_gsharedvt_bb);
12145                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PXOR_IMM, arg->dreg, arg->dreg, 1);
12146                                                 NEW_AOTCONST (cfg, addr, MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER, fsig);
12147                                                 MONO_ADD_INS (cfg->cbb, addr);
12148                                                 /*
12149                                                  * ADDR points to a gsharedvt-in wrapper, have to pass <callee, arg> as an extra arg.
12150                                                  */
12151                                                 MONO_INST_NEW (cfg, ins, OP_LOCALLOC_IMM);
12152                                                 ins->dreg = alloc_preg (cfg);
12153                                                 ins->inst_imm = 2 * SIZEOF_VOID_P;
12154                                                 MONO_ADD_INS (cfg->cbb, ins);
12155                                                 localloc_ins = ins;
12156                                                 cfg->flags |= MONO_CFG_HAS_ALLOCA;
12157                                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, localloc_ins->dreg, 0, callee->dreg);
12158                                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, localloc_ins->dreg, SIZEOF_VOID_P, arg->dreg);
12159
12160                                                 ins = emit_extra_arg_calli (cfg, fsig, sp, localloc_ins->dreg, addr);
12161                                                 ins->dreg = call->dreg;
12162                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
12163
12164                                                 MONO_START_BB (cfg, end_bb);
12165                                         }
12166                                 } else {
12167                                         /* Same as CEE_CALLI */
12168                                         if (cfg->gsharedvt && mini_is_gsharedvt_signature (fsig)) {
12169                                                 /*
12170                                                  * We pass the address to the gsharedvt trampoline in the rgctx reg
12171                                                  */
12172                                                 MonoInst *callee = addr;
12173
12174                                                 addr = emit_get_rgctx_sig (cfg, context_used,
12175                                                                                                    fsig, MONO_RGCTX_INFO_SIG_GSHAREDVT_OUT_TRAMPOLINE_CALLI);
12176                                                 ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, NULL, callee);
12177                                         } else {
12178                                                 ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
12179                                         }
12180                                 }
12181
12182                                 if (!MONO_TYPE_IS_VOID (fsig->ret))
12183                                         *sp++ = mono_emit_widen_call_res (cfg, ins, fsig);
12184
12185                                 CHECK_CFG_EXCEPTION;
12186
12187                                 ip += 6;
12188                                 ins_flag = 0;
12189                                 constrained_class = NULL;
12190                                 break;
12191                         }
12192                         case CEE_MONO_LDDOMAIN:
12193                                 CHECK_STACK_OVF (1);
12194                                 EMIT_NEW_PCONST (cfg, ins, cfg->compile_aot ? NULL : cfg->domain);
12195                                 ip += 2;
12196                                 *sp++ = ins;
12197                                 break;
12198                         case CEE_MONO_GET_LAST_ERROR:
12199                                 CHECK_OPSIZE (2);
12200                                 CHECK_STACK_OVF (1);
12201
12202                                 MONO_INST_NEW (cfg, ins, OP_GET_LAST_ERROR);
12203                                 ins->dreg = alloc_dreg (cfg, STACK_I4);
12204                                 ins->type = STACK_I4;
12205                                 MONO_ADD_INS (cfg->cbb, ins);
12206
12207                                 ip += 2;
12208                                 *sp++ = ins;
12209                                 break;
12210                         case CEE_MONO_GET_RGCTX_ARG:
12211                                 CHECK_OPSIZE (2);
12212                                 CHECK_STACK_OVF (1);
12213
12214                                 mono_create_rgctx_var (cfg);
12215
12216                                 MONO_INST_NEW (cfg, ins, OP_MOVE);
12217                                 ins->dreg = alloc_dreg (cfg, STACK_PTR);
12218                                 ins->sreg1 = cfg->rgctx_var->dreg;
12219                                 ins->type = STACK_PTR;
12220                                 MONO_ADD_INS (cfg->cbb, ins);
12221
12222                                 ip += 2;
12223                                 *sp++ = ins;
12224                                 break;
12225                         default:
12226                                 g_error ("opcode 0x%02x 0x%02x not handled", MONO_CUSTOM_PREFIX, ip [1]);
12227                                 break;
12228                         }
12229                         break;
12230                 }
12231
12232                 case CEE_PREFIX1: {
12233                         CHECK_OPSIZE (2);
12234                         switch (ip [1]) {
12235                         case CEE_ARGLIST: {
12236                                 /* somewhat similar to LDTOKEN */
12237                                 MonoInst *addr, *vtvar;
12238                                 CHECK_STACK_OVF (1);
12239                                 vtvar = mono_compile_create_var (cfg, &mono_defaults.argumenthandle_class->byval_arg, OP_LOCAL); 
12240
12241                                 EMIT_NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
12242                                 EMIT_NEW_UNALU (cfg, ins, OP_ARGLIST, -1, addr->dreg);
12243
12244                                 EMIT_NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
12245                                 ins->type = STACK_VTYPE;
12246                                 ins->klass = mono_defaults.argumenthandle_class;
12247                                 *sp++ = ins;
12248                                 ip += 2;
12249                                 break;
12250                         }
12251                         case CEE_CEQ:
12252                         case CEE_CGT:
12253                         case CEE_CGT_UN:
12254                         case CEE_CLT:
12255                         case CEE_CLT_UN: {
12256                                 MonoInst *cmp, *arg1, *arg2;
12257
12258                                 CHECK_STACK (2);
12259                                 sp -= 2;
12260                                 arg1 = sp [0];
12261                                 arg2 = sp [1];
12262
12263                                 /*
12264                                  * The following transforms:
12265                                  *    CEE_CEQ    into OP_CEQ
12266                                  *    CEE_CGT    into OP_CGT
12267                                  *    CEE_CGT_UN into OP_CGT_UN
12268                                  *    CEE_CLT    into OP_CLT
12269                                  *    CEE_CLT_UN into OP_CLT_UN
12270                                  */
12271                                 MONO_INST_NEW (cfg, cmp, (OP_CEQ - CEE_CEQ) + ip [1]);
12272
12273                                 MONO_INST_NEW (cfg, ins, cmp->opcode);
12274                                 cmp->sreg1 = arg1->dreg;
12275                                 cmp->sreg2 = arg2->dreg;
12276                                 type_from_op (cfg, cmp, arg1, arg2);
12277                                 CHECK_TYPE (cmp);
12278                                 add_widen_op (cfg, cmp, &arg1, &arg2);
12279                                 if ((arg1->type == STACK_I8) || ((SIZEOF_VOID_P == 8) && ((arg1->type == STACK_PTR) || (arg1->type == STACK_OBJ) || (arg1->type == STACK_MP))))
12280                                         cmp->opcode = OP_LCOMPARE;
12281                                 else if (arg1->type == STACK_R4)
12282                                         cmp->opcode = OP_RCOMPARE;
12283                                 else if (arg1->type == STACK_R8)
12284                                         cmp->opcode = OP_FCOMPARE;
12285                                 else
12286                                         cmp->opcode = OP_ICOMPARE;
12287                                 MONO_ADD_INS (cfg->cbb, cmp);
12288                                 ins->type = STACK_I4;
12289                                 ins->dreg = alloc_dreg (cfg, (MonoStackType)ins->type);
12290                                 type_from_op (cfg, ins, arg1, arg2);
12291
12292                                 if (cmp->opcode == OP_FCOMPARE || cmp->opcode == OP_RCOMPARE) {
12293                                         /*
12294                                          * The backends expect the fceq opcodes to do the
12295                                          * comparison too.
12296                                          */
12297                                         ins->sreg1 = cmp->sreg1;
12298                                         ins->sreg2 = cmp->sreg2;
12299                                         NULLIFY_INS (cmp);
12300                                 }
12301                                 MONO_ADD_INS (cfg->cbb, ins);
12302                                 *sp++ = ins;
12303                                 ip += 2;
12304                                 break;
12305                         }
12306                         case CEE_LDFTN: {
12307                                 MonoInst *argconst;
12308                                 MonoMethod *cil_method;
12309
12310                                 CHECK_STACK_OVF (1);
12311                                 CHECK_OPSIZE (6);
12312                                 n = read32 (ip + 2);
12313                                 cmethod = mini_get_method (cfg, method, n, NULL, generic_context);
12314                                 CHECK_CFG_ERROR;
12315
12316                                 mono_class_init (cmethod->klass);
12317
12318                                 mono_save_token_info (cfg, image, n, cmethod);
12319
12320                                 context_used = mini_method_check_context_used (cfg, cmethod);
12321
12322                                 cil_method = cmethod;
12323                                 if (!dont_verify && !cfg->skip_visibility && !mono_method_can_access_method (method, cmethod))
12324                                         emit_method_access_failure (cfg, method, cil_method);
12325
12326                                 if (mono_security_core_clr_enabled ())
12327                                         ensure_method_is_allowed_to_call_method (cfg, method, cmethod);
12328
12329                                 /* 
12330                                  * Optimize the common case of ldftn+delegate creation
12331                                  */
12332                                 if ((sp > stack_start) && (ip + 6 + 5 < end) && ip_in_bb (cfg, cfg->cbb, ip + 6) && (ip [6] == CEE_NEWOBJ)) {
12333                                         MonoMethod *ctor_method = mini_get_method (cfg, method, read32 (ip + 7), NULL, generic_context);
12334                                         if (ctor_method && (ctor_method->klass->parent == mono_defaults.multicastdelegate_class)) {
12335                                                 MonoInst *target_ins, *handle_ins;
12336                                                 MonoMethod *invoke;
12337                                                 int invoke_context_used;
12338
12339                                                 invoke = mono_get_delegate_invoke (ctor_method->klass);
12340                                                 if (!invoke || !mono_method_signature (invoke))
12341                                                         LOAD_ERROR;
12342
12343                                                 invoke_context_used = mini_method_check_context_used (cfg, invoke);
12344
12345                                                 target_ins = sp [-1];
12346
12347                                                 if (mono_security_core_clr_enabled ())
12348                                                         ensure_method_is_allowed_to_call_method (cfg, method, ctor_method);
12349
12350                                                 if (!(cmethod->flags & METHOD_ATTRIBUTE_STATIC)) {
12351                                                         /*LAME IMPL: We must not add a null check for virtual invoke delegates.*/
12352                                                         if (mono_method_signature (invoke)->param_count == mono_method_signature (cmethod)->param_count) {
12353                                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, target_ins->dreg, 0);
12354                                                                 MONO_EMIT_NEW_COND_EXC (cfg, EQ, "ArgumentException");
12355                                                         }
12356                                                 }
12357
12358                                                 /* FIXME: SGEN support */
12359                                                 if (invoke_context_used == 0 || cfg->llvm_only) {
12360                                                         ip += 6;
12361                                                         if (cfg->verbose_level > 3)
12362                                                                 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));
12363                                                         if ((handle_ins = handle_delegate_ctor (cfg, ctor_method->klass, target_ins, cmethod, context_used, FALSE))) {
12364                                                                 sp --;
12365                                                                 *sp = handle_ins;
12366                                                                 CHECK_CFG_EXCEPTION;
12367                                                                 ip += 5;
12368                                                                 sp ++;
12369                                                                 break;
12370                                                         }
12371                                                         ip -= 6;
12372                                                 }
12373                                         }
12374                                 }
12375
12376                                 argconst = emit_get_rgctx_method (cfg, context_used, cmethod, MONO_RGCTX_INFO_METHOD);
12377                                 ins = mono_emit_jit_icall (cfg, mono_ldftn, &argconst);
12378                                 *sp++ = ins;
12379                                 
12380                                 ip += 6;
12381                                 inline_costs += 10 * num_calls++;
12382                                 break;
12383                         }
12384                         case CEE_LDVIRTFTN: {
12385                                 MonoInst *args [2];
12386
12387                                 CHECK_STACK (1);
12388                                 CHECK_OPSIZE (6);
12389                                 n = read32 (ip + 2);
12390                                 cmethod = mini_get_method (cfg, method, n, NULL, generic_context);
12391                                 CHECK_CFG_ERROR;
12392
12393                                 mono_class_init (cmethod->klass);
12394  
12395                                 context_used = mini_method_check_context_used (cfg, cmethod);
12396
12397                                 if (mono_security_core_clr_enabled ())
12398                                         ensure_method_is_allowed_to_call_method (cfg, method, cmethod);
12399
12400                                 /*
12401                                  * Optimize the common case of ldvirtftn+delegate creation
12402                                  */
12403                                 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)) {
12404                                         MonoMethod *ctor_method = mini_get_method (cfg, method, read32 (ip + 7), NULL, generic_context);
12405                                         if (ctor_method && (ctor_method->klass->parent == mono_defaults.multicastdelegate_class)) {
12406                                                 MonoInst *target_ins, *handle_ins;
12407                                                 MonoMethod *invoke;
12408                                                 int invoke_context_used;
12409                                                 gboolean is_virtual = cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL;
12410
12411                                                 invoke = mono_get_delegate_invoke (ctor_method->klass);
12412                                                 if (!invoke || !mono_method_signature (invoke))
12413                                                         LOAD_ERROR;
12414
12415                                                 invoke_context_used = mini_method_check_context_used (cfg, invoke);
12416
12417                                                 target_ins = sp [-1];
12418
12419                                                 if (mono_security_core_clr_enabled ())
12420                                                         ensure_method_is_allowed_to_call_method (cfg, method, ctor_method);
12421
12422                                                 /* FIXME: SGEN support */
12423                                                 if (invoke_context_used == 0 || cfg->llvm_only) {
12424                                                         ip += 6;
12425                                                         if (cfg->verbose_level > 3)
12426                                                                 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));
12427                                                         if ((handle_ins = handle_delegate_ctor (cfg, ctor_method->klass, target_ins, cmethod, context_used, is_virtual))) {
12428                                                                 sp -= 2;
12429                                                                 *sp = handle_ins;
12430                                                                 CHECK_CFG_EXCEPTION;
12431                                                                 ip += 5;
12432                                                                 sp ++;
12433                                                                 break;
12434                                                         }
12435                                                         ip -= 6;
12436                                                 }
12437                                         }
12438                                 }
12439
12440                                 --sp;
12441                                 args [0] = *sp;
12442
12443                                 args [1] = emit_get_rgctx_method (cfg, context_used,
12444                                                                                                   cmethod, MONO_RGCTX_INFO_METHOD);
12445
12446                                 if (context_used)
12447                                         *sp++ = mono_emit_jit_icall (cfg, mono_ldvirtfn_gshared, args);
12448                                 else
12449                                         *sp++ = mono_emit_jit_icall (cfg, mono_ldvirtfn, args);
12450
12451                                 ip += 6;
12452                                 inline_costs += 10 * num_calls++;
12453                                 break;
12454                         }
12455                         case CEE_LDARG:
12456                                 CHECK_STACK_OVF (1);
12457                                 CHECK_OPSIZE (4);
12458                                 n = read16 (ip + 2);
12459                                 CHECK_ARG (n);
12460                                 EMIT_NEW_ARGLOAD (cfg, ins, n);
12461                                 *sp++ = ins;
12462                                 ip += 4;
12463                                 break;
12464                         case CEE_LDARGA:
12465                                 CHECK_STACK_OVF (1);
12466                                 CHECK_OPSIZE (4);
12467                                 n = read16 (ip + 2);
12468                                 CHECK_ARG (n);
12469                                 NEW_ARGLOADA (cfg, ins, n);
12470                                 MONO_ADD_INS (cfg->cbb, ins);
12471                                 *sp++ = ins;
12472                                 ip += 4;
12473                                 break;
12474                         case CEE_STARG:
12475                                 CHECK_STACK (1);
12476                                 --sp;
12477                                 CHECK_OPSIZE (4);
12478                                 n = read16 (ip + 2);
12479                                 CHECK_ARG (n);
12480                                 if (!dont_verify_stloc && target_type_is_incompatible (cfg, param_types [n], *sp))
12481                                         UNVERIFIED;
12482                                 EMIT_NEW_ARGSTORE (cfg, ins, n, *sp);
12483                                 ip += 4;
12484                                 break;
12485                         case CEE_LDLOC:
12486                                 CHECK_STACK_OVF (1);
12487                                 CHECK_OPSIZE (4);
12488                                 n = read16 (ip + 2);
12489                                 CHECK_LOCAL (n);
12490                                 EMIT_NEW_LOCLOAD (cfg, ins, n);
12491                                 *sp++ = ins;
12492                                 ip += 4;
12493                                 break;
12494                         case CEE_LDLOCA: {
12495                                 unsigned char *tmp_ip;
12496                                 CHECK_STACK_OVF (1);
12497                                 CHECK_OPSIZE (4);
12498                                 n = read16 (ip + 2);
12499                                 CHECK_LOCAL (n);
12500
12501                                 if ((tmp_ip = emit_optimized_ldloca_ir (cfg, ip, end, 2))) {
12502                                         ip = tmp_ip;
12503                                         inline_costs += 1;
12504                                         break;
12505                                 }                       
12506                                 
12507                                 EMIT_NEW_LOCLOADA (cfg, ins, n);
12508                                 *sp++ = ins;
12509                                 ip += 4;
12510                                 break;
12511                         }
12512                         case CEE_STLOC:
12513                                 CHECK_STACK (1);
12514                                 --sp;
12515                                 CHECK_OPSIZE (4);
12516                                 n = read16 (ip + 2);
12517                                 CHECK_LOCAL (n);
12518                                 if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [n], *sp))
12519                                         UNVERIFIED;
12520                                 emit_stloc_ir (cfg, sp, header, n);
12521                                 ip += 4;
12522                                 inline_costs += 1;
12523                                 break;
12524                         case CEE_LOCALLOC: {
12525                                 CHECK_STACK (1);
12526                                 MonoBasicBlock *non_zero_bb, *end_bb;
12527                                 int alloc_ptr = alloc_preg (cfg);
12528                                 --sp;
12529                                 if (sp != stack_start) 
12530                                         UNVERIFIED;
12531                                 if (cfg->method != method) 
12532                                         /* 
12533                                          * Inlining this into a loop in a parent could lead to 
12534                                          * stack overflows which is different behavior than the
12535                                          * non-inlined case, thus disable inlining in this case.
12536                                          */
12537                                         INLINE_FAILURE("localloc");
12538
12539                                 NEW_BBLOCK (cfg, non_zero_bb);
12540                                 NEW_BBLOCK (cfg, end_bb);
12541
12542                                 /* if size != zero */
12543                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, sp [0]->dreg, 0);
12544                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, non_zero_bb);
12545
12546                                 //size is zero, so result is NULL
12547                                 MONO_EMIT_NEW_PCONST (cfg, alloc_ptr, NULL);
12548                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
12549
12550                                 MONO_START_BB (cfg, non_zero_bb);
12551                                 MONO_INST_NEW (cfg, ins, OP_LOCALLOC);
12552                                 ins->dreg = alloc_ptr;
12553                                 ins->sreg1 = sp [0]->dreg;
12554                                 ins->type = STACK_PTR;
12555                                 MONO_ADD_INS (cfg->cbb, ins);
12556
12557                                 cfg->flags |= MONO_CFG_HAS_ALLOCA;
12558                                 if (init_locals)
12559                                         ins->flags |= MONO_INST_INIT;
12560
12561                                 MONO_START_BB (cfg, end_bb);
12562                                 EMIT_NEW_UNALU (cfg, ins, OP_MOVE, alloc_preg (cfg), alloc_ptr);
12563                                 ins->type = STACK_PTR;
12564
12565                                 *sp++ = ins;
12566                                 ip += 2;
12567                                 break;
12568                         }
12569                         case CEE_ENDFILTER: {
12570                                 MonoExceptionClause *clause, *nearest;
12571                                 int cc;
12572
12573                                 CHECK_STACK (1);
12574                                 --sp;
12575                                 if ((sp != stack_start) || (sp [0]->type != STACK_I4)) 
12576                                         UNVERIFIED;
12577                                 MONO_INST_NEW (cfg, ins, OP_ENDFILTER);
12578                                 ins->sreg1 = (*sp)->dreg;
12579                                 MONO_ADD_INS (cfg->cbb, ins);
12580                                 start_new_bblock = 1;
12581                                 ip += 2;
12582
12583                                 nearest = NULL;
12584                                 for (cc = 0; cc < header->num_clauses; ++cc) {
12585                                         clause = &header->clauses [cc];
12586                                         if ((clause->flags & MONO_EXCEPTION_CLAUSE_FILTER) &&
12587                                                 ((ip - header->code) > clause->data.filter_offset && (ip - header->code) <= clause->handler_offset) &&
12588                                             (!nearest || (clause->data.filter_offset < nearest->data.filter_offset)))
12589                                                 nearest = clause;
12590                                 }
12591                                 g_assert (nearest);
12592                                 if ((ip - header->code) != nearest->handler_offset)
12593                                         UNVERIFIED;
12594
12595                                 break;
12596                         }
12597                         case CEE_UNALIGNED_:
12598                                 ins_flag |= MONO_INST_UNALIGNED;
12599                                 /* FIXME: record alignment? we can assume 1 for now */
12600                                 CHECK_OPSIZE (3);
12601                                 ip += 3;
12602                                 break;
12603                         case CEE_VOLATILE_:
12604                                 ins_flag |= MONO_INST_VOLATILE;
12605                                 ip += 2;
12606                                 break;
12607                         case CEE_TAIL_:
12608                                 ins_flag   |= MONO_INST_TAILCALL;
12609                                 cfg->flags |= MONO_CFG_HAS_TAIL;
12610                                 /* Can't inline tail calls at this time */
12611                                 inline_costs += 100000;
12612                                 ip += 2;
12613                                 break;
12614                         case CEE_INITOBJ:
12615                                 CHECK_STACK (1);
12616                                 --sp;
12617                                 CHECK_OPSIZE (6);
12618                                 token = read32 (ip + 2);
12619                                 klass = mini_get_class (method, token, generic_context);
12620                                 CHECK_TYPELOAD (klass);
12621                                 if (generic_class_is_reference_type (cfg, klass))
12622                                         MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STORE_MEMBASE_IMM, sp [0]->dreg, 0, 0);
12623                                 else
12624                                         mini_emit_initobj (cfg, *sp, NULL, klass);
12625                                 ip += 6;
12626                                 inline_costs += 1;
12627                                 break;
12628                         case CEE_CONSTRAINED_:
12629                                 CHECK_OPSIZE (6);
12630                                 token = read32 (ip + 2);
12631                                 constrained_class = mini_get_class (method, token, generic_context);
12632                                 CHECK_TYPELOAD (constrained_class);
12633                                 ip += 6;
12634                                 break;
12635                         case CEE_CPBLK:
12636                         case CEE_INITBLK: {
12637                                 MonoInst *iargs [3];
12638                                 CHECK_STACK (3);
12639                                 sp -= 3;
12640
12641                                 /* Skip optimized paths for volatile operations. */
12642                                 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)) {
12643                                         mini_emit_memcpy (cfg, sp [0]->dreg, 0, sp [1]->dreg, 0, sp [2]->inst_c0, 0);
12644                                 } 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)) {
12645                                         /* emit_memset only works when val == 0 */
12646                                         mini_emit_memset (cfg, sp [0]->dreg, 0, sp [2]->inst_c0, sp [1]->inst_c0, 0);
12647                                 } else {
12648                                         MonoInst *call;
12649                                         iargs [0] = sp [0];
12650                                         iargs [1] = sp [1];
12651                                         iargs [2] = sp [2];
12652                                         if (ip [1] == CEE_CPBLK) {
12653                                                 /*
12654                                                  * FIXME: It's unclear whether we should be emitting both the acquire
12655                                                  * and release barriers for cpblk. It is technically both a load and
12656                                                  * store operation, so it seems like that's the sensible thing to do.
12657                                                  *
12658                                                  * FIXME: We emit full barriers on both sides of the operation for
12659                                                  * simplicity. We should have a separate atomic memcpy method instead.
12660                                                  */
12661                                                 MonoMethod *memcpy_method = mini_get_memcpy_method ();
12662
12663                                                 if (ins_flag & MONO_INST_VOLATILE)
12664                                                         mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
12665
12666                                                 call = mono_emit_method_call (cfg, memcpy_method, iargs, NULL);
12667                                                 call->flags |= ins_flag;
12668
12669                                                 if (ins_flag & MONO_INST_VOLATILE)
12670                                                         mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
12671                                         } else {
12672                                                 MonoMethod *memset_method = mini_get_memset_method ();
12673                                                 if (ins_flag & MONO_INST_VOLATILE) {
12674                                                         /* Volatile stores have release semantics, see 12.6.7 in Ecma 335 */
12675                                                         mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_REL);
12676                                                 }
12677                                                 call = mono_emit_method_call (cfg, memset_method, iargs, NULL);
12678                                                 call->flags |= ins_flag;
12679                                         }
12680                                 }
12681                                 ip += 2;
12682                                 ins_flag = 0;
12683                                 inline_costs += 1;
12684                                 break;
12685                         }
12686                         case CEE_NO_:
12687                                 CHECK_OPSIZE (3);
12688                                 if (ip [2] & 0x1)
12689                                         ins_flag |= MONO_INST_NOTYPECHECK;
12690                                 if (ip [2] & 0x2)
12691                                         ins_flag |= MONO_INST_NORANGECHECK;
12692                                 /* we ignore the no-nullcheck for now since we
12693                                  * really do it explicitly only when doing callvirt->call
12694                                  */
12695                                 ip += 3;
12696                                 break;
12697                         case CEE_RETHROW: {
12698                                 MonoInst *load;
12699                                 int handler_offset = -1;
12700
12701                                 for (i = 0; i < header->num_clauses; ++i) {
12702                                         MonoExceptionClause *clause = &header->clauses [i];
12703                                         if (MONO_OFFSET_IN_HANDLER (clause, ip - header->code) && !(clause->flags & MONO_EXCEPTION_CLAUSE_FINALLY)) {
12704                                                 handler_offset = clause->handler_offset;
12705                                                 break;
12706                                         }
12707                                 }
12708
12709                                 cfg->cbb->flags |= BB_EXCEPTION_UNSAFE;
12710
12711                                 if (handler_offset == -1)
12712                                         UNVERIFIED;
12713
12714                                 EMIT_NEW_TEMPLOAD (cfg, load, mono_find_exvar_for_offset (cfg, handler_offset)->inst_c0);
12715                                 MONO_INST_NEW (cfg, ins, OP_RETHROW);
12716                                 ins->sreg1 = load->dreg;
12717                                 MONO_ADD_INS (cfg->cbb, ins);
12718
12719                                 MONO_INST_NEW (cfg, ins, OP_NOT_REACHED);
12720                                 MONO_ADD_INS (cfg->cbb, ins);
12721
12722                                 sp = stack_start;
12723                                 link_bblock (cfg, cfg->cbb, end_bblock);
12724                                 start_new_bblock = 1;
12725                                 ip += 2;
12726                                 break;
12727                         }
12728                         case CEE_SIZEOF: {
12729                                 guint32 val;
12730                                 int ialign;
12731
12732                                 CHECK_STACK_OVF (1);
12733                                 CHECK_OPSIZE (6);
12734                                 token = read32 (ip + 2);
12735                                 if (mono_metadata_token_table (token) == MONO_TABLE_TYPESPEC && !image_is_dynamic (method->klass->image) && !generic_context) {
12736                                         MonoType *type = mono_type_create_from_typespec_checked (image, token, &cfg->error);
12737                                         CHECK_CFG_ERROR;
12738
12739                                         val = mono_type_size (type, &ialign);
12740                                 } else {
12741                                         MonoClass *klass = mini_get_class (method, token, generic_context);
12742                                         CHECK_TYPELOAD (klass);
12743
12744                                         val = mono_type_size (&klass->byval_arg, &ialign);
12745
12746                                         if (mini_is_gsharedvt_klass (klass))
12747                                                 GSHAREDVT_FAILURE (*ip);
12748                                 }
12749                                 EMIT_NEW_ICONST (cfg, ins, val);
12750                                 *sp++= ins;
12751                                 ip += 6;
12752                                 break;
12753                         }
12754                         case CEE_REFANYTYPE: {
12755                                 MonoInst *src_var, *src;
12756
12757                                 GSHAREDVT_FAILURE (*ip);
12758
12759                                 CHECK_STACK (1);
12760                                 --sp;
12761
12762                                 // FIXME:
12763                                 src_var = get_vreg_to_inst (cfg, sp [0]->dreg);
12764                                 if (!src_var)
12765                                         src_var = mono_compile_create_var_for_vreg (cfg, &mono_defaults.typed_reference_class->byval_arg, OP_LOCAL, sp [0]->dreg);
12766                                 EMIT_NEW_VARLOADA (cfg, src, src_var, src_var->inst_vtype);
12767                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &mono_defaults.typehandle_class->byval_arg, src->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, type));
12768                                 *sp++ = ins;
12769                                 ip += 2;
12770                                 break;
12771                         }
12772                         case CEE_READONLY_:
12773                                 readonly = TRUE;
12774                                 ip += 2;
12775                                 break;
12776
12777                         case CEE_UNUSED56:
12778                         case CEE_UNUSED57:
12779                         case CEE_UNUSED70:
12780                         case CEE_UNUSED:
12781                         case CEE_UNUSED99:
12782                                 UNVERIFIED;
12783                                 
12784                         default:
12785                                 g_warning ("opcode 0xfe 0x%02x not handled", ip [1]);
12786                                 UNVERIFIED;
12787                         }
12788                         break;
12789                 }
12790                 case CEE_UNUSED58:
12791                 case CEE_UNUSED1:
12792                         UNVERIFIED;
12793
12794                 default:
12795                         g_warning ("opcode 0x%02x not handled", *ip);
12796                         UNVERIFIED;
12797                 }
12798         }
12799         if (start_new_bblock != 1)
12800                 UNVERIFIED;
12801
12802         cfg->cbb->cil_length = ip - cfg->cbb->cil_code;
12803         if (cfg->cbb->next_bb) {
12804                 /* This could already be set because of inlining, #693905 */
12805                 MonoBasicBlock *bb = cfg->cbb;
12806
12807                 while (bb->next_bb)
12808                         bb = bb->next_bb;
12809                 bb->next_bb = end_bblock;
12810         } else {
12811                 cfg->cbb->next_bb = end_bblock;
12812         }
12813
12814         if (cfg->method == method && cfg->domainvar) {
12815                 MonoInst *store;
12816                 MonoInst *get_domain;
12817
12818                 cfg->cbb = init_localsbb;
12819
12820                 get_domain = mono_create_tls_get (cfg, TLS_KEY_DOMAIN);
12821                 NEW_TEMPSTORE (cfg, store, cfg->domainvar->inst_c0, get_domain);
12822                 MONO_ADD_INS (cfg->cbb, store);
12823         }
12824
12825 #if defined(TARGET_POWERPC) || defined(TARGET_X86)
12826         if (cfg->compile_aot)
12827                 /* FIXME: The plt slots require a GOT var even if the method doesn't use it */
12828                 mono_get_got_var (cfg);
12829 #endif
12830
12831         if (cfg->method == method && cfg->got_var)
12832                 mono_emit_load_got_addr (cfg);
12833
12834         if (init_localsbb) {
12835                 cfg->cbb = init_localsbb;
12836                 cfg->ip = NULL;
12837                 for (i = 0; i < header->num_locals; ++i) {
12838                         emit_init_local (cfg, i, header->locals [i], init_locals);
12839                 }
12840         }
12841
12842         if (cfg->init_ref_vars && cfg->method == method) {
12843                 /* Emit initialization for ref vars */
12844                 // FIXME: Avoid duplication initialization for IL locals.
12845                 for (i = 0; i < cfg->num_varinfo; ++i) {
12846                         MonoInst *ins = cfg->varinfo [i];
12847
12848                         if (ins->opcode == OP_LOCAL && ins->type == STACK_OBJ)
12849                                 MONO_EMIT_NEW_PCONST (cfg, ins->dreg, NULL);
12850                 }
12851         }
12852
12853         if (cfg->lmf_var && cfg->method == method && !cfg->llvm_only) {
12854                 cfg->cbb = init_localsbb;
12855                 emit_push_lmf (cfg);
12856         }
12857
12858         cfg->cbb = init_localsbb;
12859         emit_instrumentation_call (cfg, mono_profiler_method_enter);
12860
12861         if (seq_points) {
12862                 MonoBasicBlock *bb;
12863
12864                 /*
12865                  * Make seq points at backward branch targets interruptable.
12866                  */
12867                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
12868                         if (bb->code && bb->in_count > 1 && bb->code->opcode == OP_SEQ_POINT)
12869                                 bb->code->flags |= MONO_INST_SINGLE_STEP_LOC;
12870         }
12871
12872         /* Add a sequence point for method entry/exit events */
12873         if (seq_points && cfg->gen_sdb_seq_points) {
12874                 NEW_SEQ_POINT (cfg, ins, METHOD_ENTRY_IL_OFFSET, FALSE);
12875                 MONO_ADD_INS (init_localsbb, ins);
12876                 NEW_SEQ_POINT (cfg, ins, METHOD_EXIT_IL_OFFSET, FALSE);
12877                 MONO_ADD_INS (cfg->bb_exit, ins);
12878         }
12879
12880         /*
12881          * Add seq points for IL offsets which have line number info, but wasn't generated a seq point during JITting because
12882          * the code they refer to was dead (#11880).
12883          */
12884         if (sym_seq_points) {
12885                 for (i = 0; i < header->code_size; ++i) {
12886                         if (mono_bitset_test_fast (seq_point_locs, i) && !mono_bitset_test_fast (seq_point_set_locs, i)) {
12887                                 MonoInst *ins;
12888
12889                                 NEW_SEQ_POINT (cfg, ins, i, FALSE);
12890                                 mono_add_seq_point (cfg, NULL, ins, SEQ_POINT_NATIVE_OFFSET_DEAD_CODE);
12891                         }
12892                 }
12893         }
12894
12895         cfg->ip = NULL;
12896
12897         if (cfg->method == method) {
12898                 MonoBasicBlock *bb;
12899                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
12900                         if (bb == cfg->bb_init)
12901                                 bb->region = -1;
12902                         else
12903                                 bb->region = mono_find_block_region (cfg, bb->real_offset);
12904                         if (cfg->spvars)
12905                                 mono_create_spvar_for_region (cfg, bb->region);
12906                         if (cfg->verbose_level > 2)
12907                                 printf ("REGION BB%d IL_%04x ID_%08X\n", bb->block_num, bb->real_offset, bb->region);
12908                 }
12909         } else {
12910                 MonoBasicBlock *bb;
12911                 /* get_most_deep_clause () in mini-llvm.c depends on this for inlined bblocks */
12912                 for (bb = start_bblock; bb != end_bblock; bb  = bb->next_bb) {
12913                         bb->real_offset = inline_offset;
12914                 }
12915         }
12916
12917         if (inline_costs < 0) {
12918                 char *mname;
12919
12920                 /* Method is too large */
12921                 mname = mono_method_full_name (method, TRUE);
12922                 mono_cfg_set_exception_invalid_program (cfg, g_strdup_printf ("Method %s is too complex.", mname));
12923                 g_free (mname);
12924         }
12925
12926         if ((cfg->verbose_level > 2) && (cfg->method == method)) 
12927                 mono_print_code (cfg, "AFTER METHOD-TO-IR");
12928
12929         goto cleanup;
12930
12931 mono_error_exit:
12932         g_assert (!mono_error_ok (&cfg->error));
12933         goto cleanup;
12934  
12935  exception_exit:
12936         g_assert (cfg->exception_type != MONO_EXCEPTION_NONE);
12937         goto cleanup;
12938
12939  unverified:
12940         set_exception_type_from_invalid_il (cfg, method, ip);
12941         goto cleanup;
12942
12943  cleanup:
12944         g_slist_free (class_inits);
12945         mono_basic_block_free (original_bb);
12946         cfg->dont_inline = g_list_remove (cfg->dont_inline, method);
12947         if (cfg->exception_type)
12948                 return -1;
12949         else
12950                 return inline_costs;
12951 }
12952
12953 static int
12954 store_membase_reg_to_store_membase_imm (int opcode)
12955 {
12956         switch (opcode) {
12957         case OP_STORE_MEMBASE_REG:
12958                 return OP_STORE_MEMBASE_IMM;
12959         case OP_STOREI1_MEMBASE_REG:
12960                 return OP_STOREI1_MEMBASE_IMM;
12961         case OP_STOREI2_MEMBASE_REG:
12962                 return OP_STOREI2_MEMBASE_IMM;
12963         case OP_STOREI4_MEMBASE_REG:
12964                 return OP_STOREI4_MEMBASE_IMM;
12965         case OP_STOREI8_MEMBASE_REG:
12966                 return OP_STOREI8_MEMBASE_IMM;
12967         default:
12968                 g_assert_not_reached ();
12969         }
12970
12971         return -1;
12972 }               
12973
12974 int
12975 mono_op_to_op_imm (int opcode)
12976 {
12977         switch (opcode) {
12978         case OP_IADD:
12979                 return OP_IADD_IMM;
12980         case OP_ISUB:
12981                 return OP_ISUB_IMM;
12982         case OP_IDIV:
12983                 return OP_IDIV_IMM;
12984         case OP_IDIV_UN:
12985                 return OP_IDIV_UN_IMM;
12986         case OP_IREM:
12987                 return OP_IREM_IMM;
12988         case OP_IREM_UN:
12989                 return OP_IREM_UN_IMM;
12990         case OP_IMUL:
12991                 return OP_IMUL_IMM;
12992         case OP_IAND:
12993                 return OP_IAND_IMM;
12994         case OP_IOR:
12995                 return OP_IOR_IMM;
12996         case OP_IXOR:
12997                 return OP_IXOR_IMM;
12998         case OP_ISHL:
12999                 return OP_ISHL_IMM;
13000         case OP_ISHR:
13001                 return OP_ISHR_IMM;
13002         case OP_ISHR_UN:
13003                 return OP_ISHR_UN_IMM;
13004
13005         case OP_LADD:
13006                 return OP_LADD_IMM;
13007         case OP_LSUB:
13008                 return OP_LSUB_IMM;
13009         case OP_LAND:
13010                 return OP_LAND_IMM;
13011         case OP_LOR:
13012                 return OP_LOR_IMM;
13013         case OP_LXOR:
13014                 return OP_LXOR_IMM;
13015         case OP_LSHL:
13016                 return OP_LSHL_IMM;
13017         case OP_LSHR:
13018                 return OP_LSHR_IMM;
13019         case OP_LSHR_UN:
13020                 return OP_LSHR_UN_IMM;
13021 #if SIZEOF_REGISTER == 8
13022         case OP_LREM:
13023                 return OP_LREM_IMM;
13024 #endif
13025
13026         case OP_COMPARE:
13027                 return OP_COMPARE_IMM;
13028         case OP_ICOMPARE:
13029                 return OP_ICOMPARE_IMM;
13030         case OP_LCOMPARE:
13031                 return OP_LCOMPARE_IMM;
13032
13033         case OP_STORE_MEMBASE_REG:
13034                 return OP_STORE_MEMBASE_IMM;
13035         case OP_STOREI1_MEMBASE_REG:
13036                 return OP_STOREI1_MEMBASE_IMM;
13037         case OP_STOREI2_MEMBASE_REG:
13038                 return OP_STOREI2_MEMBASE_IMM;
13039         case OP_STOREI4_MEMBASE_REG:
13040                 return OP_STOREI4_MEMBASE_IMM;
13041
13042 #if defined(TARGET_X86) || defined (TARGET_AMD64)
13043         case OP_X86_PUSH:
13044                 return OP_X86_PUSH_IMM;
13045         case OP_X86_COMPARE_MEMBASE_REG:
13046                 return OP_X86_COMPARE_MEMBASE_IMM;
13047 #endif
13048 #if defined(TARGET_AMD64)
13049         case OP_AMD64_ICOMPARE_MEMBASE_REG:
13050                 return OP_AMD64_ICOMPARE_MEMBASE_IMM;
13051 #endif
13052         case OP_VOIDCALL_REG:
13053                 return OP_VOIDCALL;
13054         case OP_CALL_REG:
13055                 return OP_CALL;
13056         case OP_LCALL_REG:
13057                 return OP_LCALL;
13058         case OP_FCALL_REG:
13059                 return OP_FCALL;
13060         case OP_LOCALLOC:
13061                 return OP_LOCALLOC_IMM;
13062         }
13063
13064         return -1;
13065 }
13066
13067 static int
13068 ldind_to_load_membase (int opcode)
13069 {
13070         switch (opcode) {
13071         case CEE_LDIND_I1:
13072                 return OP_LOADI1_MEMBASE;
13073         case CEE_LDIND_U1:
13074                 return OP_LOADU1_MEMBASE;
13075         case CEE_LDIND_I2:
13076                 return OP_LOADI2_MEMBASE;
13077         case CEE_LDIND_U2:
13078                 return OP_LOADU2_MEMBASE;
13079         case CEE_LDIND_I4:
13080                 return OP_LOADI4_MEMBASE;
13081         case CEE_LDIND_U4:
13082                 return OP_LOADU4_MEMBASE;
13083         case CEE_LDIND_I:
13084                 return OP_LOAD_MEMBASE;
13085         case CEE_LDIND_REF:
13086                 return OP_LOAD_MEMBASE;
13087         case CEE_LDIND_I8:
13088                 return OP_LOADI8_MEMBASE;
13089         case CEE_LDIND_R4:
13090                 return OP_LOADR4_MEMBASE;
13091         case CEE_LDIND_R8:
13092                 return OP_LOADR8_MEMBASE;
13093         default:
13094                 g_assert_not_reached ();
13095         }
13096
13097         return -1;
13098 }
13099
13100 static int
13101 stind_to_store_membase (int opcode)
13102 {
13103         switch (opcode) {
13104         case CEE_STIND_I1:
13105                 return OP_STOREI1_MEMBASE_REG;
13106         case CEE_STIND_I2:
13107                 return OP_STOREI2_MEMBASE_REG;
13108         case CEE_STIND_I4:
13109                 return OP_STOREI4_MEMBASE_REG;
13110         case CEE_STIND_I:
13111         case CEE_STIND_REF:
13112                 return OP_STORE_MEMBASE_REG;
13113         case CEE_STIND_I8:
13114                 return OP_STOREI8_MEMBASE_REG;
13115         case CEE_STIND_R4:
13116                 return OP_STORER4_MEMBASE_REG;
13117         case CEE_STIND_R8:
13118                 return OP_STORER8_MEMBASE_REG;
13119         default:
13120                 g_assert_not_reached ();
13121         }
13122
13123         return -1;
13124 }
13125
13126 int
13127 mono_load_membase_to_load_mem (int opcode)
13128 {
13129         // FIXME: Add a MONO_ARCH_HAVE_LOAD_MEM macro
13130 #if defined(TARGET_X86) || defined(TARGET_AMD64)
13131         switch (opcode) {
13132         case OP_LOAD_MEMBASE:
13133                 return OP_LOAD_MEM;
13134         case OP_LOADU1_MEMBASE:
13135                 return OP_LOADU1_MEM;
13136         case OP_LOADU2_MEMBASE:
13137                 return OP_LOADU2_MEM;
13138         case OP_LOADI4_MEMBASE:
13139                 return OP_LOADI4_MEM;
13140         case OP_LOADU4_MEMBASE:
13141                 return OP_LOADU4_MEM;
13142 #if SIZEOF_REGISTER == 8
13143         case OP_LOADI8_MEMBASE:
13144                 return OP_LOADI8_MEM;
13145 #endif
13146         }
13147 #endif
13148
13149         return -1;
13150 }
13151
13152 static inline int
13153 op_to_op_dest_membase (int store_opcode, int opcode)
13154 {
13155 #if defined(TARGET_X86)
13156         if (!((store_opcode == OP_STORE_MEMBASE_REG) || (store_opcode == OP_STOREI4_MEMBASE_REG)))
13157                 return -1;
13158
13159         switch (opcode) {
13160         case OP_IADD:
13161                 return OP_X86_ADD_MEMBASE_REG;
13162         case OP_ISUB:
13163                 return OP_X86_SUB_MEMBASE_REG;
13164         case OP_IAND:
13165                 return OP_X86_AND_MEMBASE_REG;
13166         case OP_IOR:
13167                 return OP_X86_OR_MEMBASE_REG;
13168         case OP_IXOR:
13169                 return OP_X86_XOR_MEMBASE_REG;
13170         case OP_ADD_IMM:
13171         case OP_IADD_IMM:
13172                 return OP_X86_ADD_MEMBASE_IMM;
13173         case OP_SUB_IMM:
13174         case OP_ISUB_IMM:
13175                 return OP_X86_SUB_MEMBASE_IMM;
13176         case OP_AND_IMM:
13177         case OP_IAND_IMM:
13178                 return OP_X86_AND_MEMBASE_IMM;
13179         case OP_OR_IMM:
13180         case OP_IOR_IMM:
13181                 return OP_X86_OR_MEMBASE_IMM;
13182         case OP_XOR_IMM:
13183         case OP_IXOR_IMM:
13184                 return OP_X86_XOR_MEMBASE_IMM;
13185         case OP_MOVE:
13186                 return OP_NOP;
13187         }
13188 #endif
13189
13190 #if defined(TARGET_AMD64)
13191         if (!((store_opcode == OP_STORE_MEMBASE_REG) || (store_opcode == OP_STOREI4_MEMBASE_REG) || (store_opcode == OP_STOREI8_MEMBASE_REG)))
13192                 return -1;
13193
13194         switch (opcode) {
13195         case OP_IADD:
13196                 return OP_X86_ADD_MEMBASE_REG;
13197         case OP_ISUB:
13198                 return OP_X86_SUB_MEMBASE_REG;
13199         case OP_IAND:
13200                 return OP_X86_AND_MEMBASE_REG;
13201         case OP_IOR:
13202                 return OP_X86_OR_MEMBASE_REG;
13203         case OP_IXOR:
13204                 return OP_X86_XOR_MEMBASE_REG;
13205         case OP_IADD_IMM:
13206                 return OP_X86_ADD_MEMBASE_IMM;
13207         case OP_ISUB_IMM:
13208                 return OP_X86_SUB_MEMBASE_IMM;
13209         case OP_IAND_IMM:
13210                 return OP_X86_AND_MEMBASE_IMM;
13211         case OP_IOR_IMM:
13212                 return OP_X86_OR_MEMBASE_IMM;
13213         case OP_IXOR_IMM:
13214                 return OP_X86_XOR_MEMBASE_IMM;
13215         case OP_LADD:
13216                 return OP_AMD64_ADD_MEMBASE_REG;
13217         case OP_LSUB:
13218                 return OP_AMD64_SUB_MEMBASE_REG;
13219         case OP_LAND:
13220                 return OP_AMD64_AND_MEMBASE_REG;
13221         case OP_LOR:
13222                 return OP_AMD64_OR_MEMBASE_REG;
13223         case OP_LXOR:
13224                 return OP_AMD64_XOR_MEMBASE_REG;
13225         case OP_ADD_IMM:
13226         case OP_LADD_IMM:
13227                 return OP_AMD64_ADD_MEMBASE_IMM;
13228         case OP_SUB_IMM:
13229         case OP_LSUB_IMM:
13230                 return OP_AMD64_SUB_MEMBASE_IMM;
13231         case OP_AND_IMM:
13232         case OP_LAND_IMM:
13233                 return OP_AMD64_AND_MEMBASE_IMM;
13234         case OP_OR_IMM:
13235         case OP_LOR_IMM:
13236                 return OP_AMD64_OR_MEMBASE_IMM;
13237         case OP_XOR_IMM:
13238         case OP_LXOR_IMM:
13239                 return OP_AMD64_XOR_MEMBASE_IMM;
13240         case OP_MOVE:
13241                 return OP_NOP;
13242         }
13243 #endif
13244
13245         return -1;
13246 }
13247
13248 static inline int
13249 op_to_op_store_membase (int store_opcode, int opcode)
13250 {
13251 #if defined(TARGET_X86) || defined(TARGET_AMD64)
13252         switch (opcode) {
13253         case OP_ICEQ:
13254                 if (store_opcode == OP_STOREI1_MEMBASE_REG)
13255                         return OP_X86_SETEQ_MEMBASE;
13256         case OP_CNE:
13257                 if (store_opcode == OP_STOREI1_MEMBASE_REG)
13258                         return OP_X86_SETNE_MEMBASE;
13259         }
13260 #endif
13261
13262         return -1;
13263 }
13264
13265 static inline int
13266 op_to_op_src1_membase (MonoCompile *cfg, int load_opcode, int opcode)
13267 {
13268 #ifdef TARGET_X86
13269         /* FIXME: This has sign extension issues */
13270         /*
13271         if ((opcode == OP_ICOMPARE_IMM) && (load_opcode == OP_LOADU1_MEMBASE))
13272                 return OP_X86_COMPARE_MEMBASE8_IMM;
13273         */
13274
13275         if (!((load_opcode == OP_LOAD_MEMBASE) || (load_opcode == OP_LOADI4_MEMBASE) || (load_opcode == OP_LOADU4_MEMBASE)))
13276                 return -1;
13277
13278         switch (opcode) {
13279         case OP_X86_PUSH:
13280                 return OP_X86_PUSH_MEMBASE;
13281         case OP_COMPARE_IMM:
13282         case OP_ICOMPARE_IMM:
13283                 return OP_X86_COMPARE_MEMBASE_IMM;
13284         case OP_COMPARE:
13285         case OP_ICOMPARE:
13286                 return OP_X86_COMPARE_MEMBASE_REG;
13287         }
13288 #endif
13289
13290 #ifdef TARGET_AMD64
13291         /* FIXME: This has sign extension issues */
13292         /*
13293         if ((opcode == OP_ICOMPARE_IMM) && (load_opcode == OP_LOADU1_MEMBASE))
13294                 return OP_X86_COMPARE_MEMBASE8_IMM;
13295         */
13296
13297         switch (opcode) {
13298         case OP_X86_PUSH:
13299                 if ((load_opcode == OP_LOAD_MEMBASE && !cfg->backend->ilp32) || (load_opcode == OP_LOADI8_MEMBASE))
13300                         return OP_X86_PUSH_MEMBASE;
13301                 break;
13302                 /* FIXME: This only works for 32 bit immediates
13303         case OP_COMPARE_IMM:
13304         case OP_LCOMPARE_IMM:
13305                 if ((load_opcode == OP_LOAD_MEMBASE) || (load_opcode == OP_LOADI8_MEMBASE))
13306                         return OP_AMD64_COMPARE_MEMBASE_IMM;
13307                 */
13308         case OP_ICOMPARE_IMM:
13309                 if ((load_opcode == OP_LOADI4_MEMBASE) || (load_opcode == OP_LOADU4_MEMBASE))
13310                         return OP_AMD64_ICOMPARE_MEMBASE_IMM;
13311                 break;
13312         case OP_COMPARE:
13313         case OP_LCOMPARE:
13314                 if (cfg->backend->ilp32 && load_opcode == OP_LOAD_MEMBASE)
13315                         return OP_AMD64_ICOMPARE_MEMBASE_REG;
13316                 if ((load_opcode == OP_LOAD_MEMBASE && !cfg->backend->ilp32) || (load_opcode == OP_LOADI8_MEMBASE))
13317                         return OP_AMD64_COMPARE_MEMBASE_REG;
13318                 break;
13319         case OP_ICOMPARE:
13320                 if ((load_opcode == OP_LOADI4_MEMBASE) || (load_opcode == OP_LOADU4_MEMBASE))
13321                         return OP_AMD64_ICOMPARE_MEMBASE_REG;
13322                 break;
13323         }
13324 #endif
13325
13326         return -1;
13327 }
13328
13329 static inline int
13330 op_to_op_src2_membase (MonoCompile *cfg, int load_opcode, int opcode)
13331 {
13332 #ifdef TARGET_X86
13333         if (!((load_opcode == OP_LOAD_MEMBASE) || (load_opcode == OP_LOADI4_MEMBASE) || (load_opcode == OP_LOADU4_MEMBASE)))
13334                 return -1;
13335         
13336         switch (opcode) {
13337         case OP_COMPARE:
13338         case OP_ICOMPARE:
13339                 return OP_X86_COMPARE_REG_MEMBASE;
13340         case OP_IADD:
13341                 return OP_X86_ADD_REG_MEMBASE;
13342         case OP_ISUB:
13343                 return OP_X86_SUB_REG_MEMBASE;
13344         case OP_IAND:
13345                 return OP_X86_AND_REG_MEMBASE;
13346         case OP_IOR:
13347                 return OP_X86_OR_REG_MEMBASE;
13348         case OP_IXOR:
13349                 return OP_X86_XOR_REG_MEMBASE;
13350         }
13351 #endif
13352
13353 #ifdef TARGET_AMD64
13354         if ((load_opcode == OP_LOADI4_MEMBASE) || (load_opcode == OP_LOADU4_MEMBASE) || (load_opcode == OP_LOAD_MEMBASE && cfg->backend->ilp32)) {
13355                 switch (opcode) {
13356                 case OP_ICOMPARE:
13357                         return OP_AMD64_ICOMPARE_REG_MEMBASE;
13358                 case OP_IADD:
13359                         return OP_X86_ADD_REG_MEMBASE;
13360                 case OP_ISUB:
13361                         return OP_X86_SUB_REG_MEMBASE;
13362                 case OP_IAND:
13363                         return OP_X86_AND_REG_MEMBASE;
13364                 case OP_IOR:
13365                         return OP_X86_OR_REG_MEMBASE;
13366                 case OP_IXOR:
13367                         return OP_X86_XOR_REG_MEMBASE;
13368                 }
13369         } else if ((load_opcode == OP_LOADI8_MEMBASE) || (load_opcode == OP_LOAD_MEMBASE && !cfg->backend->ilp32)) {
13370                 switch (opcode) {
13371                 case OP_COMPARE:
13372                 case OP_LCOMPARE:
13373                         return OP_AMD64_COMPARE_REG_MEMBASE;
13374                 case OP_LADD:
13375                         return OP_AMD64_ADD_REG_MEMBASE;
13376                 case OP_LSUB:
13377                         return OP_AMD64_SUB_REG_MEMBASE;
13378                 case OP_LAND:
13379                         return OP_AMD64_AND_REG_MEMBASE;
13380                 case OP_LOR:
13381                         return OP_AMD64_OR_REG_MEMBASE;
13382                 case OP_LXOR:
13383                         return OP_AMD64_XOR_REG_MEMBASE;
13384                 }
13385         }
13386 #endif
13387
13388         return -1;
13389 }
13390
13391 int
13392 mono_op_to_op_imm_noemul (int opcode)
13393 {
13394         switch (opcode) {
13395 #if SIZEOF_REGISTER == 4 && !defined(MONO_ARCH_NO_EMULATE_LONG_SHIFT_OPS)
13396         case OP_LSHR:
13397         case OP_LSHL:
13398         case OP_LSHR_UN:
13399                 return -1;
13400 #endif
13401 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_EMULATE_DIV)
13402         case OP_IDIV:
13403         case OP_IDIV_UN:
13404         case OP_IREM:
13405         case OP_IREM_UN:
13406                 return -1;
13407 #endif
13408 #if defined(MONO_ARCH_EMULATE_MUL_DIV)
13409         case OP_IMUL:
13410                 return -1;
13411 #endif
13412         default:
13413                 return mono_op_to_op_imm (opcode);
13414         }
13415 }
13416
13417 /**
13418  * mono_handle_global_vregs:
13419  *
13420  *   Make vregs used in more than one bblock 'global', i.e. allocate a variable
13421  * for them.
13422  */
13423 void
13424 mono_handle_global_vregs (MonoCompile *cfg)
13425 {
13426         gint32 *vreg_to_bb;
13427         MonoBasicBlock *bb;
13428         int i, pos;
13429
13430         vreg_to_bb = (gint32 *)mono_mempool_alloc0 (cfg->mempool, sizeof (gint32*) * cfg->next_vreg + 1);
13431
13432 #ifdef MONO_ARCH_SIMD_INTRINSICS
13433         if (cfg->uses_simd_intrinsics)
13434                 mono_simd_simplify_indirection (cfg);
13435 #endif
13436
13437         /* Find local vregs used in more than one bb */
13438         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
13439                 MonoInst *ins = bb->code;       
13440                 int block_num = bb->block_num;
13441
13442                 if (cfg->verbose_level > 2)
13443                         printf ("\nHANDLE-GLOBAL-VREGS BLOCK %d:\n", bb->block_num);
13444
13445                 cfg->cbb = bb;
13446                 for (; ins; ins = ins->next) {
13447                         const char *spec = INS_INFO (ins->opcode);
13448                         int regtype = 0, regindex;
13449                         gint32 prev_bb;
13450
13451                         if (G_UNLIKELY (cfg->verbose_level > 2))
13452                                 mono_print_ins (ins);
13453
13454                         g_assert (ins->opcode >= MONO_CEE_LAST);
13455
13456                         for (regindex = 0; regindex < 4; regindex ++) {
13457                                 int vreg = 0;
13458
13459                                 if (regindex == 0) {
13460                                         regtype = spec [MONO_INST_DEST];
13461                                         if (regtype == ' ')
13462                                                 continue;
13463                                         vreg = ins->dreg;
13464                                 } else if (regindex == 1) {
13465                                         regtype = spec [MONO_INST_SRC1];
13466                                         if (regtype == ' ')
13467                                                 continue;
13468                                         vreg = ins->sreg1;
13469                                 } else if (regindex == 2) {
13470                                         regtype = spec [MONO_INST_SRC2];
13471                                         if (regtype == ' ')
13472                                                 continue;
13473                                         vreg = ins->sreg2;
13474                                 } else if (regindex == 3) {
13475                                         regtype = spec [MONO_INST_SRC3];
13476                                         if (regtype == ' ')
13477                                                 continue;
13478                                         vreg = ins->sreg3;
13479                                 }
13480
13481 #if SIZEOF_REGISTER == 4
13482                                 /* In the LLVM case, the long opcodes are not decomposed */
13483                                 if (regtype == 'l' && !COMPILE_LLVM (cfg)) {
13484                                         /*
13485                                          * Since some instructions reference the original long vreg,
13486                                          * and some reference the two component vregs, it is quite hard
13487                                          * to determine when it needs to be global. So be conservative.
13488                                          */
13489                                         if (!get_vreg_to_inst (cfg, vreg)) {
13490                                                 mono_compile_create_var_for_vreg (cfg, &mono_defaults.int64_class->byval_arg, OP_LOCAL, vreg);
13491
13492                                                 if (cfg->verbose_level > 2)
13493                                                         printf ("LONG VREG R%d made global.\n", vreg);
13494                                         }
13495
13496                                         /*
13497                                          * Make the component vregs volatile since the optimizations can
13498                                          * get confused otherwise.
13499                                          */
13500                                         get_vreg_to_inst (cfg, MONO_LVREG_LS (vreg))->flags |= MONO_INST_VOLATILE;
13501                                         get_vreg_to_inst (cfg, MONO_LVREG_MS (vreg))->flags |= MONO_INST_VOLATILE;
13502                                 }
13503 #endif
13504
13505                                 g_assert (vreg != -1);
13506
13507                                 prev_bb = vreg_to_bb [vreg];
13508                                 if (prev_bb == 0) {
13509                                         /* 0 is a valid block num */
13510                                         vreg_to_bb [vreg] = block_num + 1;
13511                                 } else if ((prev_bb != block_num + 1) && (prev_bb != -1)) {
13512                                         if (((regtype == 'i' && (vreg < MONO_MAX_IREGS))) || (regtype == 'f' && (vreg < MONO_MAX_FREGS)))
13513                                                 continue;
13514
13515                                         if (!get_vreg_to_inst (cfg, vreg)) {
13516                                                 if (G_UNLIKELY (cfg->verbose_level > 2))
13517                                                         printf ("VREG R%d used in BB%d and BB%d made global.\n", vreg, vreg_to_bb [vreg], block_num);
13518
13519                                                 switch (regtype) {
13520                                                 case 'i':
13521                                                         if (vreg_is_ref (cfg, vreg))
13522                                                                 mono_compile_create_var_for_vreg (cfg, &mono_defaults.object_class->byval_arg, OP_LOCAL, vreg);
13523                                                         else
13524                                                                 mono_compile_create_var_for_vreg (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL, vreg);
13525                                                         break;
13526                                                 case 'l':
13527                                                         mono_compile_create_var_for_vreg (cfg, &mono_defaults.int64_class->byval_arg, OP_LOCAL, vreg);
13528                                                         break;
13529                                                 case 'f':
13530                                                         mono_compile_create_var_for_vreg (cfg, &mono_defaults.double_class->byval_arg, OP_LOCAL, vreg);
13531                                                         break;
13532                                                 case 'v':
13533                                                 case 'x':
13534                                                         mono_compile_create_var_for_vreg (cfg, &ins->klass->byval_arg, OP_LOCAL, vreg);
13535                                                         break;
13536                                                 default:
13537                                                         g_assert_not_reached ();
13538                                                 }
13539                                         }
13540
13541                                         /* Flag as having been used in more than one bb */
13542                                         vreg_to_bb [vreg] = -1;
13543                                 }
13544                         }
13545                 }
13546         }
13547
13548         /* If a variable is used in only one bblock, convert it into a local vreg */
13549         for (i = 0; i < cfg->num_varinfo; i++) {
13550                 MonoInst *var = cfg->varinfo [i];
13551                 MonoMethodVar *vmv = MONO_VARINFO (cfg, i);
13552
13553                 switch (var->type) {
13554                 case STACK_I4:
13555                 case STACK_OBJ:
13556                 case STACK_PTR:
13557                 case STACK_MP:
13558                 case STACK_VTYPE:
13559 #if SIZEOF_REGISTER == 8
13560                 case STACK_I8:
13561 #endif
13562 #if !defined(TARGET_X86)
13563                 /* Enabling this screws up the fp stack on x86 */
13564                 case STACK_R8:
13565 #endif
13566                         if (mono_arch_is_soft_float ())
13567                                 break;
13568
13569                         /*
13570                         if (var->type == STACK_VTYPE && cfg->gsharedvt && mini_is_gsharedvt_variable_type (var->inst_vtype))
13571                                 break;
13572                         */
13573
13574                         /* Arguments are implicitly global */
13575                         /* Putting R4 vars into registers doesn't work currently */
13576                         /* The gsharedvt vars are implicitly referenced by ldaddr opcodes, but those opcodes are only generated later */
13577                         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) {
13578                                 /* 
13579                                  * Make that the variable's liveness interval doesn't contain a call, since
13580                                  * that would cause the lvreg to be spilled, making the whole optimization
13581                                  * useless.
13582                                  */
13583                                 /* This is too slow for JIT compilation */
13584 #if 0
13585                                 if (cfg->compile_aot && vreg_to_bb [var->dreg]) {
13586                                         MonoInst *ins;
13587                                         int def_index, call_index, ins_index;
13588                                         gboolean spilled = FALSE;
13589
13590                                         def_index = -1;
13591                                         call_index = -1;
13592                                         ins_index = 0;
13593                                         for (ins = vreg_to_bb [var->dreg]->code; ins; ins = ins->next) {
13594                                                 const char *spec = INS_INFO (ins->opcode);
13595
13596                                                 if ((spec [MONO_INST_DEST] != ' ') && (ins->dreg == var->dreg))
13597                                                         def_index = ins_index;
13598
13599                                                 if (((spec [MONO_INST_SRC1] != ' ') && (ins->sreg1 == var->dreg)) ||
13600                                                         ((spec [MONO_INST_SRC1] != ' ') && (ins->sreg1 == var->dreg))) {
13601                                                         if (call_index > def_index) {
13602                                                                 spilled = TRUE;
13603                                                                 break;
13604                                                         }
13605                                                 }
13606
13607                                                 if (MONO_IS_CALL (ins))
13608                                                         call_index = ins_index;
13609
13610                                                 ins_index ++;
13611                                         }
13612
13613                                         if (spilled)
13614                                                 break;
13615                                 }
13616 #endif
13617
13618                                 if (G_UNLIKELY (cfg->verbose_level > 2))
13619                                         printf ("CONVERTED R%d(%d) TO VREG.\n", var->dreg, vmv->idx);
13620                                 var->flags |= MONO_INST_IS_DEAD;
13621                                 cfg->vreg_to_inst [var->dreg] = NULL;
13622                         }
13623                         break;
13624                 }
13625         }
13626
13627         /* 
13628          * Compress the varinfo and vars tables so the liveness computation is faster and
13629          * takes up less space.
13630          */
13631         pos = 0;
13632         for (i = 0; i < cfg->num_varinfo; ++i) {
13633                 MonoInst *var = cfg->varinfo [i];
13634                 if (pos < i && cfg->locals_start == i)
13635                         cfg->locals_start = pos;
13636                 if (!(var->flags & MONO_INST_IS_DEAD)) {
13637                         if (pos < i) {
13638                                 cfg->varinfo [pos] = cfg->varinfo [i];
13639                                 cfg->varinfo [pos]->inst_c0 = pos;
13640                                 memcpy (&cfg->vars [pos], &cfg->vars [i], sizeof (MonoMethodVar));
13641                                 cfg->vars [pos].idx = pos;
13642 #if SIZEOF_REGISTER == 4
13643                                 if (cfg->varinfo [pos]->type == STACK_I8) {
13644                                         /* Modify the two component vars too */
13645                                         MonoInst *var1;
13646
13647                                         var1 = get_vreg_to_inst (cfg, MONO_LVREG_LS (cfg->varinfo [pos]->dreg));
13648                                         var1->inst_c0 = pos;
13649                                         var1 = get_vreg_to_inst (cfg, MONO_LVREG_MS (cfg->varinfo [pos]->dreg));
13650                                         var1->inst_c0 = pos;
13651                                 }
13652 #endif
13653                         }
13654                         pos ++;
13655                 }
13656         }
13657         cfg->num_varinfo = pos;
13658         if (cfg->locals_start > cfg->num_varinfo)
13659                 cfg->locals_start = cfg->num_varinfo;
13660 }
13661
13662 /*
13663  * mono_allocate_gsharedvt_vars:
13664  *
13665  *   Allocate variables with gsharedvt types to entries in the MonoGSharedVtMethodRuntimeInfo.entries array.
13666  * Initialize cfg->gsharedvt_vreg_to_idx with the mapping between vregs and indexes.
13667  */
13668 void
13669 mono_allocate_gsharedvt_vars (MonoCompile *cfg)
13670 {
13671         int i;
13672
13673         cfg->gsharedvt_vreg_to_idx = (int *)mono_mempool_alloc0 (cfg->mempool, sizeof (int) * cfg->next_vreg);
13674
13675         for (i = 0; i < cfg->num_varinfo; ++i) {
13676                 MonoInst *ins = cfg->varinfo [i];
13677                 int idx;
13678
13679                 if (mini_is_gsharedvt_variable_type (ins->inst_vtype)) {
13680                         if (i >= cfg->locals_start) {
13681                                 /* Local */
13682                                 idx = get_gsharedvt_info_slot (cfg, ins->inst_vtype, MONO_RGCTX_INFO_LOCAL_OFFSET);
13683                                 cfg->gsharedvt_vreg_to_idx [ins->dreg] = idx + 1;
13684                                 ins->opcode = OP_GSHAREDVT_LOCAL;
13685                                 ins->inst_imm = idx;
13686                         } else {
13687                                 /* Arg */
13688                                 cfg->gsharedvt_vreg_to_idx [ins->dreg] = -1;
13689                                 ins->opcode = OP_GSHAREDVT_ARG_REGOFFSET;
13690                         }
13691                 }
13692         }
13693 }
13694
13695 /**
13696  * mono_spill_global_vars:
13697  *
13698  *   Generate spill code for variables which are not allocated to registers, 
13699  * and replace vregs with their allocated hregs. *need_local_opts is set to TRUE if
13700  * code is generated which could be optimized by the local optimization passes.
13701  */
13702 void
13703 mono_spill_global_vars (MonoCompile *cfg, gboolean *need_local_opts)
13704 {
13705         MonoBasicBlock *bb;
13706         char spec2 [16];
13707         int orig_next_vreg;
13708         guint32 *vreg_to_lvreg;
13709         guint32 *lvregs;
13710         guint32 i, lvregs_len, lvregs_size;
13711         gboolean dest_has_lvreg = FALSE;
13712         MonoStackType stacktypes [128];
13713         MonoInst **live_range_start, **live_range_end;
13714         MonoBasicBlock **live_range_start_bb, **live_range_end_bb;
13715
13716         *need_local_opts = FALSE;
13717
13718         memset (spec2, 0, sizeof (spec2));
13719
13720         /* FIXME: Move this function to mini.c */
13721         stacktypes ['i'] = STACK_PTR;
13722         stacktypes ['l'] = STACK_I8;
13723         stacktypes ['f'] = STACK_R8;
13724 #ifdef MONO_ARCH_SIMD_INTRINSICS
13725         stacktypes ['x'] = STACK_VTYPE;
13726 #endif
13727
13728 #if SIZEOF_REGISTER == 4
13729         /* Create MonoInsts for longs */
13730         for (i = 0; i < cfg->num_varinfo; i++) {
13731                 MonoInst *ins = cfg->varinfo [i];
13732
13733                 if ((ins->opcode != OP_REGVAR) && !(ins->flags & MONO_INST_IS_DEAD)) {
13734                         switch (ins->type) {
13735                         case STACK_R8:
13736                         case STACK_I8: {
13737                                 MonoInst *tree;
13738
13739                                 if (ins->type == STACK_R8 && !COMPILE_SOFT_FLOAT (cfg))
13740                                         break;
13741
13742                                 g_assert (ins->opcode == OP_REGOFFSET);
13743
13744                                 tree = get_vreg_to_inst (cfg, MONO_LVREG_LS (ins->dreg));
13745                                 g_assert (tree);
13746                                 tree->opcode = OP_REGOFFSET;
13747                                 tree->inst_basereg = ins->inst_basereg;
13748                                 tree->inst_offset = ins->inst_offset + MINI_LS_WORD_OFFSET;
13749
13750                                 tree = get_vreg_to_inst (cfg, MONO_LVREG_MS (ins->dreg));
13751                                 g_assert (tree);
13752                                 tree->opcode = OP_REGOFFSET;
13753                                 tree->inst_basereg = ins->inst_basereg;
13754                                 tree->inst_offset = ins->inst_offset + MINI_MS_WORD_OFFSET;
13755                                 break;
13756                         }
13757                         default:
13758                                 break;
13759                         }
13760                 }
13761         }
13762 #endif
13763
13764         if (cfg->compute_gc_maps) {
13765                 /* registers need liveness info even for !non refs */
13766                 for (i = 0; i < cfg->num_varinfo; i++) {
13767                         MonoInst *ins = cfg->varinfo [i];
13768
13769                         if (ins->opcode == OP_REGVAR)
13770                                 ins->flags |= MONO_INST_GC_TRACK;
13771                 }
13772         }
13773                 
13774         /* FIXME: widening and truncation */
13775
13776         /*
13777          * As an optimization, when a variable allocated to the stack is first loaded into 
13778          * an lvreg, we will remember the lvreg and use it the next time instead of loading
13779          * the variable again.
13780          */
13781         orig_next_vreg = cfg->next_vreg;
13782         vreg_to_lvreg = (guint32 *)mono_mempool_alloc0 (cfg->mempool, sizeof (guint32) * cfg->next_vreg);
13783         lvregs_size = 1024;
13784         lvregs = (guint32 *)mono_mempool_alloc (cfg->mempool, sizeof (guint32) * lvregs_size);
13785         lvregs_len = 0;
13786
13787         /* 
13788          * These arrays contain the first and last instructions accessing a given
13789          * variable.
13790          * Since we emit bblocks in the same order we process them here, and we
13791          * don't split live ranges, these will precisely describe the live range of
13792          * the variable, i.e. the instruction range where a valid value can be found
13793          * in the variables location.
13794          * The live range is computed using the liveness info computed by the liveness pass.
13795          * We can't use vmv->range, since that is an abstract live range, and we need
13796          * one which is instruction precise.
13797          * FIXME: Variables used in out-of-line bblocks have a hole in their live range.
13798          */
13799         /* FIXME: Only do this if debugging info is requested */
13800         live_range_start = g_new0 (MonoInst*, cfg->next_vreg);
13801         live_range_end = g_new0 (MonoInst*, cfg->next_vreg);
13802         live_range_start_bb = g_new (MonoBasicBlock*, cfg->next_vreg);
13803         live_range_end_bb = g_new (MonoBasicBlock*, cfg->next_vreg);
13804         
13805         /* Add spill loads/stores */
13806         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
13807                 MonoInst *ins;
13808
13809                 if (cfg->verbose_level > 2)
13810                         printf ("\nSPILL BLOCK %d:\n", bb->block_num);
13811
13812                 /* Clear vreg_to_lvreg array */
13813                 for (i = 0; i < lvregs_len; i++)
13814                         vreg_to_lvreg [lvregs [i]] = 0;
13815                 lvregs_len = 0;
13816
13817                 cfg->cbb = bb;
13818                 MONO_BB_FOR_EACH_INS (bb, ins) {
13819                         const char *spec = INS_INFO (ins->opcode);
13820                         int regtype, srcindex, sreg, tmp_reg, prev_dreg, num_sregs;
13821                         gboolean store, no_lvreg;
13822                         int sregs [MONO_MAX_SRC_REGS];
13823
13824                         if (G_UNLIKELY (cfg->verbose_level > 2))
13825                                 mono_print_ins (ins);
13826
13827                         if (ins->opcode == OP_NOP)
13828                                 continue;
13829
13830                         /* 
13831                          * We handle LDADDR here as well, since it can only be decomposed
13832                          * when variable addresses are known.
13833                          */
13834                         if (ins->opcode == OP_LDADDR) {
13835                                 MonoInst *var = (MonoInst *)ins->inst_p0;
13836
13837                                 if (var->opcode == OP_VTARG_ADDR) {
13838                                         /* Happens on SPARC/S390 where vtypes are passed by reference */
13839                                         MonoInst *vtaddr = var->inst_left;
13840                                         if (vtaddr->opcode == OP_REGVAR) {
13841                                                 ins->opcode = OP_MOVE;
13842                                                 ins->sreg1 = vtaddr->dreg;
13843                                         }
13844                                         else if (var->inst_left->opcode == OP_REGOFFSET) {
13845                                                 ins->opcode = OP_LOAD_MEMBASE;
13846                                                 ins->inst_basereg = vtaddr->inst_basereg;
13847                                                 ins->inst_offset = vtaddr->inst_offset;
13848                                         } else
13849                                                 NOT_IMPLEMENTED;
13850                                 } else if (cfg->gsharedvt && cfg->gsharedvt_vreg_to_idx [var->dreg] < 0) {
13851                                         /* gsharedvt arg passed by ref */
13852                                         g_assert (var->opcode == OP_GSHAREDVT_ARG_REGOFFSET);
13853
13854                                         ins->opcode = OP_LOAD_MEMBASE;
13855                                         ins->inst_basereg = var->inst_basereg;
13856                                         ins->inst_offset = var->inst_offset;
13857                                 } else if (cfg->gsharedvt && cfg->gsharedvt_vreg_to_idx [var->dreg]) {
13858                                         MonoInst *load, *load2, *load3;
13859                                         int idx = cfg->gsharedvt_vreg_to_idx [var->dreg] - 1;
13860                                         int reg1, reg2, reg3;
13861                                         MonoInst *info_var = cfg->gsharedvt_info_var;
13862                                         MonoInst *locals_var = cfg->gsharedvt_locals_var;
13863
13864                                         /*
13865                                          * gsharedvt local.
13866                                          * Compute the address of the local as gsharedvt_locals_var + gsharedvt_info_var->locals_offsets [idx].
13867                                          */
13868
13869                                         g_assert (var->opcode == OP_GSHAREDVT_LOCAL);
13870
13871                                         g_assert (info_var);
13872                                         g_assert (locals_var);
13873
13874                                         /* Mark the instruction used to compute the locals var as used */
13875                                         cfg->gsharedvt_locals_var_ins = NULL;
13876
13877                                         /* Load the offset */
13878                                         if (info_var->opcode == OP_REGOFFSET) {
13879                                                 reg1 = alloc_ireg (cfg);
13880                                                 NEW_LOAD_MEMBASE (cfg, load, OP_LOAD_MEMBASE, reg1, info_var->inst_basereg, info_var->inst_offset);
13881                                         } else if (info_var->opcode == OP_REGVAR) {
13882                                                 load = NULL;
13883                                                 reg1 = info_var->dreg;
13884                                         } else {
13885                                                 g_assert_not_reached ();
13886                                         }
13887                                         reg2 = alloc_ireg (cfg);
13888                                         NEW_LOAD_MEMBASE (cfg, load2, OP_LOADI4_MEMBASE, reg2, reg1, MONO_STRUCT_OFFSET (MonoGSharedVtMethodRuntimeInfo, entries) + (idx * sizeof (gpointer)));
13889                                         /* Load the locals area address */
13890                                         reg3 = alloc_ireg (cfg);
13891                                         if (locals_var->opcode == OP_REGOFFSET) {
13892                                                 NEW_LOAD_MEMBASE (cfg, load3, OP_LOAD_MEMBASE, reg3, locals_var->inst_basereg, locals_var->inst_offset);
13893                                         } else if (locals_var->opcode == OP_REGVAR) {
13894                                                 NEW_UNALU (cfg, load3, OP_MOVE, reg3, locals_var->dreg);
13895                                         } else {
13896                                                 g_assert_not_reached ();
13897                                         }
13898                                         /* Compute the address */
13899                                         ins->opcode = OP_PADD;
13900                                         ins->sreg1 = reg3;
13901                                         ins->sreg2 = reg2;
13902
13903                                         mono_bblock_insert_before_ins (bb, ins, load3);
13904                                         mono_bblock_insert_before_ins (bb, load3, load2);
13905                                         if (load)
13906                                                 mono_bblock_insert_before_ins (bb, load2, load);
13907                                 } else {
13908                                         g_assert (var->opcode == OP_REGOFFSET);
13909
13910                                         ins->opcode = OP_ADD_IMM;
13911                                         ins->sreg1 = var->inst_basereg;
13912                                         ins->inst_imm = var->inst_offset;
13913                                 }
13914
13915                                 *need_local_opts = TRUE;
13916                                 spec = INS_INFO (ins->opcode);
13917                         }
13918
13919                         if (ins->opcode < MONO_CEE_LAST) {
13920                                 mono_print_ins (ins);
13921                                 g_assert_not_reached ();
13922                         }
13923
13924                         /*
13925                          * Store opcodes have destbasereg in the dreg, but in reality, it is an
13926                          * src register.
13927                          * FIXME:
13928                          */
13929                         if (MONO_IS_STORE_MEMBASE (ins)) {
13930                                 tmp_reg = ins->dreg;
13931                                 ins->dreg = ins->sreg2;
13932                                 ins->sreg2 = tmp_reg;
13933                                 store = TRUE;
13934
13935                                 spec2 [MONO_INST_DEST] = ' ';
13936                                 spec2 [MONO_INST_SRC1] = spec [MONO_INST_SRC1];
13937                                 spec2 [MONO_INST_SRC2] = spec [MONO_INST_DEST];
13938                                 spec2 [MONO_INST_SRC3] = ' ';
13939                                 spec = spec2;
13940                         } else if (MONO_IS_STORE_MEMINDEX (ins))
13941                                 g_assert_not_reached ();
13942                         else
13943                                 store = FALSE;
13944                         no_lvreg = FALSE;
13945
13946                         if (G_UNLIKELY (cfg->verbose_level > 2)) {
13947                                 printf ("\t %.3s %d", spec, ins->dreg);
13948                                 num_sregs = mono_inst_get_src_registers (ins, sregs);
13949                                 for (srcindex = 0; srcindex < num_sregs; ++srcindex)
13950                                         printf (" %d", sregs [srcindex]);
13951                                 printf ("\n");
13952                         }
13953
13954                         /***************/
13955                         /*    DREG     */
13956                         /***************/
13957                         regtype = spec [MONO_INST_DEST];
13958                         g_assert (((ins->dreg == -1) && (regtype == ' ')) || ((ins->dreg != -1) && (regtype != ' ')));
13959                         prev_dreg = -1;
13960
13961                         if ((ins->dreg != -1) && get_vreg_to_inst (cfg, ins->dreg)) {
13962                                 MonoInst *var = get_vreg_to_inst (cfg, ins->dreg);
13963                                 MonoInst *store_ins;
13964                                 int store_opcode;
13965                                 MonoInst *def_ins = ins;
13966                                 int dreg = ins->dreg; /* The original vreg */
13967
13968                                 store_opcode = mono_type_to_store_membase (cfg, var->inst_vtype);
13969
13970                                 if (var->opcode == OP_REGVAR) {
13971                                         ins->dreg = var->dreg;
13972                                 } 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)) {
13973                                         /* 
13974                                          * Instead of emitting a load+store, use a _membase opcode.
13975                                          */
13976                                         g_assert (var->opcode == OP_REGOFFSET);
13977                                         if (ins->opcode == OP_MOVE) {
13978                                                 NULLIFY_INS (ins);
13979                                                 def_ins = NULL;
13980                                         } else {
13981                                                 ins->opcode = op_to_op_dest_membase (store_opcode, ins->opcode);
13982                                                 ins->inst_basereg = var->inst_basereg;
13983                                                 ins->inst_offset = var->inst_offset;
13984                                                 ins->dreg = -1;
13985                                         }
13986                                         spec = INS_INFO (ins->opcode);
13987                                 } else {
13988                                         guint32 lvreg;
13989
13990                                         g_assert (var->opcode == OP_REGOFFSET);
13991
13992                                         prev_dreg = ins->dreg;
13993
13994                                         /* Invalidate any previous lvreg for this vreg */
13995                                         vreg_to_lvreg [ins->dreg] = 0;
13996
13997                                         lvreg = 0;
13998
13999                                         if (COMPILE_SOFT_FLOAT (cfg) && store_opcode == OP_STORER8_MEMBASE_REG) {
14000                                                 regtype = 'l';
14001                                                 store_opcode = OP_STOREI8_MEMBASE_REG;
14002                                         }
14003
14004                                         ins->dreg = alloc_dreg (cfg, stacktypes [regtype]);
14005
14006 #if SIZEOF_REGISTER != 8
14007                                         if (regtype == 'l') {
14008                                                 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));
14009                                                 mono_bblock_insert_after_ins (bb, ins, store_ins);
14010                                                 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));
14011                                                 mono_bblock_insert_after_ins (bb, ins, store_ins);
14012                                                 def_ins = store_ins;
14013                                         }
14014                                         else
14015 #endif
14016                                         {
14017                                                 g_assert (store_opcode != OP_STOREV_MEMBASE);
14018
14019                                                 /* Try to fuse the store into the instruction itself */
14020                                                 /* FIXME: Add more instructions */
14021                                                 if (!lvreg && ((ins->opcode == OP_ICONST) || ((ins->opcode == OP_I8CONST) && (ins->inst_c0 == 0)))) {
14022                                                         ins->opcode = store_membase_reg_to_store_membase_imm (store_opcode);
14023                                                         ins->inst_imm = ins->inst_c0;
14024                                                         ins->inst_destbasereg = var->inst_basereg;
14025                                                         ins->inst_offset = var->inst_offset;
14026                                                         spec = INS_INFO (ins->opcode);
14027                                                 } else if (!lvreg && ((ins->opcode == OP_MOVE) || (ins->opcode == OP_FMOVE) || (ins->opcode == OP_LMOVE) || (ins->opcode == OP_RMOVE))) {
14028                                                         ins->opcode = store_opcode;
14029                                                         ins->inst_destbasereg = var->inst_basereg;
14030                                                         ins->inst_offset = var->inst_offset;
14031
14032                                                         no_lvreg = TRUE;
14033
14034                                                         tmp_reg = ins->dreg;
14035                                                         ins->dreg = ins->sreg2;
14036                                                         ins->sreg2 = tmp_reg;
14037                                                         store = TRUE;
14038
14039                                                         spec2 [MONO_INST_DEST] = ' ';
14040                                                         spec2 [MONO_INST_SRC1] = spec [MONO_INST_SRC1];
14041                                                         spec2 [MONO_INST_SRC2] = spec [MONO_INST_DEST];
14042                                                         spec2 [MONO_INST_SRC3] = ' ';
14043                                                         spec = spec2;
14044                                                 } else if (!lvreg && (op_to_op_store_membase (store_opcode, ins->opcode) != -1)) {
14045                                                         // FIXME: The backends expect the base reg to be in inst_basereg
14046                                                         ins->opcode = op_to_op_store_membase (store_opcode, ins->opcode);
14047                                                         ins->dreg = -1;
14048                                                         ins->inst_basereg = var->inst_basereg;
14049                                                         ins->inst_offset = var->inst_offset;
14050                                                         spec = INS_INFO (ins->opcode);
14051                                                 } else {
14052                                                         /* printf ("INS: "); mono_print_ins (ins); */
14053                                                         /* Create a store instruction */
14054                                                         NEW_STORE_MEMBASE (cfg, store_ins, store_opcode, var->inst_basereg, var->inst_offset, ins->dreg);
14055
14056                                                         /* Insert it after the instruction */
14057                                                         mono_bblock_insert_after_ins (bb, ins, store_ins);
14058
14059                                                         def_ins = store_ins;
14060
14061                                                         /* 
14062                                                          * We can't assign ins->dreg to var->dreg here, since the
14063                                                          * sregs could use it. So set a flag, and do it after
14064                                                          * the sregs.
14065                                                          */
14066                                                         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)))
14067                                                                 dest_has_lvreg = TRUE;
14068                                                 }
14069                                         }
14070                                 }
14071
14072                                 if (def_ins && !live_range_start [dreg]) {
14073                                         live_range_start [dreg] = def_ins;
14074                                         live_range_start_bb [dreg] = bb;
14075                                 }
14076
14077                                 if (cfg->compute_gc_maps && def_ins && (var->flags & MONO_INST_GC_TRACK)) {
14078                                         MonoInst *tmp;
14079
14080                                         MONO_INST_NEW (cfg, tmp, OP_GC_LIVENESS_DEF);
14081                                         tmp->inst_c1 = dreg;
14082                                         mono_bblock_insert_after_ins (bb, def_ins, tmp);
14083                                 }
14084                         }
14085
14086                         /************/
14087                         /*  SREGS   */
14088                         /************/
14089                         num_sregs = mono_inst_get_src_registers (ins, sregs);
14090                         for (srcindex = 0; srcindex < 3; ++srcindex) {
14091                                 regtype = spec [MONO_INST_SRC1 + srcindex];
14092                                 sreg = sregs [srcindex];
14093
14094                                 g_assert (((sreg == -1) && (regtype == ' ')) || ((sreg != -1) && (regtype != ' ')));
14095                                 if ((sreg != -1) && get_vreg_to_inst (cfg, sreg)) {
14096                                         MonoInst *var = get_vreg_to_inst (cfg, sreg);
14097                                         MonoInst *use_ins = ins;
14098                                         MonoInst *load_ins;
14099                                         guint32 load_opcode;
14100
14101                                         if (var->opcode == OP_REGVAR) {
14102                                                 sregs [srcindex] = var->dreg;
14103                                                 //mono_inst_set_src_registers (ins, sregs);
14104                                                 live_range_end [sreg] = use_ins;
14105                                                 live_range_end_bb [sreg] = bb;
14106
14107                                                 if (cfg->compute_gc_maps && var->dreg < orig_next_vreg && (var->flags & MONO_INST_GC_TRACK)) {
14108                                                         MonoInst *tmp;
14109
14110                                                         MONO_INST_NEW (cfg, tmp, OP_GC_LIVENESS_USE);
14111                                                         /* var->dreg is a hreg */
14112                                                         tmp->inst_c1 = sreg;
14113                                                         mono_bblock_insert_after_ins (bb, ins, tmp);
14114                                                 }
14115
14116                                                 continue;
14117                                         }
14118
14119                                         g_assert (var->opcode == OP_REGOFFSET);
14120                                                 
14121                                         load_opcode = mono_type_to_load_membase (cfg, var->inst_vtype);
14122
14123                                         g_assert (load_opcode != OP_LOADV_MEMBASE);
14124
14125                                         if (vreg_to_lvreg [sreg]) {
14126                                                 g_assert (vreg_to_lvreg [sreg] != -1);
14127
14128                                                 /* The variable is already loaded to an lvreg */
14129                                                 if (G_UNLIKELY (cfg->verbose_level > 2))
14130                                                         printf ("\t\tUse lvreg R%d for R%d.\n", vreg_to_lvreg [sreg], sreg);
14131                                                 sregs [srcindex] = vreg_to_lvreg [sreg];
14132                                                 //mono_inst_set_src_registers (ins, sregs);
14133                                                 continue;
14134                                         }
14135
14136                                         /* Try to fuse the load into the instruction */
14137                                         if ((srcindex == 0) && (op_to_op_src1_membase (cfg, load_opcode, ins->opcode) != -1)) {
14138                                                 ins->opcode = op_to_op_src1_membase (cfg, load_opcode, ins->opcode);
14139                                                 sregs [0] = var->inst_basereg;
14140                                                 //mono_inst_set_src_registers (ins, sregs);
14141                                                 ins->inst_offset = var->inst_offset;
14142                                         } else if ((srcindex == 1) && (op_to_op_src2_membase (cfg, load_opcode, ins->opcode) != -1)) {
14143                                                 ins->opcode = op_to_op_src2_membase (cfg, load_opcode, ins->opcode);
14144                                                 sregs [1] = var->inst_basereg;
14145                                                 //mono_inst_set_src_registers (ins, sregs);
14146                                                 ins->inst_offset = var->inst_offset;
14147                                         } else {
14148                                                 if (MONO_IS_REAL_MOVE (ins)) {
14149                                                         ins->opcode = OP_NOP;
14150                                                         sreg = ins->dreg;
14151                                                 } else {
14152                                                         //printf ("%d ", srcindex); mono_print_ins (ins);
14153
14154                                                         sreg = alloc_dreg (cfg, stacktypes [regtype]);
14155
14156                                                         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) {
14157                                                                 if (var->dreg == prev_dreg) {
14158                                                                         /*
14159                                                                          * sreg refers to the value loaded by the load
14160                                                                          * emitted below, but we need to use ins->dreg
14161                                                                          * since it refers to the store emitted earlier.
14162                                                                          */
14163                                                                         sreg = ins->dreg;
14164                                                                 }
14165                                                                 g_assert (sreg != -1);
14166                                                                 vreg_to_lvreg [var->dreg] = sreg;
14167                                                                 if (lvregs_len >= lvregs_size) {
14168                                                                         guint32 *new_lvregs = mono_mempool_alloc0 (cfg->mempool, sizeof (guint32) * lvregs_size * 2);
14169                                                                         memcpy (new_lvregs, lvregs, sizeof (guint32) * lvregs_size);
14170                                                                         lvregs = new_lvregs;
14171                                                                         lvregs_size *= 2;
14172                                                                 }
14173                                                                 lvregs [lvregs_len ++] = var->dreg;
14174                                                         }
14175                                                 }
14176
14177                                                 sregs [srcindex] = sreg;
14178                                                 //mono_inst_set_src_registers (ins, sregs);
14179
14180 #if SIZEOF_REGISTER != 8
14181                                                 if (regtype == 'l') {
14182                                                         NEW_LOAD_MEMBASE (cfg, load_ins, OP_LOADI4_MEMBASE, MONO_LVREG_MS (sreg), var->inst_basereg, var->inst_offset + MINI_MS_WORD_OFFSET);
14183                                                         mono_bblock_insert_before_ins (bb, ins, load_ins);
14184                                                         NEW_LOAD_MEMBASE (cfg, load_ins, OP_LOADI4_MEMBASE, MONO_LVREG_LS (sreg), var->inst_basereg, var->inst_offset + MINI_LS_WORD_OFFSET);
14185                                                         mono_bblock_insert_before_ins (bb, ins, load_ins);
14186                                                         use_ins = load_ins;
14187                                                 }
14188                                                 else
14189 #endif
14190                                                 {
14191 #if SIZEOF_REGISTER == 4
14192                                                         g_assert (load_opcode != OP_LOADI8_MEMBASE);
14193 #endif
14194                                                         NEW_LOAD_MEMBASE (cfg, load_ins, load_opcode, sreg, var->inst_basereg, var->inst_offset);
14195                                                         mono_bblock_insert_before_ins (bb, ins, load_ins);
14196                                                         use_ins = load_ins;
14197                                                 }
14198                                         }
14199
14200                                         if (var->dreg < orig_next_vreg) {
14201                                                 live_range_end [var->dreg] = use_ins;
14202                                                 live_range_end_bb [var->dreg] = bb;
14203                                         }
14204
14205                                         if (cfg->compute_gc_maps && var->dreg < orig_next_vreg && (var->flags & MONO_INST_GC_TRACK)) {
14206                                                 MonoInst *tmp;
14207
14208                                                 MONO_INST_NEW (cfg, tmp, OP_GC_LIVENESS_USE);
14209                                                 tmp->inst_c1 = var->dreg;
14210                                                 mono_bblock_insert_after_ins (bb, ins, tmp);
14211                                         }
14212                                 }
14213                         }
14214                         mono_inst_set_src_registers (ins, sregs);
14215
14216                         if (dest_has_lvreg) {
14217                                 g_assert (ins->dreg != -1);
14218                                 vreg_to_lvreg [prev_dreg] = ins->dreg;
14219                                 if (lvregs_len >= lvregs_size) {
14220                                         guint32 *new_lvregs = mono_mempool_alloc0 (cfg->mempool, sizeof (guint32) * lvregs_size * 2);
14221                                         memcpy (new_lvregs, lvregs, sizeof (guint32) * lvregs_size);
14222                                         lvregs = new_lvregs;
14223                                         lvregs_size *= 2;
14224                                 }
14225                                 lvregs [lvregs_len ++] = prev_dreg;
14226                                 dest_has_lvreg = FALSE;
14227                         }
14228
14229                         if (store) {
14230                                 tmp_reg = ins->dreg;
14231                                 ins->dreg = ins->sreg2;
14232                                 ins->sreg2 = tmp_reg;
14233                         }
14234
14235                         if (MONO_IS_CALL (ins)) {
14236                                 /* Clear vreg_to_lvreg array */
14237                                 for (i = 0; i < lvregs_len; i++)
14238                                         vreg_to_lvreg [lvregs [i]] = 0;
14239                                 lvregs_len = 0;
14240                         } else if (ins->opcode == OP_NOP) {
14241                                 ins->dreg = -1;
14242                                 MONO_INST_NULLIFY_SREGS (ins);
14243                         }
14244
14245                         if (cfg->verbose_level > 2)
14246                                 mono_print_ins_index (1, ins);
14247                 }
14248
14249                 /* Extend the live range based on the liveness info */
14250                 if (cfg->compute_precise_live_ranges && bb->live_out_set && bb->code) {
14251                         for (i = 0; i < cfg->num_varinfo; i ++) {
14252                                 MonoMethodVar *vi = MONO_VARINFO (cfg, i);
14253
14254                                 if (vreg_is_volatile (cfg, vi->vreg))
14255                                         /* The liveness info is incomplete */
14256                                         continue;
14257
14258                                 if (mono_bitset_test_fast (bb->live_in_set, i) && !live_range_start [vi->vreg]) {
14259                                         /* Live from at least the first ins of this bb */
14260                                         live_range_start [vi->vreg] = bb->code;
14261                                         live_range_start_bb [vi->vreg] = bb;
14262                                 }
14263
14264                                 if (mono_bitset_test_fast (bb->live_out_set, i)) {
14265                                         /* Live at least until the last ins of this bb */
14266                                         live_range_end [vi->vreg] = bb->last_ins;
14267                                         live_range_end_bb [vi->vreg] = bb;
14268                                 }
14269                         }
14270                 }
14271         }
14272         
14273         /*
14274          * Emit LIVERANGE_START/LIVERANGE_END opcodes, the backend will implement them
14275          * by storing the current native offset into MonoMethodVar->live_range_start/end.
14276          */
14277         if (cfg->backend->have_liverange_ops && cfg->compute_precise_live_ranges && cfg->comp_done & MONO_COMP_LIVENESS) {
14278                 for (i = 0; i < cfg->num_varinfo; ++i) {
14279                         int vreg = MONO_VARINFO (cfg, i)->vreg;
14280                         MonoInst *ins;
14281
14282                         if (live_range_start [vreg]) {
14283                                 MONO_INST_NEW (cfg, ins, OP_LIVERANGE_START);
14284                                 ins->inst_c0 = i;
14285                                 ins->inst_c1 = vreg;
14286                                 mono_bblock_insert_after_ins (live_range_start_bb [vreg], live_range_start [vreg], ins);
14287                         }
14288                         if (live_range_end [vreg]) {
14289                                 MONO_INST_NEW (cfg, ins, OP_LIVERANGE_END);
14290                                 ins->inst_c0 = i;
14291                                 ins->inst_c1 = vreg;
14292                                 if (live_range_end [vreg] == live_range_end_bb [vreg]->last_ins)
14293                                         mono_add_ins_to_end (live_range_end_bb [vreg], ins);
14294                                 else
14295                                         mono_bblock_insert_after_ins (live_range_end_bb [vreg], live_range_end [vreg], ins);
14296                         }
14297                 }
14298         }
14299
14300         if (cfg->gsharedvt_locals_var_ins) {
14301                 /* Nullify if unused */
14302                 cfg->gsharedvt_locals_var_ins->opcode = OP_PCONST;
14303                 cfg->gsharedvt_locals_var_ins->inst_imm = 0;
14304         }
14305
14306         g_free (live_range_start);
14307         g_free (live_range_end);
14308         g_free (live_range_start_bb);
14309         g_free (live_range_end_bb);
14310 }
14311
14312
14313 /**
14314  * FIXME:
14315  * - use 'iadd' instead of 'int_add'
14316  * - handling ovf opcodes: decompose in method_to_ir.
14317  * - unify iregs/fregs
14318  *   -> partly done, the missing parts are:
14319  *   - a more complete unification would involve unifying the hregs as well, so
14320  *     code wouldn't need if (fp) all over the place. but that would mean the hregs
14321  *     would no longer map to the machine hregs, so the code generators would need to
14322  *     be modified. Also, on ia64 for example, niregs + nfregs > 256 -> bitmasks
14323  *     wouldn't work any more. Duplicating the code in mono_local_regalloc () into
14324  *     fp/non-fp branches speeds it up by about 15%.
14325  * - use sext/zext opcodes instead of shifts
14326  * - add OP_ICALL
14327  * - get rid of TEMPLOADs if possible and use vregs instead
14328  * - clean up usage of OP_P/OP_ opcodes
14329  * - cleanup usage of DUMMY_USE
14330  * - cleanup the setting of ins->type for MonoInst's which are pushed on the 
14331  *   stack
14332  * - set the stack type and allocate a dreg in the EMIT_NEW macros
14333  * - get rid of all the <foo>2 stuff when the new JIT is ready.
14334  * - make sure handle_stack_args () is called before the branch is emitted
14335  * - when the new IR is done, get rid of all unused stuff
14336  * - COMPARE/BEQ as separate instructions or unify them ?
14337  *   - keeping them separate allows specialized compare instructions like
14338  *     compare_imm, compare_membase
14339  *   - most back ends unify fp compare+branch, fp compare+ceq
14340  * - integrate mono_save_args into inline_method
14341  * - get rid of the empty bblocks created by MONO_EMIT_NEW_BRACH_BLOCK2
14342  * - handle long shift opts on 32 bit platforms somehow: they require 
14343  *   3 sregs (2 for arg1 and 1 for arg2)
14344  * - make byref a 'normal' type.
14345  * - use vregs for bb->out_stacks if possible, handle_global_vreg will make them a
14346  *   variable if needed.
14347  * - do not start a new IL level bblock when cfg->cbb is changed by a function call
14348  *   like inline_method.
14349  * - remove inlining restrictions
14350  * - fix LNEG and enable cfold of INEG
14351  * - generalize x86 optimizations like ldelema as a peephole optimization
14352  * - add store_mem_imm for amd64
14353  * - optimize the loading of the interruption flag in the managed->native wrappers
14354  * - avoid special handling of OP_NOP in passes
14355  * - move code inserting instructions into one function/macro.
14356  * - try a coalescing phase after liveness analysis
14357  * - add float -> vreg conversion + local optimizations on !x86
14358  * - figure out how to handle decomposed branches during optimizations, ie.
14359  *   compare+branch, op_jump_table+op_br etc.
14360  * - promote RuntimeXHandles to vregs
14361  * - vtype cleanups:
14362  *   - add a NEW_VARLOADA_VREG macro
14363  * - the vtype optimizations are blocked by the LDADDR opcodes generated for 
14364  *   accessing vtype fields.
14365  * - get rid of I8CONST on 64 bit platforms
14366  * - dealing with the increase in code size due to branches created during opcode
14367  *   decomposition:
14368  *   - use extended basic blocks
14369  *     - all parts of the JIT
14370  *     - handle_global_vregs () && local regalloc
14371  *   - avoid introducing global vregs during decomposition, like 'vtable' in isinst
14372  * - sources of increase in code size:
14373  *   - vtypes
14374  *   - long compares
14375  *   - isinst and castclass
14376  *   - lvregs not allocated to global registers even if used multiple times
14377  * - call cctors outside the JIT, to make -v output more readable and JIT timings more
14378  *   meaningful.
14379  * - check for fp stack leakage in other opcodes too. (-> 'exceptions' optimization)
14380  * - add all micro optimizations from the old JIT
14381  * - put tree optimizations into the deadce pass
14382  * - decompose op_start_handler/op_endfilter/op_endfinally earlier using an arch
14383  *   specific function.
14384  * - unify the float comparison opcodes with the other comparison opcodes, i.e.
14385  *   fcompare + branchCC.
14386  * - create a helper function for allocating a stack slot, taking into account 
14387  *   MONO_CFG_HAS_SPILLUP.
14388  * - merge r68207.
14389  * - merge the ia64 switch changes.
14390  * - optimize mono_regstate2_alloc_int/float.
14391  * - fix the pessimistic handling of variables accessed in exception handler blocks.
14392  * - need to write a tree optimization pass, but the creation of trees is difficult, i.e.
14393  *   parts of the tree could be separated by other instructions, killing the tree
14394  *   arguments, or stores killing loads etc. Also, should we fold loads into other
14395  *   instructions if the result of the load is used multiple times ?
14396  * - make the REM_IMM optimization in mini-x86.c arch-independent.
14397  * - LAST MERGE: 108395.
14398  * - when returning vtypes in registers, generate IR and append it to the end of the
14399  *   last bb instead of doing it in the epilog.
14400  * - change the store opcodes so they use sreg1 instead of dreg to store the base register.
14401  */
14402
14403 /*
14404
14405 NOTES
14406 -----
14407
14408 - When to decompose opcodes:
14409   - earlier: this makes some optimizations hard to implement, since the low level IR
14410   no longer contains the neccessary information. But it is easier to do.
14411   - later: harder to implement, enables more optimizations.
14412 - Branches inside bblocks:
14413   - created when decomposing complex opcodes. 
14414     - branches to another bblock: harmless, but not tracked by the branch 
14415       optimizations, so need to branch to a label at the start of the bblock.
14416     - branches to inside the same bblock: very problematic, trips up the local
14417       reg allocator. Can be fixed by spitting the current bblock, but that is a
14418       complex operation, since some local vregs can become global vregs etc.
14419 - Local/global vregs:
14420   - local vregs: temporary vregs used inside one bblock. Assigned to hregs by the
14421     local register allocator.
14422   - global vregs: used in more than one bblock. Have an associated MonoMethodVar
14423     structure, created by mono_create_var (). Assigned to hregs or the stack by
14424     the global register allocator.
14425 - When to do optimizations like alu->alu_imm:
14426   - earlier -> saves work later on since the IR will be smaller/simpler
14427   - later -> can work on more instructions
14428 - Handling of valuetypes:
14429   - When a vtype is pushed on the stack, a new temporary is created, an 
14430     instruction computing its address (LDADDR) is emitted and pushed on
14431     the stack. Need to optimize cases when the vtype is used immediately as in
14432     argument passing, stloc etc.
14433 - Instead of the to_end stuff in the old JIT, simply call the function handling
14434   the values on the stack before emitting the last instruction of the bb.
14435 */
14436
14437 #else /* !DISABLE_JIT */
14438
14439 void
14440 mono_set_break_policy (MonoBreakPolicyFunc policy_callback)
14441 {
14442 }
14443
14444 #endif /* !DISABLE_JIT */