[jit] Make newarr [void] unverified. Fixes #55083.
[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 inline static MonoInst*
152 mono_emit_calli (MonoCompile *cfg, MonoMethodSignature *sig, MonoInst **args, MonoInst *addr, MonoInst *imt_arg, MonoInst *rgctx_arg);
153
154 /* helper methods signatures */
155 static MonoMethodSignature *helper_sig_domain_get;
156 static MonoMethodSignature *helper_sig_rgctx_lazy_fetch_trampoline;
157 static MonoMethodSignature *helper_sig_llvmonly_imt_trampoline;
158 static MonoMethodSignature *helper_sig_jit_thread_attach;
159 static MonoMethodSignature *helper_sig_get_tls_tramp;
160 static MonoMethodSignature *helper_sig_set_tls_tramp;
161
162 /* type loading helpers */
163 static GENERATE_GET_CLASS_WITH_CACHE (runtime_helpers, "System.Runtime.CompilerServices", "RuntimeHelpers")
164 static GENERATE_TRY_GET_CLASS_WITH_CACHE (debuggable_attribute, "System.Diagnostics", "DebuggableAttribute")
165
166 /*
167  * Instruction metadata
168  */
169 #ifdef MINI_OP
170 #undef MINI_OP
171 #endif
172 #ifdef MINI_OP3
173 #undef MINI_OP3
174 #endif
175 #define MINI_OP(a,b,dest,src1,src2) dest, src1, src2, ' ',
176 #define MINI_OP3(a,b,dest,src1,src2,src3) dest, src1, src2, src3,
177 #define NONE ' '
178 #define IREG 'i'
179 #define FREG 'f'
180 #define VREG 'v'
181 #define XREG 'x'
182 #if SIZEOF_REGISTER == 8 && SIZEOF_REGISTER == SIZEOF_VOID_P
183 #define LREG IREG
184 #else
185 #define LREG 'l'
186 #endif
187 /* keep in sync with the enum in mini.h */
188 const char
189 ins_info[] = {
190 #include "mini-ops.h"
191 };
192 #undef MINI_OP
193 #undef MINI_OP3
194
195 #define MINI_OP(a,b,dest,src1,src2) ((src2) != NONE ? 2 : ((src1) != NONE ? 1 : 0)),
196 #define MINI_OP3(a,b,dest,src1,src2,src3) ((src3) != NONE ? 3 : ((src2) != NONE ? 2 : ((src1) != NONE ? 1 : 0))),
197 /* 
198  * This should contain the index of the last sreg + 1. This is not the same
199  * as the number of sregs for opcodes like IA64_CMP_EQ_IMM.
200  */
201 const gint8 ins_sreg_counts[] = {
202 #include "mini-ops.h"
203 };
204 #undef MINI_OP
205 #undef MINI_OP3
206
207 guint32
208 mono_alloc_ireg (MonoCompile *cfg)
209 {
210         return alloc_ireg (cfg);
211 }
212
213 guint32
214 mono_alloc_lreg (MonoCompile *cfg)
215 {
216         return alloc_lreg (cfg);
217 }
218
219 guint32
220 mono_alloc_freg (MonoCompile *cfg)
221 {
222         return alloc_freg (cfg);
223 }
224
225 guint32
226 mono_alloc_preg (MonoCompile *cfg)
227 {
228         return alloc_preg (cfg);
229 }
230
231 guint32
232 mono_alloc_dreg (MonoCompile *cfg, MonoStackType stack_type)
233 {
234         return alloc_dreg (cfg, stack_type);
235 }
236
237 /*
238  * mono_alloc_ireg_ref:
239  *
240  *   Allocate an IREG, and mark it as holding a GC ref.
241  */
242 guint32
243 mono_alloc_ireg_ref (MonoCompile *cfg)
244 {
245         return alloc_ireg_ref (cfg);
246 }
247
248 /*
249  * mono_alloc_ireg_mp:
250  *
251  *   Allocate an IREG, and mark it as holding a managed pointer.
252  */
253 guint32
254 mono_alloc_ireg_mp (MonoCompile *cfg)
255 {
256         return alloc_ireg_mp (cfg);
257 }
258
259 /*
260  * mono_alloc_ireg_copy:
261  *
262  *   Allocate an IREG with the same GC type as VREG.
263  */
264 guint32
265 mono_alloc_ireg_copy (MonoCompile *cfg, guint32 vreg)
266 {
267         if (vreg_is_ref (cfg, vreg))
268                 return alloc_ireg_ref (cfg);
269         else if (vreg_is_mp (cfg, vreg))
270                 return alloc_ireg_mp (cfg);
271         else
272                 return alloc_ireg (cfg);
273 }
274
275 guint
276 mono_type_to_regmove (MonoCompile *cfg, MonoType *type)
277 {
278         if (type->byref)
279                 return OP_MOVE;
280
281         type = mini_get_underlying_type (type);
282 handle_enum:
283         switch (type->type) {
284         case MONO_TYPE_I1:
285         case MONO_TYPE_U1:
286                 return OP_MOVE;
287         case MONO_TYPE_I2:
288         case MONO_TYPE_U2:
289                 return OP_MOVE;
290         case MONO_TYPE_I4:
291         case MONO_TYPE_U4:
292                 return OP_MOVE;
293         case MONO_TYPE_I:
294         case MONO_TYPE_U:
295         case MONO_TYPE_PTR:
296         case MONO_TYPE_FNPTR:
297                 return OP_MOVE;
298         case MONO_TYPE_CLASS:
299         case MONO_TYPE_STRING:
300         case MONO_TYPE_OBJECT:
301         case MONO_TYPE_SZARRAY:
302         case MONO_TYPE_ARRAY:    
303                 return OP_MOVE;
304         case MONO_TYPE_I8:
305         case MONO_TYPE_U8:
306 #if SIZEOF_REGISTER == 8
307                 return OP_MOVE;
308 #else
309                 return OP_LMOVE;
310 #endif
311         case MONO_TYPE_R4:
312                 return cfg->r4fp ? OP_RMOVE : OP_FMOVE;
313         case MONO_TYPE_R8:
314                 return OP_FMOVE;
315         case MONO_TYPE_VALUETYPE:
316                 if (type->data.klass->enumtype) {
317                         type = mono_class_enum_basetype (type->data.klass);
318                         goto handle_enum;
319                 }
320                 if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type (type)))
321                         return OP_XMOVE;
322                 return OP_VMOVE;
323         case MONO_TYPE_TYPEDBYREF:
324                 return OP_VMOVE;
325         case MONO_TYPE_GENERICINST:
326                 if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type (type)))
327                         return OP_XMOVE;
328                 type = &type->data.generic_class->container_class->byval_arg;
329                 goto handle_enum;
330         case MONO_TYPE_VAR:
331         case MONO_TYPE_MVAR:
332                 g_assert (cfg->gshared);
333                 if (mini_type_var_is_vt (type))
334                         return OP_VMOVE;
335                 else
336                         return mono_type_to_regmove (cfg, mini_get_underlying_type (type));
337         default:
338                 g_error ("unknown type 0x%02x in type_to_regstore", type->type);
339         }
340         return -1;
341 }
342
343 void
344 mono_print_bb (MonoBasicBlock *bb, const char *msg)
345 {
346         int i;
347         MonoInst *tree;
348         GString *str = g_string_new ("");
349
350         g_string_append_printf (str, "%s %d: [IN: ", msg, bb->block_num);
351         for (i = 0; i < bb->in_count; ++i)
352                 g_string_append_printf (str, " BB%d(%d)", bb->in_bb [i]->block_num, bb->in_bb [i]->dfn);
353         g_string_append_printf (str, ", OUT: ");
354         for (i = 0; i < bb->out_count; ++i)
355                 g_string_append_printf (str, " BB%d(%d)", bb->out_bb [i]->block_num, bb->out_bb [i]->dfn);
356         g_string_append_printf (str, " ]\n");
357
358         g_print ("%s", str->str);
359         g_string_free (str, TRUE);
360
361         for (tree = bb->code; tree; tree = tree->next)
362                 mono_print_ins_index (-1, tree);
363 }
364
365 void
366 mono_create_helper_signatures (void)
367 {
368         helper_sig_domain_get = mono_create_icall_signature ("ptr");
369         helper_sig_rgctx_lazy_fetch_trampoline = mono_create_icall_signature ("ptr ptr");
370         helper_sig_llvmonly_imt_trampoline = mono_create_icall_signature ("ptr ptr ptr");
371         helper_sig_jit_thread_attach = mono_create_icall_signature ("ptr ptr");
372         helper_sig_get_tls_tramp = mono_create_icall_signature ("ptr");
373         helper_sig_set_tls_tramp = mono_create_icall_signature ("void ptr");
374 }
375
376 static MONO_NEVER_INLINE void
377 break_on_unverified (void)
378 {
379         if (mini_get_debug_options ()->break_on_unverified)
380                 G_BREAKPOINT ();
381 }
382
383 static MONO_NEVER_INLINE void
384 field_access_failure (MonoCompile *cfg, MonoMethod *method, MonoClassField *field)
385 {
386         char *method_fname = mono_method_full_name (method, TRUE);
387         char *field_fname = mono_field_full_name (field);
388         mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
389         mono_error_set_generic_error (&cfg->error, "System", "FieldAccessException", "Field `%s' is inaccessible from method `%s'\n", field_fname, method_fname);
390         g_free (method_fname);
391         g_free (field_fname);
392 }
393
394 static MONO_NEVER_INLINE void
395 inline_failure (MonoCompile *cfg, const char *msg)
396 {
397         if (cfg->verbose_level >= 2)
398                 printf ("inline failed: %s\n", msg);
399         mono_cfg_set_exception (cfg, MONO_EXCEPTION_INLINE_FAILED);
400 }
401
402 static MONO_NEVER_INLINE void
403 gshared_failure (MonoCompile *cfg, int opcode, const char *file, int line)
404 {
405         if (cfg->verbose_level > 2)                                                                                     \
406                 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);
407         mono_cfg_set_exception (cfg, MONO_EXCEPTION_GENERIC_SHARING_FAILED);
408 }
409
410 static MONO_NEVER_INLINE void
411 gsharedvt_failure (MonoCompile *cfg, int opcode, const char *file, int line)
412 {
413         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);
414         if (cfg->verbose_level >= 2)
415                 printf ("%s\n", cfg->exception_message);
416         mono_cfg_set_exception (cfg, MONO_EXCEPTION_GENERIC_SHARING_FAILED);
417 }
418
419 /*
420  * When using gsharedvt, some instatiations might be verifiable, and some might be not. i.e. 
421  * foo<T> (int i) { ldarg.0; box T; }
422  */
423 #define UNVERIFIED do { \
424         if (cfg->gsharedvt) { \
425                 if (cfg->verbose_level > 2)                                                                     \
426                         printf ("gsharedvt method failed to verify, falling back to instantiation.\n"); \
427                 mono_cfg_set_exception (cfg, MONO_EXCEPTION_GENERIC_SHARING_FAILED); \
428                 goto exception_exit;                                                                                    \
429         }                                                                                                                                       \
430         break_on_unverified ();                                                                                         \
431         goto unverified;                                                                                                        \
432 } while (0)
433
434 #define GET_BBLOCK(cfg,tblock,ip) do {  \
435                 (tblock) = cfg->cil_offset_to_bb [(ip) - cfg->cil_start]; \
436                 if (!(tblock)) {        \
437                         if ((ip) >= end || (ip) < header->code) UNVERIFIED; \
438             NEW_BBLOCK (cfg, (tblock)); \
439                         (tblock)->cil_code = (ip);      \
440                         ADD_BBLOCK (cfg, (tblock));     \
441                 } \
442         } while (0)
443
444 #if defined(TARGET_X86) || defined(TARGET_AMD64)
445 #define EMIT_NEW_X86_LEA(cfg,dest,sr1,sr2,shift,imm) do { \
446                 MONO_INST_NEW (cfg, dest, OP_X86_LEA); \
447                 (dest)->dreg = alloc_ireg_mp ((cfg)); \
448                 (dest)->sreg1 = (sr1); \
449                 (dest)->sreg2 = (sr2); \
450                 (dest)->inst_imm = (imm); \
451                 (dest)->backend.shift_amount = (shift); \
452                 MONO_ADD_INS ((cfg)->cbb, (dest)); \
453         } while (0)
454 #endif
455
456 /* Emit conversions so both operands of a binary opcode are of the same type */
457 static void
458 add_widen_op (MonoCompile *cfg, MonoInst *ins, MonoInst **arg1_ref, MonoInst **arg2_ref)
459 {
460         MonoInst *arg1 = *arg1_ref;
461         MonoInst *arg2 = *arg2_ref;
462
463         if (cfg->r4fp &&
464                 ((arg1->type == STACK_R4 && arg2->type == STACK_R8) ||
465                  (arg1->type == STACK_R8 && arg2->type == STACK_R4))) {
466                 MonoInst *conv;
467
468                 /* Mixing r4/r8 is allowed by the spec */
469                 if (arg1->type == STACK_R4) {
470                         int dreg = alloc_freg (cfg);
471
472                         EMIT_NEW_UNALU (cfg, conv, OP_RCONV_TO_R8, dreg, arg1->dreg);
473                         conv->type = STACK_R8;
474                         ins->sreg1 = dreg;
475                         *arg1_ref = conv;
476                 }
477                 if (arg2->type == STACK_R4) {
478                         int dreg = alloc_freg (cfg);
479
480                         EMIT_NEW_UNALU (cfg, conv, OP_RCONV_TO_R8, dreg, arg2->dreg);
481                         conv->type = STACK_R8;
482                         ins->sreg2 = dreg;
483                         *arg2_ref = conv;
484                 }
485         }
486
487 #if SIZEOF_REGISTER == 8
488         /* FIXME: Need to add many more cases */
489         if ((arg1)->type == STACK_PTR && (arg2)->type == STACK_I4) {
490                 MonoInst *widen;
491
492                 int dr = alloc_preg (cfg);
493                 EMIT_NEW_UNALU (cfg, widen, OP_SEXT_I4, dr, (arg2)->dreg);
494                 (ins)->sreg2 = widen->dreg;
495         }
496 #endif
497 }
498
499 #define ADD_BINOP(op) do {      \
500                 MONO_INST_NEW (cfg, ins, (op)); \
501                 sp -= 2;        \
502                 ins->sreg1 = sp [0]->dreg;      \
503                 ins->sreg2 = sp [1]->dreg;      \
504                 type_from_op (cfg, ins, sp [0], sp [1]);        \
505                 CHECK_TYPE (ins);       \
506                 /* Have to insert a widening op */               \
507         add_widen_op (cfg, ins, &sp [0], &sp [1]);               \
508         ins->dreg = alloc_dreg ((cfg), (MonoStackType)(ins)->type); \
509         MONO_ADD_INS ((cfg)->cbb, (ins)); \
510         *sp++ = mono_decompose_opcode ((cfg), (ins));   \
511         } while (0)
512
513 #define ADD_UNOP(op) do {       \
514                 MONO_INST_NEW (cfg, ins, (op)); \
515                 sp--;   \
516                 ins->sreg1 = sp [0]->dreg;      \
517                 type_from_op (cfg, ins, sp [0], NULL);  \
518                 CHECK_TYPE (ins);       \
519         (ins)->dreg = alloc_dreg ((cfg), (MonoStackType)(ins)->type); \
520         MONO_ADD_INS ((cfg)->cbb, (ins)); \
521                 *sp++ = mono_decompose_opcode (cfg, ins);       \
522         } while (0)
523
524 #define ADD_BINCOND(next_block) do {    \
525                 MonoInst *cmp;  \
526                 sp -= 2; \
527                 MONO_INST_NEW(cfg, cmp, OP_COMPARE);    \
528                 cmp->sreg1 = sp [0]->dreg;      \
529                 cmp->sreg2 = sp [1]->dreg;      \
530                 type_from_op (cfg, cmp, sp [0], sp [1]);        \
531                 CHECK_TYPE (cmp);       \
532                 add_widen_op (cfg, cmp, &sp [0], &sp [1]);                                              \
533                 type_from_op (cfg, ins, sp [0], sp [1]);                                                        \
534                 ins->inst_many_bb = (MonoBasicBlock **)mono_mempool_alloc (cfg->mempool, sizeof(gpointer)*2);   \
535                 GET_BBLOCK (cfg, tblock, target);               \
536                 link_bblock (cfg, cfg->cbb, tblock);    \
537                 ins->inst_true_bb = tblock;     \
538                 if ((next_block)) {     \
539                         link_bblock (cfg, cfg->cbb, (next_block));      \
540                         ins->inst_false_bb = (next_block);      \
541                         start_new_bblock = 1;   \
542                 } else {        \
543                         GET_BBLOCK (cfg, tblock, ip);           \
544                         link_bblock (cfg, cfg->cbb, tblock);    \
545                         ins->inst_false_bb = tblock;    \
546                         start_new_bblock = 2;   \
547                 }       \
548                 if (sp != stack_start) {                                                                        \
549                     handle_stack_args (cfg, stack_start, sp - stack_start); \
550                         CHECK_UNVERIFIABLE (cfg); \
551                 } \
552         MONO_ADD_INS (cfg->cbb, cmp); \
553                 MONO_ADD_INS (cfg->cbb, ins);   \
554         } while (0)
555
556 /* *
557  * link_bblock: Links two basic blocks
558  *
559  * links two basic blocks in the control flow graph, the 'from'
560  * argument is the starting block and the 'to' argument is the block
561  * the control flow ends to after 'from'.
562  */
563 static void
564 link_bblock (MonoCompile *cfg, MonoBasicBlock *from, MonoBasicBlock* to)
565 {
566         MonoBasicBlock **newa;
567         int i, found;
568
569 #if 0
570         if (from->cil_code) {
571                 if (to->cil_code)
572                         printf ("edge from IL%04x to IL_%04x\n", from->cil_code - cfg->cil_code, to->cil_code - cfg->cil_code);
573                 else
574                         printf ("edge from IL%04x to exit\n", from->cil_code - cfg->cil_code);
575         } else {
576                 if (to->cil_code)
577                         printf ("edge from entry to IL_%04x\n", to->cil_code - cfg->cil_code);
578                 else
579                         printf ("edge from entry to exit\n");
580         }
581 #endif
582
583         found = FALSE;
584         for (i = 0; i < from->out_count; ++i) {
585                 if (to == from->out_bb [i]) {
586                         found = TRUE;
587                         break;
588                 }
589         }
590         if (!found) {
591                 newa = (MonoBasicBlock **)mono_mempool_alloc (cfg->mempool, sizeof (gpointer) * (from->out_count + 1));
592                 for (i = 0; i < from->out_count; ++i) {
593                         newa [i] = from->out_bb [i];
594                 }
595                 newa [i] = to;
596                 from->out_count++;
597                 from->out_bb = newa;
598         }
599
600         found = FALSE;
601         for (i = 0; i < to->in_count; ++i) {
602                 if (from == to->in_bb [i]) {
603                         found = TRUE;
604                         break;
605                 }
606         }
607         if (!found) {
608                 newa = (MonoBasicBlock **)mono_mempool_alloc (cfg->mempool, sizeof (gpointer) * (to->in_count + 1));
609                 for (i = 0; i < to->in_count; ++i) {
610                         newa [i] = to->in_bb [i];
611                 }
612                 newa [i] = from;
613                 to->in_count++;
614                 to->in_bb = newa;
615         }
616 }
617
618 void
619 mono_link_bblock (MonoCompile *cfg, MonoBasicBlock *from, MonoBasicBlock* to)
620 {
621         link_bblock (cfg, from, to);
622 }
623
624 /**
625  * mono_find_block_region:
626  *
627  *   We mark each basic block with a region ID. We use that to avoid BB
628  *   optimizations when blocks are in different regions.
629  *
630  * Returns:
631  *   A region token that encodes where this region is, and information
632  *   about the clause owner for this block.
633  *
634  *   The region encodes the try/catch/filter clause that owns this block
635  *   as well as the type.  -1 is a special value that represents a block
636  *   that is in none of try/catch/filter.
637  */
638 static int
639 mono_find_block_region (MonoCompile *cfg, int offset)
640 {
641         MonoMethodHeader *header = cfg->header;
642         MonoExceptionClause *clause;
643         int i;
644
645         for (i = 0; i < header->num_clauses; ++i) {
646                 clause = &header->clauses [i];
647                 if ((clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) && (offset >= clause->data.filter_offset) &&
648                     (offset < (clause->handler_offset)))
649                         return ((i + 1) << 8) | MONO_REGION_FILTER | clause->flags;
650                            
651                 if (MONO_OFFSET_IN_HANDLER (clause, offset)) {
652                         if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
653                                 return ((i + 1) << 8) | MONO_REGION_FINALLY | clause->flags;
654                         else if (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT)
655                                 return ((i + 1) << 8) | MONO_REGION_FAULT | clause->flags;
656                         else
657                                 return ((i + 1) << 8) | MONO_REGION_CATCH | clause->flags;
658                 }
659         }
660         for (i = 0; i < header->num_clauses; ++i) {
661                 clause = &header->clauses [i];
662
663                 if (MONO_OFFSET_IN_CLAUSE (clause, offset))
664                         return ((i + 1) << 8) | clause->flags;
665         }
666
667         return -1;
668 }
669
670 static gboolean
671 ip_in_finally_clause (MonoCompile *cfg, int offset)
672 {
673         MonoMethodHeader *header = cfg->header;
674         MonoExceptionClause *clause;
675         int i;
676
677         for (i = 0; i < header->num_clauses; ++i) {
678                 clause = &header->clauses [i];
679                 if (clause->flags != MONO_EXCEPTION_CLAUSE_FINALLY && clause->flags != MONO_EXCEPTION_CLAUSE_FAULT)
680                         continue;
681
682                 if (MONO_OFFSET_IN_HANDLER (clause, offset))
683                         return TRUE;
684         }
685         return FALSE;
686 }
687
688 static GList*
689 mono_find_final_block (MonoCompile *cfg, unsigned char *ip, unsigned char *target, int type)
690 {
691         MonoMethodHeader *header = cfg->header;
692         MonoExceptionClause *clause;
693         int i;
694         GList *res = NULL;
695
696         for (i = 0; i < header->num_clauses; ++i) {
697                 clause = &header->clauses [i];
698                 if (MONO_OFFSET_IN_CLAUSE (clause, (ip - header->code)) && 
699                     (!MONO_OFFSET_IN_CLAUSE (clause, (target - header->code)))) {
700                         if (clause->flags == type)
701                                 res = g_list_append (res, clause);
702                 }
703         }
704         return res;
705 }
706
707 static void
708 mono_create_spvar_for_region (MonoCompile *cfg, int region)
709 {
710         MonoInst *var;
711
712         var = (MonoInst *)g_hash_table_lookup (cfg->spvars, GINT_TO_POINTER (region));
713         if (var)
714                 return;
715
716         var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
717         /* prevent it from being register allocated */
718         var->flags |= MONO_INST_VOLATILE;
719
720         g_hash_table_insert (cfg->spvars, GINT_TO_POINTER (region), var);
721 }
722
723 MonoInst *
724 mono_find_exvar_for_offset (MonoCompile *cfg, int offset)
725 {
726         return (MonoInst *)g_hash_table_lookup (cfg->exvars, GINT_TO_POINTER (offset));
727 }
728
729 static MonoInst*
730 mono_create_exvar_for_offset (MonoCompile *cfg, int offset)
731 {
732         MonoInst *var;
733
734         var = (MonoInst *)g_hash_table_lookup (cfg->exvars, GINT_TO_POINTER (offset));
735         if (var)
736                 return var;
737
738         var = mono_compile_create_var (cfg, &mono_defaults.object_class->byval_arg, OP_LOCAL);
739         /* prevent it from being register allocated */
740         var->flags |= MONO_INST_VOLATILE;
741
742         g_hash_table_insert (cfg->exvars, GINT_TO_POINTER (offset), var);
743
744         return var;
745 }
746
747 /*
748  * Returns the type used in the eval stack when @type is loaded.
749  * FIXME: return a MonoType/MonoClass for the byref and VALUETYPE cases.
750  */
751 void
752 type_to_eval_stack_type (MonoCompile *cfg, MonoType *type, MonoInst *inst)
753 {
754         MonoClass *klass;
755
756         type = mini_get_underlying_type (type);
757         inst->klass = klass = mono_class_from_mono_type (type);
758         if (type->byref) {
759                 inst->type = STACK_MP;
760                 return;
761         }
762
763 handle_enum:
764         switch (type->type) {
765         case MONO_TYPE_VOID:
766                 inst->type = STACK_INV;
767                 return;
768         case MONO_TYPE_I1:
769         case MONO_TYPE_U1:
770         case MONO_TYPE_I2:
771         case MONO_TYPE_U2:
772         case MONO_TYPE_I4:
773         case MONO_TYPE_U4:
774                 inst->type = STACK_I4;
775                 return;
776         case MONO_TYPE_I:
777         case MONO_TYPE_U:
778         case MONO_TYPE_PTR:
779         case MONO_TYPE_FNPTR:
780                 inst->type = STACK_PTR;
781                 return;
782         case MONO_TYPE_CLASS:
783         case MONO_TYPE_STRING:
784         case MONO_TYPE_OBJECT:
785         case MONO_TYPE_SZARRAY:
786         case MONO_TYPE_ARRAY:    
787                 inst->type = STACK_OBJ;
788                 return;
789         case MONO_TYPE_I8:
790         case MONO_TYPE_U8:
791                 inst->type = STACK_I8;
792                 return;
793         case MONO_TYPE_R4:
794                 inst->type = cfg->r4_stack_type;
795                 break;
796         case MONO_TYPE_R8:
797                 inst->type = STACK_R8;
798                 return;
799         case MONO_TYPE_VALUETYPE:
800                 if (type->data.klass->enumtype) {
801                         type = mono_class_enum_basetype (type->data.klass);
802                         goto handle_enum;
803                 } else {
804                         inst->klass = klass;
805                         inst->type = STACK_VTYPE;
806                         return;
807                 }
808         case MONO_TYPE_TYPEDBYREF:
809                 inst->klass = mono_defaults.typed_reference_class;
810                 inst->type = STACK_VTYPE;
811                 return;
812         case MONO_TYPE_GENERICINST:
813                 type = &type->data.generic_class->container_class->byval_arg;
814                 goto handle_enum;
815         case MONO_TYPE_VAR:
816         case MONO_TYPE_MVAR:
817                 g_assert (cfg->gshared);
818                 if (mini_is_gsharedvt_type (type)) {
819                         g_assert (cfg->gsharedvt);
820                         inst->type = STACK_VTYPE;
821                 } else {
822                         type_to_eval_stack_type (cfg, mini_get_underlying_type (type), inst);
823                 }
824                 return;
825         default:
826                 g_error ("unknown type 0x%02x in eval stack type", type->type);
827         }
828 }
829
830 /*
831  * The following tables are used to quickly validate the IL code in type_from_op ().
832  */
833 static const char
834 bin_num_table [STACK_MAX] [STACK_MAX] = {
835         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
836         {STACK_INV, STACK_I4,  STACK_INV, STACK_PTR, STACK_INV, STACK_MP,  STACK_INV, STACK_INV},
837         {STACK_INV, STACK_INV, STACK_I8,  STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
838         {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_MP,  STACK_INV, STACK_INV},
839         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_R8,  STACK_INV, STACK_INV, STACK_INV, STACK_R8},
840         {STACK_INV, STACK_MP,  STACK_INV, STACK_MP,  STACK_INV, STACK_PTR, STACK_INV, STACK_INV},
841         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
842         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
843         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_R8, STACK_INV, STACK_INV, STACK_INV, STACK_R4}
844 };
845
846 static const char 
847 neg_table [] = {
848         STACK_INV, STACK_I4, STACK_I8, STACK_PTR, STACK_R8, STACK_INV, STACK_INV, STACK_INV, STACK_R4
849 };
850
851 /* reduce the size of this table */
852 static const char
853 bin_int_table [STACK_MAX] [STACK_MAX] = {
854         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
855         {STACK_INV, STACK_I4,  STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
856         {STACK_INV, STACK_INV, STACK_I8,  STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
857         {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
858         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
859         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
860         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
861         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
862 };
863
864 static const char
865 bin_comp_table [STACK_MAX] [STACK_MAX] = {
866 /*      Inv i  L  p  F  &  O  vt r4 */
867         {0},
868         {0, 1, 0, 1, 0, 0, 0, 0}, /* i, int32 */
869         {0, 0, 1, 0, 0, 0, 0, 0}, /* L, int64 */
870         {0, 1, 0, 1, 0, 2, 4, 0}, /* p, ptr */
871         {0, 0, 0, 0, 1, 0, 0, 0, 1}, /* F, R8 */
872         {0, 0, 0, 2, 0, 1, 0, 0}, /* &, managed pointer */
873         {0, 0, 0, 4, 0, 0, 3, 0}, /* O, reference */
874         {0, 0, 0, 0, 0, 0, 0, 0}, /* vt value type */
875         {0, 0, 0, 0, 1, 0, 0, 0, 1}, /* r, r4 */
876 };
877
878 /* reduce the size of this table */
879 static const char
880 shift_table [STACK_MAX] [STACK_MAX] = {
881         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
882         {STACK_INV, STACK_I4,  STACK_INV, STACK_I4,  STACK_INV, STACK_INV, STACK_INV, STACK_INV},
883         {STACK_INV, STACK_I8,  STACK_INV, STACK_I8,  STACK_INV, STACK_INV, STACK_INV, STACK_INV},
884         {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
885         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
886         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
887         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
888         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
889 };
890
891 /*
892  * Tables to map from the non-specific opcode to the matching
893  * type-specific opcode.
894  */
895 /* handles from CEE_ADD to CEE_SHR_UN (CEE_REM_UN for floats) */
896 static const guint16
897 binops_op_map [STACK_MAX] = {
898         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
899 };
900
901 /* handles from CEE_NEG to CEE_CONV_U8 */
902 static const guint16
903 unops_op_map [STACK_MAX] = {
904         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
905 };
906
907 /* handles from CEE_CONV_U2 to CEE_SUB_OVF_UN */
908 static const guint16
909 ovfops_op_map [STACK_MAX] = {
910         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
911 };
912
913 /* handles from CEE_CONV_OVF_I1_UN to CEE_CONV_OVF_U_UN */
914 static const guint16
915 ovf2ops_op_map [STACK_MAX] = {
916         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
917 };
918
919 /* handles from CEE_CONV_OVF_I1 to CEE_CONV_OVF_U8 */
920 static const guint16
921 ovf3ops_op_map [STACK_MAX] = {
922         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
923 };
924
925 /* handles from CEE_BEQ to CEE_BLT_UN */
926 static const guint16
927 beqops_op_map [STACK_MAX] = {
928         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
929 };
930
931 /* handles from CEE_CEQ to CEE_CLT_UN */
932 static const guint16
933 ceqops_op_map [STACK_MAX] = {
934         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
935 };
936
937 /*
938  * Sets ins->type (the type on the eval stack) according to the
939  * type of the opcode and the arguments to it.
940  * Invalid IL code is marked by setting ins->type to the invalid value STACK_INV.
941  *
942  * FIXME: this function sets ins->type unconditionally in some cases, but
943  * it should set it to invalid for some types (a conv.x on an object)
944  */
945 static void
946 type_from_op (MonoCompile *cfg, MonoInst *ins, MonoInst *src1, MonoInst *src2)
947 {
948         switch (ins->opcode) {
949         /* binops */
950         case CEE_ADD:
951         case CEE_SUB:
952         case CEE_MUL:
953         case CEE_DIV:
954         case CEE_REM:
955                 /* FIXME: check unverifiable args for STACK_MP */
956                 ins->type = bin_num_table [src1->type] [src2->type];
957                 ins->opcode += binops_op_map [ins->type];
958                 break;
959         case CEE_DIV_UN:
960         case CEE_REM_UN:
961         case CEE_AND:
962         case CEE_OR:
963         case CEE_XOR:
964                 ins->type = bin_int_table [src1->type] [src2->type];
965                 ins->opcode += binops_op_map [ins->type];
966                 break;
967         case CEE_SHL:
968         case CEE_SHR:
969         case CEE_SHR_UN:
970                 ins->type = shift_table [src1->type] [src2->type];
971                 ins->opcode += binops_op_map [ins->type];
972                 break;
973         case OP_COMPARE:
974         case OP_LCOMPARE:
975         case OP_ICOMPARE:
976                 ins->type = bin_comp_table [src1->type] [src2->type] ? STACK_I4: STACK_INV;
977                 if ((src1->type == STACK_I8) || ((SIZEOF_VOID_P == 8) && ((src1->type == STACK_PTR) || (src1->type == STACK_OBJ) || (src1->type == STACK_MP))))
978                         ins->opcode = OP_LCOMPARE;
979                 else if (src1->type == STACK_R4)
980                         ins->opcode = OP_RCOMPARE;
981                 else if (src1->type == STACK_R8)
982                         ins->opcode = OP_FCOMPARE;
983                 else
984                         ins->opcode = OP_ICOMPARE;
985                 break;
986         case OP_ICOMPARE_IMM:
987                 ins->type = bin_comp_table [src1->type] [src1->type] ? STACK_I4 : STACK_INV;
988                 if ((src1->type == STACK_I8) || ((SIZEOF_VOID_P == 8) && ((src1->type == STACK_PTR) || (src1->type == STACK_OBJ) || (src1->type == STACK_MP))))
989                         ins->opcode = OP_LCOMPARE_IMM;          
990                 break;
991         case CEE_BEQ:
992         case CEE_BGE:
993         case CEE_BGT:
994         case CEE_BLE:
995         case CEE_BLT:
996         case CEE_BNE_UN:
997         case CEE_BGE_UN:
998         case CEE_BGT_UN:
999         case CEE_BLE_UN:
1000         case CEE_BLT_UN:
1001                 ins->opcode += beqops_op_map [src1->type];
1002                 break;
1003         case OP_CEQ:
1004                 ins->type = bin_comp_table [src1->type] [src2->type] ? STACK_I4: STACK_INV;
1005                 ins->opcode += ceqops_op_map [src1->type];
1006                 break;
1007         case OP_CGT:
1008         case OP_CGT_UN:
1009         case OP_CLT:
1010         case OP_CLT_UN:
1011                 ins->type = (bin_comp_table [src1->type] [src2->type] & 1) ? STACK_I4: STACK_INV;
1012                 ins->opcode += ceqops_op_map [src1->type];
1013                 break;
1014         /* unops */
1015         case CEE_NEG:
1016                 ins->type = neg_table [src1->type];
1017                 ins->opcode += unops_op_map [ins->type];
1018                 break;
1019         case CEE_NOT:
1020                 if (src1->type >= STACK_I4 && src1->type <= STACK_PTR)
1021                         ins->type = src1->type;
1022                 else
1023                         ins->type = STACK_INV;
1024                 ins->opcode += unops_op_map [ins->type];
1025                 break;
1026         case CEE_CONV_I1:
1027         case CEE_CONV_I2:
1028         case CEE_CONV_I4:
1029         case CEE_CONV_U4:
1030                 ins->type = STACK_I4;
1031                 ins->opcode += unops_op_map [src1->type];
1032                 break;
1033         case CEE_CONV_R_UN:
1034                 ins->type = STACK_R8;
1035                 switch (src1->type) {
1036                 case STACK_I4:
1037                 case STACK_PTR:
1038                         ins->opcode = OP_ICONV_TO_R_UN;
1039                         break;
1040                 case STACK_I8:
1041                         ins->opcode = OP_LCONV_TO_R_UN; 
1042                         break;
1043                 }
1044                 break;
1045         case CEE_CONV_OVF_I1:
1046         case CEE_CONV_OVF_U1:
1047         case CEE_CONV_OVF_I2:
1048         case CEE_CONV_OVF_U2:
1049         case CEE_CONV_OVF_I4:
1050         case CEE_CONV_OVF_U4:
1051                 ins->type = STACK_I4;
1052                 ins->opcode += ovf3ops_op_map [src1->type];
1053                 break;
1054         case CEE_CONV_OVF_I_UN:
1055         case CEE_CONV_OVF_U_UN:
1056                 ins->type = STACK_PTR;
1057                 ins->opcode += ovf2ops_op_map [src1->type];
1058                 break;
1059         case CEE_CONV_OVF_I1_UN:
1060         case CEE_CONV_OVF_I2_UN:
1061         case CEE_CONV_OVF_I4_UN:
1062         case CEE_CONV_OVF_U1_UN:
1063         case CEE_CONV_OVF_U2_UN:
1064         case CEE_CONV_OVF_U4_UN:
1065                 ins->type = STACK_I4;
1066                 ins->opcode += ovf2ops_op_map [src1->type];
1067                 break;
1068         case CEE_CONV_U:
1069                 ins->type = STACK_PTR;
1070                 switch (src1->type) {
1071                 case STACK_I4:
1072                         ins->opcode = OP_ICONV_TO_U;
1073                         break;
1074                 case STACK_PTR:
1075                 case STACK_MP:
1076 #if SIZEOF_VOID_P == 8
1077                         ins->opcode = OP_LCONV_TO_U;
1078 #else
1079                         ins->opcode = OP_MOVE;
1080 #endif
1081                         break;
1082                 case STACK_I8:
1083                         ins->opcode = OP_LCONV_TO_U;
1084                         break;
1085                 case STACK_R8:
1086                         ins->opcode = OP_FCONV_TO_U;
1087                         break;
1088                 }
1089                 break;
1090         case CEE_CONV_I8:
1091         case CEE_CONV_U8:
1092                 ins->type = STACK_I8;
1093                 ins->opcode += unops_op_map [src1->type];
1094                 break;
1095         case CEE_CONV_OVF_I8:
1096         case CEE_CONV_OVF_U8:
1097                 ins->type = STACK_I8;
1098                 ins->opcode += ovf3ops_op_map [src1->type];
1099                 break;
1100         case CEE_CONV_OVF_U8_UN:
1101         case CEE_CONV_OVF_I8_UN:
1102                 ins->type = STACK_I8;
1103                 ins->opcode += ovf2ops_op_map [src1->type];
1104                 break;
1105         case CEE_CONV_R4:
1106                 ins->type = cfg->r4_stack_type;
1107                 ins->opcode += unops_op_map [src1->type];
1108                 break;
1109         case CEE_CONV_R8:
1110                 ins->type = STACK_R8;
1111                 ins->opcode += unops_op_map [src1->type];
1112                 break;
1113         case OP_CKFINITE:
1114                 ins->type = STACK_R8;           
1115                 break;
1116         case CEE_CONV_U2:
1117         case CEE_CONV_U1:
1118                 ins->type = STACK_I4;
1119                 ins->opcode += ovfops_op_map [src1->type];
1120                 break;
1121         case CEE_CONV_I:
1122         case CEE_CONV_OVF_I:
1123         case CEE_CONV_OVF_U:
1124                 ins->type = STACK_PTR;
1125                 ins->opcode += ovfops_op_map [src1->type];
1126                 break;
1127         case CEE_ADD_OVF:
1128         case CEE_ADD_OVF_UN:
1129         case CEE_MUL_OVF:
1130         case CEE_MUL_OVF_UN:
1131         case CEE_SUB_OVF:
1132         case CEE_SUB_OVF_UN:
1133                 ins->type = bin_num_table [src1->type] [src2->type];
1134                 ins->opcode += ovfops_op_map [src1->type];
1135                 if (ins->type == STACK_R8)
1136                         ins->type = STACK_INV;
1137                 break;
1138         case OP_LOAD_MEMBASE:
1139                 ins->type = STACK_PTR;
1140                 break;
1141         case OP_LOADI1_MEMBASE:
1142         case OP_LOADU1_MEMBASE:
1143         case OP_LOADI2_MEMBASE:
1144         case OP_LOADU2_MEMBASE:
1145         case OP_LOADI4_MEMBASE:
1146         case OP_LOADU4_MEMBASE:
1147                 ins->type = STACK_PTR;
1148                 break;
1149         case OP_LOADI8_MEMBASE:
1150                 ins->type = STACK_I8;
1151                 break;
1152         case OP_LOADR4_MEMBASE:
1153                 ins->type = cfg->r4_stack_type;
1154                 break;
1155         case OP_LOADR8_MEMBASE:
1156                 ins->type = STACK_R8;
1157                 break;
1158         default:
1159                 g_error ("opcode 0x%04x not handled in type from op", ins->opcode);
1160                 break;
1161         }
1162
1163         if (ins->type == STACK_MP)
1164                 ins->klass = mono_defaults.object_class;
1165 }
1166
1167 static const char 
1168 ldind_type [] = {
1169         STACK_I4, STACK_I4, STACK_I4, STACK_I4, STACK_I4, STACK_I4, STACK_I8, STACK_PTR, STACK_R8, STACK_R8, STACK_OBJ
1170 };
1171
1172 #if 0
1173
1174 static const char
1175 param_table [STACK_MAX] [STACK_MAX] = {
1176         {0},
1177 };
1178
1179 static int
1180 check_values_to_signature (MonoInst *args, MonoType *this_ins, MonoMethodSignature *sig)
1181 {
1182         int i;
1183
1184         if (sig->hasthis) {
1185                 switch (args->type) {
1186                 case STACK_I4:
1187                 case STACK_I8:
1188                 case STACK_R8:
1189                 case STACK_VTYPE:
1190                 case STACK_INV:
1191                         return 0;
1192                 }
1193                 args++;
1194         }
1195         for (i = 0; i < sig->param_count; ++i) {
1196                 switch (args [i].type) {
1197                 case STACK_INV:
1198                         return 0;
1199                 case STACK_MP:
1200                         if (!sig->params [i]->byref)
1201                                 return 0;
1202                         continue;
1203                 case STACK_OBJ:
1204                         if (sig->params [i]->byref)
1205                                 return 0;
1206                         switch (sig->params [i]->type) {
1207                         case MONO_TYPE_CLASS:
1208                         case MONO_TYPE_STRING:
1209                         case MONO_TYPE_OBJECT:
1210                         case MONO_TYPE_SZARRAY:
1211                         case MONO_TYPE_ARRAY:
1212                                 break;
1213                         default:
1214                                 return 0;
1215                         }
1216                         continue;
1217                 case STACK_R8:
1218                         if (sig->params [i]->byref)
1219                                 return 0;
1220                         if (sig->params [i]->type != MONO_TYPE_R4 && sig->params [i]->type != MONO_TYPE_R8)
1221                                 return 0;
1222                         continue;
1223                 case STACK_PTR:
1224                 case STACK_I4:
1225                 case STACK_I8:
1226                 case STACK_VTYPE:
1227                         break;
1228                 }
1229                 /*if (!param_table [args [i].type] [sig->params [i]->type])
1230                         return 0;*/
1231         }
1232         return 1;
1233 }
1234 #endif
1235
1236 /*
1237  * When we need a pointer to the current domain many times in a method, we
1238  * call mono_domain_get() once and we store the result in a local variable.
1239  * This function returns the variable that represents the MonoDomain*.
1240  */
1241 inline static MonoInst *
1242 mono_get_domainvar (MonoCompile *cfg)
1243 {
1244         if (!cfg->domainvar)
1245                 cfg->domainvar = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1246         return cfg->domainvar;
1247 }
1248
1249 /*
1250  * The got_var contains the address of the Global Offset Table when AOT 
1251  * compiling.
1252  */
1253 MonoInst *
1254 mono_get_got_var (MonoCompile *cfg)
1255 {
1256         if (!cfg->compile_aot || !cfg->backend->need_got_var)
1257                 return NULL;
1258         if (!cfg->got_var) {
1259                 cfg->got_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1260         }
1261         return cfg->got_var;
1262 }
1263
1264 static void
1265 mono_create_rgctx_var (MonoCompile *cfg)
1266 {
1267         if (!cfg->rgctx_var) {
1268                 cfg->rgctx_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1269                 /* force the var to be stack allocated */
1270                 cfg->rgctx_var->flags |= MONO_INST_VOLATILE;
1271         }
1272 }
1273
1274 static MonoInst *
1275 mono_get_vtable_var (MonoCompile *cfg)
1276 {
1277         g_assert (cfg->gshared);
1278
1279         mono_create_rgctx_var (cfg);
1280
1281         return cfg->rgctx_var;
1282 }
1283
1284 static MonoType*
1285 type_from_stack_type (MonoInst *ins) {
1286         switch (ins->type) {
1287         case STACK_I4: return &mono_defaults.int32_class->byval_arg;
1288         case STACK_I8: return &mono_defaults.int64_class->byval_arg;
1289         case STACK_PTR: return &mono_defaults.int_class->byval_arg;
1290         case STACK_R4: return &mono_defaults.single_class->byval_arg;
1291         case STACK_R8: return &mono_defaults.double_class->byval_arg;
1292         case STACK_MP:
1293                 return &ins->klass->this_arg;
1294         case STACK_OBJ: return &mono_defaults.object_class->byval_arg;
1295         case STACK_VTYPE: return &ins->klass->byval_arg;
1296         default:
1297                 g_error ("stack type %d to monotype not handled\n", ins->type);
1298         }
1299         return NULL;
1300 }
1301
1302 static G_GNUC_UNUSED int
1303 type_to_stack_type (MonoCompile *cfg, MonoType *t)
1304 {
1305         t = mono_type_get_underlying_type (t);
1306         switch (t->type) {
1307         case MONO_TYPE_I1:
1308         case MONO_TYPE_U1:
1309         case MONO_TYPE_I2:
1310         case MONO_TYPE_U2:
1311         case MONO_TYPE_I4:
1312         case MONO_TYPE_U4:
1313                 return STACK_I4;
1314         case MONO_TYPE_I:
1315         case MONO_TYPE_U:
1316         case MONO_TYPE_PTR:
1317         case MONO_TYPE_FNPTR:
1318                 return STACK_PTR;
1319         case MONO_TYPE_CLASS:
1320         case MONO_TYPE_STRING:
1321         case MONO_TYPE_OBJECT:
1322         case MONO_TYPE_SZARRAY:
1323         case MONO_TYPE_ARRAY:    
1324                 return STACK_OBJ;
1325         case MONO_TYPE_I8:
1326         case MONO_TYPE_U8:
1327                 return STACK_I8;
1328         case MONO_TYPE_R4:
1329                 return cfg->r4_stack_type;
1330         case MONO_TYPE_R8:
1331                 return STACK_R8;
1332         case MONO_TYPE_VALUETYPE:
1333         case MONO_TYPE_TYPEDBYREF:
1334                 return STACK_VTYPE;
1335         case MONO_TYPE_GENERICINST:
1336                 if (mono_type_generic_inst_is_valuetype (t))
1337                         return STACK_VTYPE;
1338                 else
1339                         return STACK_OBJ;
1340                 break;
1341         default:
1342                 g_assert_not_reached ();
1343         }
1344
1345         return -1;
1346 }
1347
1348 static MonoClass*
1349 array_access_to_klass (int opcode)
1350 {
1351         switch (opcode) {
1352         case CEE_LDELEM_U1:
1353                 return mono_defaults.byte_class;
1354         case CEE_LDELEM_U2:
1355                 return mono_defaults.uint16_class;
1356         case CEE_LDELEM_I:
1357         case CEE_STELEM_I:
1358                 return mono_defaults.int_class;
1359         case CEE_LDELEM_I1:
1360         case CEE_STELEM_I1:
1361                 return mono_defaults.sbyte_class;
1362         case CEE_LDELEM_I2:
1363         case CEE_STELEM_I2:
1364                 return mono_defaults.int16_class;
1365         case CEE_LDELEM_I4:
1366         case CEE_STELEM_I4:
1367                 return mono_defaults.int32_class;
1368         case CEE_LDELEM_U4:
1369                 return mono_defaults.uint32_class;
1370         case CEE_LDELEM_I8:
1371         case CEE_STELEM_I8:
1372                 return mono_defaults.int64_class;
1373         case CEE_LDELEM_R4:
1374         case CEE_STELEM_R4:
1375                 return mono_defaults.single_class;
1376         case CEE_LDELEM_R8:
1377         case CEE_STELEM_R8:
1378                 return mono_defaults.double_class;
1379         case CEE_LDELEM_REF:
1380         case CEE_STELEM_REF:
1381                 return mono_defaults.object_class;
1382         default:
1383                 g_assert_not_reached ();
1384         }
1385         return NULL;
1386 }
1387
1388 /*
1389  * We try to share variables when possible
1390  */
1391 static MonoInst *
1392 mono_compile_get_interface_var (MonoCompile *cfg, int slot, MonoInst *ins)
1393 {
1394         MonoInst *res;
1395         int pos, vnum;
1396
1397         /* inlining can result in deeper stacks */ 
1398         if (slot >= cfg->header->max_stack)
1399                 return mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
1400
1401         pos = ins->type - 1 + slot * STACK_MAX;
1402
1403         switch (ins->type) {
1404         case STACK_I4:
1405         case STACK_I8:
1406         case STACK_R8:
1407         case STACK_PTR:
1408         case STACK_MP:
1409         case STACK_OBJ:
1410                 if ((vnum = cfg->intvars [pos]))
1411                         return cfg->varinfo [vnum];
1412                 res = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
1413                 cfg->intvars [pos] = res->inst_c0;
1414                 break;
1415         default:
1416                 res = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
1417         }
1418         return res;
1419 }
1420
1421 static void
1422 mono_save_token_info (MonoCompile *cfg, MonoImage *image, guint32 token, gpointer key)
1423 {
1424         /* 
1425          * Don't use this if a generic_context is set, since that means AOT can't
1426          * look up the method using just the image+token.
1427          * table == 0 means this is a reference made from a wrapper.
1428          */
1429         if (cfg->compile_aot && !cfg->generic_context && (mono_metadata_token_table (token) > 0)) {
1430                 MonoJumpInfoToken *jump_info_token = (MonoJumpInfoToken *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoJumpInfoToken));
1431                 jump_info_token->image = image;
1432                 jump_info_token->token = token;
1433                 g_hash_table_insert (cfg->token_info_hash, key, jump_info_token);
1434         }
1435 }
1436
1437 /*
1438  * This function is called to handle items that are left on the evaluation stack
1439  * at basic block boundaries. What happens is that we save the values to local variables
1440  * and we reload them later when first entering the target basic block (with the
1441  * handle_loaded_temps () function).
1442  * A single joint point will use the same variables (stored in the array bb->out_stack or
1443  * bb->in_stack, if the basic block is before or after the joint point).
1444  *
1445  * This function needs to be called _before_ emitting the last instruction of
1446  * the bb (i.e. before emitting a branch).
1447  * If the stack merge fails at a join point, cfg->unverifiable is set.
1448  */
1449 static void
1450 handle_stack_args (MonoCompile *cfg, MonoInst **sp, int count)
1451 {
1452         int i, bindex;
1453         MonoBasicBlock *bb = cfg->cbb;
1454         MonoBasicBlock *outb;
1455         MonoInst *inst, **locals;
1456         gboolean found;
1457
1458         if (!count)
1459                 return;
1460         if (cfg->verbose_level > 3)
1461                 printf ("%d item(s) on exit from B%d\n", count, bb->block_num);
1462         if (!bb->out_scount) {
1463                 bb->out_scount = count;
1464                 //printf ("bblock %d has out:", bb->block_num);
1465                 found = FALSE;
1466                 for (i = 0; i < bb->out_count; ++i) {
1467                         outb = bb->out_bb [i];
1468                         /* exception handlers are linked, but they should not be considered for stack args */
1469                         if (outb->flags & BB_EXCEPTION_HANDLER)
1470                                 continue;
1471                         //printf (" %d", outb->block_num);
1472                         if (outb->in_stack) {
1473                                 found = TRUE;
1474                                 bb->out_stack = outb->in_stack;
1475                                 break;
1476                         }
1477                 }
1478                 //printf ("\n");
1479                 if (!found) {
1480                         bb->out_stack = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * count);
1481                         for (i = 0; i < count; ++i) {
1482                                 /* 
1483                                  * try to reuse temps already allocated for this purpouse, if they occupy the same
1484                                  * stack slot and if they are of the same type.
1485                                  * This won't cause conflicts since if 'local' is used to 
1486                                  * store one of the values in the in_stack of a bblock, then
1487                                  * the same variable will be used for the same outgoing stack 
1488                                  * slot as well. 
1489                                  * This doesn't work when inlining methods, since the bblocks
1490                                  * in the inlined methods do not inherit their in_stack from
1491                                  * the bblock they are inlined to. See bug #58863 for an
1492                                  * example.
1493                                  */
1494                                 if (cfg->inlined_method)
1495                                         bb->out_stack [i] = mono_compile_create_var (cfg, type_from_stack_type (sp [i]), OP_LOCAL);
1496                                 else
1497                                         bb->out_stack [i] = mono_compile_get_interface_var (cfg, i, sp [i]);
1498                         }
1499                 }
1500         }
1501
1502         for (i = 0; i < bb->out_count; ++i) {
1503                 outb = bb->out_bb [i];
1504                 /* exception handlers are linked, but they should not be considered for stack args */
1505                 if (outb->flags & BB_EXCEPTION_HANDLER)
1506                         continue;
1507                 if (outb->in_scount) {
1508                         if (outb->in_scount != bb->out_scount) {
1509                                 cfg->unverifiable = TRUE;
1510                                 return;
1511                         }
1512                         continue; /* check they are the same locals */
1513                 }
1514                 outb->in_scount = count;
1515                 outb->in_stack = bb->out_stack;
1516         }
1517
1518         locals = bb->out_stack;
1519         cfg->cbb = bb;
1520         for (i = 0; i < count; ++i) {
1521                 EMIT_NEW_TEMPSTORE (cfg, inst, locals [i]->inst_c0, sp [i]);
1522                 inst->cil_code = sp [i]->cil_code;
1523                 sp [i] = locals [i];
1524                 if (cfg->verbose_level > 3)
1525                         printf ("storing %d to temp %d\n", i, (int)locals [i]->inst_c0);
1526         }
1527
1528         /*
1529          * It is possible that the out bblocks already have in_stack assigned, and
1530          * the in_stacks differ. In this case, we will store to all the different 
1531          * in_stacks.
1532          */
1533
1534         found = TRUE;
1535         bindex = 0;
1536         while (found) {
1537                 /* Find a bblock which has a different in_stack */
1538                 found = FALSE;
1539                 while (bindex < bb->out_count) {
1540                         outb = bb->out_bb [bindex];
1541                         /* exception handlers are linked, but they should not be considered for stack args */
1542                         if (outb->flags & BB_EXCEPTION_HANDLER) {
1543                                 bindex++;
1544                                 continue;
1545                         }
1546                         if (outb->in_stack != locals) {
1547                                 for (i = 0; i < count; ++i) {
1548                                         EMIT_NEW_TEMPSTORE (cfg, inst, outb->in_stack [i]->inst_c0, sp [i]);
1549                                         inst->cil_code = sp [i]->cil_code;
1550                                         sp [i] = locals [i];
1551                                         if (cfg->verbose_level > 3)
1552                                                 printf ("storing %d to temp %d\n", i, (int)outb->in_stack [i]->inst_c0);
1553                                 }
1554                                 locals = outb->in_stack;
1555                                 found = TRUE;
1556                                 break;
1557                         }
1558                         bindex ++;
1559                 }
1560         }
1561 }
1562
1563 static MonoInst*
1564 emit_runtime_constant (MonoCompile *cfg, MonoJumpInfoType patch_type, gpointer data)
1565 {
1566         MonoInst *ins;
1567
1568         if (cfg->compile_aot) {
1569                 EMIT_NEW_AOTCONST (cfg, ins, patch_type, data);
1570         } else {
1571                 MonoJumpInfo ji;
1572                 gpointer target;
1573                 MonoError error;
1574
1575                 ji.type = patch_type;
1576                 ji.data.target = data;
1577                 target = mono_resolve_patch_target (NULL, cfg->domain, NULL, &ji, FALSE, &error);
1578                 mono_error_assert_ok (&error);
1579
1580                 EMIT_NEW_PCONST (cfg, ins, target);
1581         }
1582         return ins;
1583 }
1584
1585 MonoInst*
1586 mini_emit_runtime_constant (MonoCompile *cfg, MonoJumpInfoType patch_type, gpointer data)
1587 {
1588         return emit_runtime_constant (cfg, patch_type, data);
1589 }
1590
1591 static void 
1592 mini_emit_memset (MonoCompile *cfg, int destreg, int offset, int size, int val, int align)
1593 {
1594         int val_reg;
1595
1596         g_assert (val == 0);
1597
1598         if (align == 0)
1599                 align = 4;
1600
1601         if ((size <= SIZEOF_REGISTER) && (size <= align)) {
1602                 switch (size) {
1603                 case 1:
1604                         MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STOREI1_MEMBASE_IMM, destreg, offset, val);
1605                         return;
1606                 case 2:
1607                         MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STOREI2_MEMBASE_IMM, destreg, offset, val);
1608                         return;
1609                 case 4:
1610                         MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STOREI4_MEMBASE_IMM, destreg, offset, val);
1611                         return;
1612 #if SIZEOF_REGISTER == 8
1613                 case 8:
1614                         MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STOREI8_MEMBASE_IMM, destreg, offset, val);
1615                         return;
1616 #endif
1617                 }
1618         }
1619
1620         val_reg = alloc_preg (cfg);
1621
1622         if (SIZEOF_REGISTER == 8)
1623                 MONO_EMIT_NEW_I8CONST (cfg, val_reg, val);
1624         else
1625                 MONO_EMIT_NEW_ICONST (cfg, val_reg, val);
1626
1627         if (align < 4) {
1628                 /* This could be optimized further if neccesary */
1629                 while (size >= 1) {
1630                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI1_MEMBASE_REG, destreg, offset, val_reg);
1631                         offset += 1;
1632                         size -= 1;
1633                 }
1634                 return;
1635         }       
1636
1637         if (!cfg->backend->no_unaligned_access && SIZEOF_REGISTER == 8) {
1638                 if (offset % 8) {
1639                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI4_MEMBASE_REG, destreg, offset, val_reg);
1640                         offset += 4;
1641                         size -= 4;
1642                 }
1643                 while (size >= 8) {
1644                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI8_MEMBASE_REG, destreg, offset, val_reg);
1645                         offset += 8;
1646                         size -= 8;
1647                 }
1648         }       
1649
1650         while (size >= 4) {
1651                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI4_MEMBASE_REG, destreg, offset, val_reg);
1652                 offset += 4;
1653                 size -= 4;
1654         }
1655         while (size >= 2) {
1656                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI2_MEMBASE_REG, destreg, offset, val_reg);
1657                 offset += 2;
1658                 size -= 2;
1659         }
1660         while (size >= 1) {
1661                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI1_MEMBASE_REG, destreg, offset, val_reg);
1662                 offset += 1;
1663                 size -= 1;
1664         }
1665 }
1666
1667 void 
1668 mini_emit_memcpy (MonoCompile *cfg, int destreg, int doffset, int srcreg, int soffset, int size, int align)
1669 {
1670         int cur_reg;
1671
1672         if (align == 0)
1673                 align = 4;
1674
1675         /*FIXME arbitrary hack to avoid unbound code expansion.*/
1676         g_assert (size < 10000);
1677
1678         if (align < 4) {
1679                 /* This could be optimized further if neccesary */
1680                 while (size >= 1) {
1681                         cur_reg = alloc_preg (cfg);
1682                         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI1_MEMBASE, cur_reg, srcreg, soffset);
1683                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI1_MEMBASE_REG, destreg, doffset, cur_reg);
1684                         doffset += 1;
1685                         soffset += 1;
1686                         size -= 1;
1687                 }
1688         }
1689
1690         if (!cfg->backend->no_unaligned_access && SIZEOF_REGISTER == 8) {
1691                 while (size >= 8) {
1692                         cur_reg = alloc_preg (cfg);
1693                         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI8_MEMBASE, cur_reg, srcreg, soffset);
1694                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI8_MEMBASE_REG, destreg, doffset, cur_reg);
1695                         doffset += 8;
1696                         soffset += 8;
1697                         size -= 8;
1698                 }
1699         }       
1700
1701         while (size >= 4) {
1702                 cur_reg = alloc_preg (cfg);
1703                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, cur_reg, srcreg, soffset);
1704                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI4_MEMBASE_REG, destreg, doffset, cur_reg);
1705                 doffset += 4;
1706                 soffset += 4;
1707                 size -= 4;
1708         }
1709         while (size >= 2) {
1710                 cur_reg = alloc_preg (cfg);
1711                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI2_MEMBASE, cur_reg, srcreg, soffset);
1712                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI2_MEMBASE_REG, destreg, doffset, cur_reg);
1713                 doffset += 2;
1714                 soffset += 2;
1715                 size -= 2;
1716         }
1717         while (size >= 1) {
1718                 cur_reg = alloc_preg (cfg);
1719                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI1_MEMBASE, cur_reg, srcreg, soffset);
1720                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI1_MEMBASE_REG, destreg, doffset, cur_reg);
1721                 doffset += 1;
1722                 soffset += 1;
1723                 size -= 1;
1724         }
1725 }
1726
1727 static MonoInst*
1728 mono_create_fast_tls_getter (MonoCompile *cfg, MonoTlsKey key)
1729 {
1730         int tls_offset = mono_tls_get_tls_offset (key);
1731
1732         if (cfg->compile_aot)
1733                 return NULL;
1734
1735         if (tls_offset != -1 && mono_arch_have_fast_tls ()) {
1736                 MonoInst *ins;
1737                 MONO_INST_NEW (cfg, ins, OP_TLS_GET);
1738                 ins->dreg = mono_alloc_preg (cfg);
1739                 ins->inst_offset = tls_offset;
1740                 return ins;
1741         }
1742         return NULL;
1743 }
1744
1745 static MonoInst*
1746 mono_create_fast_tls_setter (MonoCompile *cfg, MonoInst* value, MonoTlsKey key)
1747 {
1748         int tls_offset = mono_tls_get_tls_offset (key);
1749
1750         if (cfg->compile_aot)
1751                 return NULL;
1752
1753         if (tls_offset != -1 && mono_arch_have_fast_tls ()) {
1754                 MonoInst *ins;
1755                 MONO_INST_NEW (cfg, ins, OP_TLS_SET);
1756                 ins->sreg1 = value->dreg;
1757                 ins->inst_offset = tls_offset;
1758                 return ins;
1759         }
1760         return NULL;
1761 }
1762
1763
1764 MonoInst*
1765 mono_create_tls_get (MonoCompile *cfg, MonoTlsKey key)
1766 {
1767         MonoInst *fast_tls = NULL;
1768
1769         if (!mini_get_debug_options ()->use_fallback_tls)
1770                 fast_tls = mono_create_fast_tls_getter (cfg, key);
1771
1772         if (fast_tls) {
1773                 MONO_ADD_INS (cfg->cbb, fast_tls);
1774                 return fast_tls;
1775         }
1776
1777         if (cfg->compile_aot) {
1778                 MonoInst *addr;
1779                 /*
1780                  * tls getters are critical pieces of code and we don't want to resolve them
1781                  * through the standard plt/tramp mechanism since we might expose ourselves
1782                  * to crashes and infinite recursions.
1783                  */
1784                 EMIT_NEW_AOTCONST (cfg, addr, MONO_PATCH_INFO_GET_TLS_TRAMP, (void*)key);
1785                 return mono_emit_calli (cfg, helper_sig_get_tls_tramp, NULL, addr, NULL, NULL);
1786         } else {
1787                 gpointer getter = mono_tls_get_tls_getter (key, FALSE);
1788                 return mono_emit_jit_icall (cfg, getter, NULL);
1789         }
1790 }
1791
1792 static MonoInst*
1793 mono_create_tls_set (MonoCompile *cfg, MonoInst *value, MonoTlsKey key)
1794 {
1795         MonoInst *fast_tls = NULL;
1796
1797         if (!mini_get_debug_options ()->use_fallback_tls)
1798                 fast_tls = mono_create_fast_tls_setter (cfg, value, key);
1799
1800         if (fast_tls) {
1801                 MONO_ADD_INS (cfg->cbb, fast_tls);
1802                 return fast_tls;
1803         }
1804
1805         if (cfg->compile_aot) {
1806                 MonoInst *addr;
1807                 EMIT_NEW_AOTCONST (cfg, addr, MONO_PATCH_INFO_SET_TLS_TRAMP, (void*)key);
1808                 return mono_emit_calli (cfg, helper_sig_set_tls_tramp, &value, addr, NULL, NULL);
1809         } else {
1810                 gpointer setter = mono_tls_get_tls_setter (key, FALSE);
1811                 return mono_emit_jit_icall (cfg, setter, &value);
1812         }
1813 }
1814
1815 /*
1816  * emit_push_lmf:
1817  *
1818  *   Emit IR to push the current LMF onto the LMF stack.
1819  */
1820 static void
1821 emit_push_lmf (MonoCompile *cfg)
1822 {
1823         /*
1824          * Emit IR to push the LMF:
1825          * lmf_addr = <lmf_addr from tls>
1826          * lmf->lmf_addr = lmf_addr
1827          * lmf->prev_lmf = *lmf_addr
1828          * *lmf_addr = lmf
1829          */
1830         MonoInst *ins, *lmf_ins;
1831
1832         if (!cfg->lmf_ir)
1833                 return;
1834
1835         int lmf_reg, prev_lmf_reg;
1836         /*
1837          * Store lmf_addr in a variable, so it can be allocated to a global register.
1838          */
1839         if (!cfg->lmf_addr_var)
1840                 cfg->lmf_addr_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1841
1842 #ifdef HOST_WIN32
1843         ins = mono_create_tls_get (cfg, TLS_KEY_JIT_TLS);
1844         g_assert (ins);
1845         int jit_tls_dreg = ins->dreg;
1846
1847         lmf_reg = alloc_preg (cfg);
1848         EMIT_NEW_BIALU_IMM (cfg, lmf_ins, OP_PADD_IMM, lmf_reg, jit_tls_dreg, MONO_STRUCT_OFFSET (MonoJitTlsData, lmf));
1849 #else
1850         lmf_ins = mono_create_tls_get (cfg, TLS_KEY_LMF_ADDR);
1851         g_assert (lmf_ins);
1852 #endif
1853         lmf_ins->dreg = cfg->lmf_addr_var->dreg;
1854
1855         EMIT_NEW_VARLOADA (cfg, ins, cfg->lmf_var, NULL);
1856         lmf_reg = ins->dreg;
1857
1858         prev_lmf_reg = alloc_preg (cfg);
1859         /* Save previous_lmf */
1860         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, prev_lmf_reg, cfg->lmf_addr_var->dreg, 0);
1861         EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STORE_MEMBASE_REG, lmf_reg, MONO_STRUCT_OFFSET (MonoLMF, previous_lmf), prev_lmf_reg);
1862         /* Set new lmf */
1863         EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STORE_MEMBASE_REG, cfg->lmf_addr_var->dreg, 0, lmf_reg);
1864 }
1865
1866 /*
1867  * emit_pop_lmf:
1868  *
1869  *   Emit IR to pop the current LMF from the LMF stack.
1870  */
1871 static void
1872 emit_pop_lmf (MonoCompile *cfg)
1873 {
1874         int lmf_reg, lmf_addr_reg;
1875         MonoInst *ins;
1876
1877         if (!cfg->lmf_ir)
1878                 return;
1879
1880         EMIT_NEW_VARLOADA (cfg, ins, cfg->lmf_var, NULL);
1881         lmf_reg = ins->dreg;
1882
1883         int prev_lmf_reg;
1884         /*
1885          * Emit IR to pop the LMF:
1886          * *(lmf->lmf_addr) = lmf->prev_lmf
1887          */
1888         /* This could be called before emit_push_lmf () */
1889         if (!cfg->lmf_addr_var)
1890                 cfg->lmf_addr_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1891         lmf_addr_reg = cfg->lmf_addr_var->dreg;
1892
1893         prev_lmf_reg = alloc_preg (cfg);
1894         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, prev_lmf_reg, lmf_reg, MONO_STRUCT_OFFSET (MonoLMF, previous_lmf));
1895         EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STORE_MEMBASE_REG, lmf_addr_reg, 0, prev_lmf_reg);
1896 }
1897
1898 static void
1899 emit_instrumentation_call (MonoCompile *cfg, void *func)
1900 {
1901         MonoInst *iargs [1];
1902
1903         /*
1904          * Avoid instrumenting inlined methods since it can
1905          * distort profiling results.
1906          */
1907         if (cfg->method != cfg->current_method)
1908                 return;
1909
1910         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE) {
1911                 EMIT_NEW_METHODCONST (cfg, iargs [0], cfg->method);
1912                 mono_emit_jit_icall (cfg, func, iargs);
1913         }
1914 }
1915
1916 static int
1917 ret_type_to_call_opcode (MonoCompile *cfg, MonoType *type, int calli, int virt)
1918 {
1919 handle_enum:
1920         type = mini_get_underlying_type (type);
1921         switch (type->type) {
1922         case MONO_TYPE_VOID:
1923                 return calli? OP_VOIDCALL_REG: virt? OP_VOIDCALL_MEMBASE: OP_VOIDCALL;
1924         case MONO_TYPE_I1:
1925         case MONO_TYPE_U1:
1926         case MONO_TYPE_I2:
1927         case MONO_TYPE_U2:
1928         case MONO_TYPE_I4:
1929         case MONO_TYPE_U4:
1930                 return calli? OP_CALL_REG: virt? OP_CALL_MEMBASE: OP_CALL;
1931         case MONO_TYPE_I:
1932         case MONO_TYPE_U:
1933         case MONO_TYPE_PTR:
1934         case MONO_TYPE_FNPTR:
1935                 return calli? OP_CALL_REG: virt? OP_CALL_MEMBASE: OP_CALL;
1936         case MONO_TYPE_CLASS:
1937         case MONO_TYPE_STRING:
1938         case MONO_TYPE_OBJECT:
1939         case MONO_TYPE_SZARRAY:
1940         case MONO_TYPE_ARRAY:    
1941                 return calli? OP_CALL_REG: virt? OP_CALL_MEMBASE: OP_CALL;
1942         case MONO_TYPE_I8:
1943         case MONO_TYPE_U8:
1944                 return calli? OP_LCALL_REG: virt? OP_LCALL_MEMBASE: OP_LCALL;
1945         case MONO_TYPE_R4:
1946                 if (cfg->r4fp)
1947                         return calli? OP_RCALL_REG: virt? OP_RCALL_MEMBASE: OP_RCALL;
1948                 else
1949                         return calli? OP_FCALL_REG: virt? OP_FCALL_MEMBASE: OP_FCALL;
1950         case MONO_TYPE_R8:
1951                 return calli? OP_FCALL_REG: virt? OP_FCALL_MEMBASE: OP_FCALL;
1952         case MONO_TYPE_VALUETYPE:
1953                 if (type->data.klass->enumtype) {
1954                         type = mono_class_enum_basetype (type->data.klass);
1955                         goto handle_enum;
1956                 } else
1957                         return calli? OP_VCALL_REG: virt? OP_VCALL_MEMBASE: OP_VCALL;
1958         case MONO_TYPE_TYPEDBYREF:
1959                 return calli? OP_VCALL_REG: virt? OP_VCALL_MEMBASE: OP_VCALL;
1960         case MONO_TYPE_GENERICINST:
1961                 type = &type->data.generic_class->container_class->byval_arg;
1962                 goto handle_enum;
1963         case MONO_TYPE_VAR:
1964         case MONO_TYPE_MVAR:
1965                 /* gsharedvt */
1966                 return calli? OP_VCALL_REG: virt? OP_VCALL_MEMBASE: OP_VCALL;
1967         default:
1968                 g_error ("unknown type 0x%02x in ret_type_to_call_opcode", type->type);
1969         }
1970         return -1;
1971 }
1972
1973 //XXX this ignores if t is byref
1974 #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)))))
1975
1976 /*
1977  * target_type_is_incompatible:
1978  * @cfg: MonoCompile context
1979  *
1980  * Check that the item @arg on the evaluation stack can be stored
1981  * in the target type (can be a local, or field, etc).
1982  * The cfg arg can be used to check if we need verification or just
1983  * validity checks.
1984  *
1985  * Returns: non-0 value if arg can't be stored on a target.
1986  */
1987 static int
1988 target_type_is_incompatible (MonoCompile *cfg, MonoType *target, MonoInst *arg)
1989 {
1990         MonoType *simple_type;
1991         MonoClass *klass;
1992
1993         if (target->byref) {
1994                 /* FIXME: check that the pointed to types match */
1995                 if (arg->type == STACK_MP) {
1996                         /* This is needed to handle gshared types + ldaddr. We lower the types so we can handle enums and other typedef-like types. */
1997                         MonoClass *target_class_lowered = mono_class_from_mono_type (mini_get_underlying_type (&mono_class_from_mono_type (target)->byval_arg));
1998                         MonoClass *source_class_lowered = mono_class_from_mono_type (mini_get_underlying_type (&arg->klass->byval_arg));
1999
2000                         /* if the target is native int& or same type */
2001                         if (target->type == MONO_TYPE_I || target_class_lowered == source_class_lowered)
2002                                 return 0;
2003
2004                         /* Both are primitive type byrefs and the source points to a larger type that the destination */
2005                         if (MONO_TYPE_IS_PRIMITIVE_SCALAR (&target_class_lowered->byval_arg) && MONO_TYPE_IS_PRIMITIVE_SCALAR (&source_class_lowered->byval_arg) &&
2006                                 mono_class_instance_size (target_class_lowered) <= mono_class_instance_size (source_class_lowered))
2007                                 return 0;
2008                         return 1;
2009                 }
2010                 if (arg->type == STACK_PTR)
2011                         return 0;
2012                 return 1;
2013         }
2014
2015         simple_type = mini_get_underlying_type (target);
2016         switch (simple_type->type) {
2017         case MONO_TYPE_VOID:
2018                 return 1;
2019         case MONO_TYPE_I1:
2020         case MONO_TYPE_U1:
2021         case MONO_TYPE_I2:
2022         case MONO_TYPE_U2:
2023         case MONO_TYPE_I4:
2024         case MONO_TYPE_U4:
2025                 if (arg->type != STACK_I4 && arg->type != STACK_PTR)
2026                         return 1;
2027                 return 0;
2028         case MONO_TYPE_PTR:
2029                 /* STACK_MP is needed when setting pinned locals */
2030                 if (arg->type != STACK_I4 && arg->type != STACK_PTR && arg->type != STACK_MP)
2031                         return 1;
2032                 return 0;
2033         case MONO_TYPE_I:
2034         case MONO_TYPE_U:
2035         case MONO_TYPE_FNPTR:
2036                 /* 
2037                  * Some opcodes like ldloca returns 'transient pointers' which can be stored in
2038                  * in native int. (#688008).
2039                  */
2040                 if (arg->type != STACK_I4 && arg->type != STACK_PTR && arg->type != STACK_MP)
2041                         return 1;
2042                 return 0;
2043         case MONO_TYPE_CLASS:
2044         case MONO_TYPE_STRING:
2045         case MONO_TYPE_OBJECT:
2046         case MONO_TYPE_SZARRAY:
2047         case MONO_TYPE_ARRAY:    
2048                 if (arg->type != STACK_OBJ)
2049                         return 1;
2050                 /* FIXME: check type compatibility */
2051                 return 0;
2052         case MONO_TYPE_I8:
2053         case MONO_TYPE_U8:
2054                 if (arg->type != STACK_I8)
2055                         return 1;
2056                 return 0;
2057         case MONO_TYPE_R4:
2058                 if (arg->type != cfg->r4_stack_type)
2059                         return 1;
2060                 return 0;
2061         case MONO_TYPE_R8:
2062                 if (arg->type != STACK_R8)
2063                         return 1;
2064                 return 0;
2065         case MONO_TYPE_VALUETYPE:
2066                 if (arg->type != STACK_VTYPE)
2067                         return 1;
2068                 klass = mono_class_from_mono_type (simple_type);
2069                 if (klass != arg->klass)
2070                         return 1;
2071                 return 0;
2072         case MONO_TYPE_TYPEDBYREF:
2073                 if (arg->type != STACK_VTYPE)
2074                         return 1;
2075                 klass = mono_class_from_mono_type (simple_type);
2076                 if (klass != arg->klass)
2077                         return 1;
2078                 return 0;
2079         case MONO_TYPE_GENERICINST:
2080                 if (mono_type_generic_inst_is_valuetype (simple_type)) {
2081                         MonoClass *target_class;
2082                         if (arg->type != STACK_VTYPE)
2083                                 return 1;
2084                         klass = mono_class_from_mono_type (simple_type);
2085                         target_class = mono_class_from_mono_type (target);
2086                         /* The second cases is needed when doing partial sharing */
2087                         if (klass != arg->klass && target_class != arg->klass && target_class != mono_class_from_mono_type (mini_get_underlying_type (&arg->klass->byval_arg)))
2088                                 return 1;
2089                         return 0;
2090                 } else {
2091                         if (arg->type != STACK_OBJ)
2092                                 return 1;
2093                         /* FIXME: check type compatibility */
2094                         return 0;
2095                 }
2096         case MONO_TYPE_VAR:
2097         case MONO_TYPE_MVAR:
2098                 g_assert (cfg->gshared);
2099                 if (mini_type_var_is_vt (simple_type)) {
2100                         if (arg->type != STACK_VTYPE)
2101                                 return 1;
2102                 } else {
2103                         if (arg->type != STACK_OBJ)
2104                                 return 1;
2105                 }
2106                 return 0;
2107         default:
2108                 g_error ("unknown type 0x%02x in target_type_is_incompatible", simple_type->type);
2109         }
2110         return 1;
2111 }
2112
2113 /*
2114  * Prepare arguments for passing to a function call.
2115  * Return a non-zero value if the arguments can't be passed to the given
2116  * signature.
2117  * The type checks are not yet complete and some conversions may need
2118  * casts on 32 or 64 bit architectures.
2119  *
2120  * FIXME: implement this using target_type_is_incompatible ()
2121  */
2122 static int
2123 check_call_signature (MonoCompile *cfg, MonoMethodSignature *sig, MonoInst **args)
2124 {
2125         MonoType *simple_type;
2126         int i;
2127
2128         if (sig->hasthis) {
2129                 if (args [0]->type != STACK_OBJ && args [0]->type != STACK_MP && args [0]->type != STACK_PTR)
2130                         return 1;
2131                 args++;
2132         }
2133         for (i = 0; i < sig->param_count; ++i) {
2134                 if (sig->params [i]->byref) {
2135                         if (args [i]->type != STACK_MP && args [i]->type != STACK_PTR)
2136                                 return 1;
2137                         continue;
2138                 }
2139                 simple_type = mini_get_underlying_type (sig->params [i]);
2140 handle_enum:
2141                 switch (simple_type->type) {
2142                 case MONO_TYPE_VOID:
2143                         return 1;
2144                         continue;
2145                 case MONO_TYPE_I1:
2146                 case MONO_TYPE_U1:
2147                 case MONO_TYPE_I2:
2148                 case MONO_TYPE_U2:
2149                 case MONO_TYPE_I4:
2150                 case MONO_TYPE_U4:
2151                         if (args [i]->type != STACK_I4 && args [i]->type != STACK_PTR)
2152                                 return 1;
2153                         continue;
2154                 case MONO_TYPE_I:
2155                 case MONO_TYPE_U:
2156                 case MONO_TYPE_PTR:
2157                 case MONO_TYPE_FNPTR:
2158                         if (args [i]->type != STACK_I4 && args [i]->type != STACK_PTR && args [i]->type != STACK_MP && args [i]->type != STACK_OBJ)
2159                                 return 1;
2160                         continue;
2161                 case MONO_TYPE_CLASS:
2162                 case MONO_TYPE_STRING:
2163                 case MONO_TYPE_OBJECT:
2164                 case MONO_TYPE_SZARRAY:
2165                 case MONO_TYPE_ARRAY:    
2166                         if (args [i]->type != STACK_OBJ)
2167                                 return 1;
2168                         continue;
2169                 case MONO_TYPE_I8:
2170                 case MONO_TYPE_U8:
2171                         if (args [i]->type != STACK_I8)
2172                                 return 1;
2173                         continue;
2174                 case MONO_TYPE_R4:
2175                         if (args [i]->type != cfg->r4_stack_type)
2176                                 return 1;
2177                         continue;
2178                 case MONO_TYPE_R8:
2179                         if (args [i]->type != STACK_R8)
2180                                 return 1;
2181                         continue;
2182                 case MONO_TYPE_VALUETYPE:
2183                         if (simple_type->data.klass->enumtype) {
2184                                 simple_type = mono_class_enum_basetype (simple_type->data.klass);
2185                                 goto handle_enum;
2186                         }
2187                         if (args [i]->type != STACK_VTYPE)
2188                                 return 1;
2189                         continue;
2190                 case MONO_TYPE_TYPEDBYREF:
2191                         if (args [i]->type != STACK_VTYPE)
2192                                 return 1;
2193                         continue;
2194                 case MONO_TYPE_GENERICINST:
2195                         simple_type = &simple_type->data.generic_class->container_class->byval_arg;
2196                         goto handle_enum;
2197                 case MONO_TYPE_VAR:
2198                 case MONO_TYPE_MVAR:
2199                         /* gsharedvt */
2200                         if (args [i]->type != STACK_VTYPE)
2201                                 return 1;
2202                         continue;
2203                 default:
2204                         g_error ("unknown type 0x%02x in check_call_signature",
2205                                  simple_type->type);
2206                 }
2207         }
2208         return 0;
2209 }
2210
2211 static int
2212 callvirt_to_call (int opcode)
2213 {
2214         switch (opcode) {
2215         case OP_CALL_MEMBASE:
2216                 return OP_CALL;
2217         case OP_VOIDCALL_MEMBASE:
2218                 return OP_VOIDCALL;
2219         case OP_FCALL_MEMBASE:
2220                 return OP_FCALL;
2221         case OP_RCALL_MEMBASE:
2222                 return OP_RCALL;
2223         case OP_VCALL_MEMBASE:
2224                 return OP_VCALL;
2225         case OP_LCALL_MEMBASE:
2226                 return OP_LCALL;
2227         default:
2228                 g_assert_not_reached ();
2229         }
2230
2231         return -1;
2232 }
2233
2234 static int
2235 callvirt_to_call_reg (int opcode)
2236 {
2237         switch (opcode) {
2238         case OP_CALL_MEMBASE:
2239                 return OP_CALL_REG;
2240         case OP_VOIDCALL_MEMBASE:
2241                 return OP_VOIDCALL_REG;
2242         case OP_FCALL_MEMBASE:
2243                 return OP_FCALL_REG;
2244         case OP_RCALL_MEMBASE:
2245                 return OP_RCALL_REG;
2246         case OP_VCALL_MEMBASE:
2247                 return OP_VCALL_REG;
2248         case OP_LCALL_MEMBASE:
2249                 return OP_LCALL_REG;
2250         default:
2251                 g_assert_not_reached ();
2252         }
2253
2254         return -1;
2255 }
2256
2257 /* Either METHOD or IMT_ARG needs to be set */
2258 static void
2259 emit_imt_argument (MonoCompile *cfg, MonoCallInst *call, MonoMethod *method, MonoInst *imt_arg)
2260 {
2261         int method_reg;
2262
2263         if (COMPILE_LLVM (cfg)) {
2264                 if (imt_arg) {
2265                         method_reg = alloc_preg (cfg);
2266                         MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, method_reg, imt_arg->dreg);
2267                 } else {
2268                         MonoInst *ins = emit_runtime_constant (cfg, MONO_PATCH_INFO_METHODCONST, method);
2269                         method_reg = ins->dreg;
2270                 }
2271
2272 #ifdef ENABLE_LLVM
2273                 call->imt_arg_reg = method_reg;
2274 #endif
2275                 mono_call_inst_add_outarg_reg (cfg, call, method_reg, MONO_ARCH_IMT_REG, FALSE);
2276                 return;
2277         }
2278
2279         if (imt_arg) {
2280                 method_reg = alloc_preg (cfg);
2281                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, method_reg, imt_arg->dreg);
2282         } else {
2283                 MonoInst *ins = emit_runtime_constant (cfg, MONO_PATCH_INFO_METHODCONST, method);
2284                 method_reg = ins->dreg;
2285         }
2286
2287         mono_call_inst_add_outarg_reg (cfg, call, method_reg, MONO_ARCH_IMT_REG, FALSE);
2288 }
2289
2290 static MonoJumpInfo *
2291 mono_patch_info_new (MonoMemPool *mp, int ip, MonoJumpInfoType type, gconstpointer target)
2292 {
2293         MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc (mp, sizeof (MonoJumpInfo));
2294
2295         ji->ip.i = ip;
2296         ji->type = type;
2297         ji->data.target = target;
2298
2299         return ji;
2300 }
2301
2302 static int
2303 mini_class_check_context_used (MonoCompile *cfg, MonoClass *klass)
2304 {
2305         if (cfg->gshared)
2306                 return mono_class_check_context_used (klass);
2307         else
2308                 return 0;
2309 }
2310
2311 static int
2312 mini_method_check_context_used (MonoCompile *cfg, MonoMethod *method)
2313 {
2314         if (cfg->gshared)
2315                 return mono_method_check_context_used (method);
2316         else
2317                 return 0;
2318 }
2319
2320 /*
2321  * check_method_sharing:
2322  *
2323  *   Check whenever the vtable or an mrgctx needs to be passed when calling CMETHOD.
2324  */
2325 static void
2326 check_method_sharing (MonoCompile *cfg, MonoMethod *cmethod, gboolean *out_pass_vtable, gboolean *out_pass_mrgctx)
2327 {
2328         gboolean pass_vtable = FALSE;
2329         gboolean pass_mrgctx = FALSE;
2330
2331         if (((cmethod->flags & METHOD_ATTRIBUTE_STATIC) || cmethod->klass->valuetype) &&
2332                 (mono_class_is_ginst (cmethod->klass) || mono_class_is_gtd (cmethod->klass))) {
2333                 gboolean sharable = FALSE;
2334
2335                 if (mono_method_is_generic_sharable_full (cmethod, TRUE, TRUE, TRUE))
2336                         sharable = TRUE;
2337
2338                 /*
2339                  * Pass vtable iff target method might
2340                  * be shared, which means that sharing
2341                  * is enabled for its class and its
2342                  * context is sharable (and it's not a
2343                  * generic method).
2344                  */
2345                 if (sharable && !(mini_method_get_context (cmethod) && mini_method_get_context (cmethod)->method_inst))
2346                         pass_vtable = TRUE;
2347         }
2348
2349         if (mini_method_get_context (cmethod) &&
2350                 mini_method_get_context (cmethod)->method_inst) {
2351                 g_assert (!pass_vtable);
2352
2353                 if (mono_method_is_generic_sharable_full (cmethod, TRUE, TRUE, TRUE)) {
2354                         pass_mrgctx = TRUE;
2355                 } else {
2356                         if (cfg->gsharedvt && mini_is_gsharedvt_signature (mono_method_signature (cmethod)))
2357                                 pass_mrgctx = TRUE;
2358                 }
2359         }
2360
2361         if (out_pass_vtable)
2362                 *out_pass_vtable = pass_vtable;
2363         if (out_pass_mrgctx)
2364                 *out_pass_mrgctx = pass_mrgctx;
2365 }
2366
2367 inline static MonoCallInst *
2368 mono_emit_call_args (MonoCompile *cfg, MonoMethodSignature *sig, 
2369                                          MonoInst **args, int calli, int virtual_, int tail, int rgctx, int unbox_trampoline)
2370 {
2371         MonoType *sig_ret;
2372         MonoCallInst *call;
2373 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
2374         int i;
2375 #endif
2376
2377         if (cfg->llvm_only)
2378                 tail = FALSE;
2379
2380         if (tail) {
2381                 emit_instrumentation_call (cfg, mono_profiler_method_leave);
2382
2383                 MONO_INST_NEW_CALL (cfg, call, OP_TAILCALL);
2384         } else
2385                 MONO_INST_NEW_CALL (cfg, call, ret_type_to_call_opcode (cfg, sig->ret, calli, virtual_));
2386
2387         call->args = args;
2388         call->signature = sig;
2389         call->rgctx_reg = rgctx;
2390         sig_ret = mini_get_underlying_type (sig->ret);
2391
2392         type_to_eval_stack_type ((cfg), sig_ret, &call->inst);
2393
2394         if (tail) {
2395                 if (mini_type_is_vtype (sig_ret)) {
2396                         call->vret_var = cfg->vret_addr;
2397                         //g_assert_not_reached ();
2398                 }
2399         } else if (mini_type_is_vtype (sig_ret)) {
2400                 MonoInst *temp = mono_compile_create_var (cfg, sig_ret, OP_LOCAL);
2401                 MonoInst *loada;
2402
2403                 temp->backend.is_pinvoke = sig->pinvoke;
2404
2405                 /*
2406                  * We use a new opcode OP_OUTARG_VTRETADDR instead of LDADDR for emitting the
2407                  * address of return value to increase optimization opportunities.
2408                  * Before vtype decomposition, the dreg of the call ins itself represents the
2409                  * fact the call modifies the return value. After decomposition, the call will
2410                  * be transformed into one of the OP_VOIDCALL opcodes, and the VTRETADDR opcode
2411                  * will be transformed into an LDADDR.
2412                  */
2413                 MONO_INST_NEW (cfg, loada, OP_OUTARG_VTRETADDR);
2414                 loada->dreg = alloc_preg (cfg);
2415                 loada->inst_p0 = temp;
2416                 /* We reference the call too since call->dreg could change during optimization */
2417                 loada->inst_p1 = call;
2418                 MONO_ADD_INS (cfg->cbb, loada);
2419
2420                 call->inst.dreg = temp->dreg;
2421
2422                 call->vret_var = loada;
2423         } else if (!MONO_TYPE_IS_VOID (sig_ret))
2424                 call->inst.dreg = alloc_dreg (cfg, (MonoStackType)call->inst.type);
2425
2426 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
2427         if (COMPILE_SOFT_FLOAT (cfg)) {
2428                 /* 
2429                  * If the call has a float argument, we would need to do an r8->r4 conversion using 
2430                  * an icall, but that cannot be done during the call sequence since it would clobber
2431                  * the call registers + the stack. So we do it before emitting the call.
2432                  */
2433                 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
2434                         MonoType *t;
2435                         MonoInst *in = call->args [i];
2436
2437                         if (i >= sig->hasthis)
2438                                 t = sig->params [i - sig->hasthis];
2439                         else
2440                                 t = &mono_defaults.int_class->byval_arg;
2441                         t = mono_type_get_underlying_type (t);
2442
2443                         if (!t->byref && t->type == MONO_TYPE_R4) {
2444                                 MonoInst *iargs [1];
2445                                 MonoInst *conv;
2446
2447                                 iargs [0] = in;
2448                                 conv = mono_emit_jit_icall (cfg, mono_fload_r4_arg, iargs);
2449
2450                                 /* The result will be in an int vreg */
2451                                 call->args [i] = conv;
2452                         }
2453                 }
2454         }
2455 #endif
2456
2457         call->need_unbox_trampoline = unbox_trampoline;
2458
2459 #ifdef ENABLE_LLVM
2460         if (COMPILE_LLVM (cfg))
2461                 mono_llvm_emit_call (cfg, call);
2462         else
2463                 mono_arch_emit_call (cfg, call);
2464 #else
2465         mono_arch_emit_call (cfg, call);
2466 #endif
2467
2468         cfg->param_area = MAX (cfg->param_area, call->stack_usage);
2469         cfg->flags |= MONO_CFG_HAS_CALLS;
2470         
2471         return call;
2472 }
2473
2474 static void
2475 set_rgctx_arg (MonoCompile *cfg, MonoCallInst *call, int rgctx_reg, MonoInst *rgctx_arg)
2476 {
2477         mono_call_inst_add_outarg_reg (cfg, call, rgctx_reg, MONO_ARCH_RGCTX_REG, FALSE);
2478         cfg->uses_rgctx_reg = TRUE;
2479         call->rgctx_reg = TRUE;
2480 #ifdef ENABLE_LLVM
2481         call->rgctx_arg_reg = rgctx_reg;
2482 #endif
2483 }       
2484
2485 inline static MonoInst*
2486 mono_emit_calli (MonoCompile *cfg, MonoMethodSignature *sig, MonoInst **args, MonoInst *addr, MonoInst *imt_arg, MonoInst *rgctx_arg)
2487 {
2488         MonoCallInst *call;
2489         MonoInst *ins;
2490         int rgctx_reg = -1;
2491         gboolean check_sp = FALSE;
2492
2493         if (cfg->check_pinvoke_callconv && cfg->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
2494                 WrapperInfo *info = mono_marshal_get_wrapper_info (cfg->method);
2495
2496                 if (info && info->subtype == WRAPPER_SUBTYPE_PINVOKE)
2497                         check_sp = TRUE;
2498         }
2499
2500         if (rgctx_arg) {
2501                 rgctx_reg = mono_alloc_preg (cfg);
2502                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, rgctx_reg, rgctx_arg->dreg);
2503         }
2504
2505         if (check_sp) {
2506                 if (!cfg->stack_inbalance_var)
2507                         cfg->stack_inbalance_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
2508
2509                 MONO_INST_NEW (cfg, ins, OP_GET_SP);
2510                 ins->dreg = cfg->stack_inbalance_var->dreg;
2511                 MONO_ADD_INS (cfg->cbb, ins);
2512         }
2513
2514         call = mono_emit_call_args (cfg, sig, args, TRUE, FALSE, FALSE, rgctx_arg ? TRUE : FALSE, FALSE);
2515
2516         call->inst.sreg1 = addr->dreg;
2517
2518         if (imt_arg)
2519                 emit_imt_argument (cfg, call, NULL, imt_arg);
2520
2521         MONO_ADD_INS (cfg->cbb, (MonoInst*)call);
2522
2523         if (check_sp) {
2524                 int sp_reg;
2525
2526                 sp_reg = mono_alloc_preg (cfg);
2527
2528                 MONO_INST_NEW (cfg, ins, OP_GET_SP);
2529                 ins->dreg = sp_reg;
2530                 MONO_ADD_INS (cfg->cbb, ins);
2531
2532                 /* Restore the stack so we don't crash when throwing the exception */
2533                 MONO_INST_NEW (cfg, ins, OP_SET_SP);
2534                 ins->sreg1 = cfg->stack_inbalance_var->dreg;
2535                 MONO_ADD_INS (cfg->cbb, ins);
2536
2537                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, cfg->stack_inbalance_var->dreg, sp_reg);
2538                 MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "ExecutionEngineException");
2539         }
2540
2541         if (rgctx_arg)
2542                 set_rgctx_arg (cfg, call, rgctx_reg, rgctx_arg);
2543
2544         return (MonoInst*)call;
2545 }
2546
2547 static MonoInst*
2548 emit_get_gsharedvt_info_klass (MonoCompile *cfg, MonoClass *klass, MonoRgctxInfoType rgctx_type);
2549
2550 static MonoInst*
2551 emit_get_rgctx_method (MonoCompile *cfg, int context_used, MonoMethod *cmethod, MonoRgctxInfoType rgctx_type);
2552
2553 static MonoInst*
2554 mono_emit_method_call_full (MonoCompile *cfg, MonoMethod *method, MonoMethodSignature *sig, gboolean tail,
2555                                                         MonoInst **args, MonoInst *this_ins, MonoInst *imt_arg, MonoInst *rgctx_arg)
2556 {
2557 #ifndef DISABLE_REMOTING
2558         gboolean might_be_remote = FALSE;
2559 #endif
2560         gboolean virtual_ = this_ins != NULL;
2561         gboolean enable_for_aot = TRUE;
2562         int context_used;
2563         MonoCallInst *call;
2564         MonoInst *call_target = NULL;
2565         int rgctx_reg = 0;
2566         gboolean need_unbox_trampoline;
2567
2568         if (!sig)
2569                 sig = mono_method_signature (method);
2570
2571         if (cfg->llvm_only && (mono_class_is_interface (method->klass)))
2572                 g_assert_not_reached ();
2573
2574         if (rgctx_arg) {
2575                 rgctx_reg = mono_alloc_preg (cfg);
2576                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, rgctx_reg, rgctx_arg->dreg);
2577         }
2578
2579         if (method->string_ctor) {
2580                 /* Create the real signature */
2581                 /* FIXME: Cache these */
2582                 MonoMethodSignature *ctor_sig = mono_metadata_signature_dup_mempool (cfg->mempool, sig);
2583                 ctor_sig->ret = &mono_defaults.string_class->byval_arg;
2584
2585                 sig = ctor_sig;
2586         }
2587
2588         context_used = mini_method_check_context_used (cfg, method);
2589
2590 #ifndef DISABLE_REMOTING
2591         might_be_remote = this_ins && sig->hasthis &&
2592                 (mono_class_is_marshalbyref (method->klass) || method->klass == mono_defaults.object_class) &&
2593                 !(method->flags & METHOD_ATTRIBUTE_VIRTUAL) && (!MONO_CHECK_THIS (this_ins) || context_used);
2594
2595         if (might_be_remote && context_used) {
2596                 MonoInst *addr;
2597
2598                 g_assert (cfg->gshared);
2599
2600                 addr = emit_get_rgctx_method (cfg, context_used, method, MONO_RGCTX_INFO_REMOTING_INVOKE_WITH_CHECK);
2601
2602                 return mono_emit_calli (cfg, sig, args, addr, NULL, NULL);
2603         }
2604 #endif
2605
2606         if (cfg->llvm_only && !call_target && virtual_ && (method->flags & METHOD_ATTRIBUTE_VIRTUAL))
2607                 return emit_llvmonly_virtual_call (cfg, method, sig, 0, args);
2608
2609         need_unbox_trampoline = method->klass == mono_defaults.object_class || mono_class_is_interface (method->klass);
2610
2611         call = mono_emit_call_args (cfg, sig, args, FALSE, virtual_, tail, rgctx_arg ? TRUE : FALSE, need_unbox_trampoline);
2612
2613 #ifndef DISABLE_REMOTING
2614         if (might_be_remote)
2615                 call->method = mono_marshal_get_remoting_invoke_with_check (method);
2616         else
2617 #endif
2618                 call->method = method;
2619         call->inst.flags |= MONO_INST_HAS_METHOD;
2620         call->inst.inst_left = this_ins;
2621         call->tail_call = tail;
2622
2623         if (virtual_) {
2624                 int vtable_reg, slot_reg, this_reg;
2625                 int offset;
2626
2627                 this_reg = this_ins->dreg;
2628
2629                 if (!cfg->llvm_only && (method->klass->parent == mono_defaults.multicastdelegate_class) && !strcmp (method->name, "Invoke")) {
2630                         MonoInst *dummy_use;
2631
2632                         MONO_EMIT_NULL_CHECK (cfg, this_reg);
2633
2634                         /* Make a call to delegate->invoke_impl */
2635                         call->inst.inst_basereg = this_reg;
2636                         call->inst.inst_offset = MONO_STRUCT_OFFSET (MonoDelegate, invoke_impl);
2637                         MONO_ADD_INS (cfg->cbb, (MonoInst*)call);
2638
2639                         /* We must emit a dummy use here because the delegate trampoline will
2640                         replace the 'this' argument with the delegate target making this activation
2641                         no longer a root for the delegate.
2642                         This is an issue for delegates that target collectible code such as dynamic
2643                         methods of GC'able assemblies.
2644
2645                         For a test case look into #667921.
2646
2647                         FIXME: a dummy use is not the best way to do it as the local register allocator
2648                         will put it on a caller save register and spil it around the call. 
2649                         Ideally, we would either put it on a callee save register or only do the store part.  
2650                          */
2651                         EMIT_NEW_DUMMY_USE (cfg, dummy_use, args [0]);
2652
2653                         return (MonoInst*)call;
2654                 }
2655
2656                 if ((!cfg->compile_aot || enable_for_aot) && 
2657                         (!(method->flags & METHOD_ATTRIBUTE_VIRTUAL) || 
2658                          (MONO_METHOD_IS_FINAL (method) &&
2659                           method->wrapper_type != MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)) &&
2660                         !(mono_class_is_marshalbyref (method->klass) && context_used)) {
2661                         /* 
2662                          * the method is not virtual, we just need to ensure this is not null
2663                          * and then we can call the method directly.
2664                          */
2665 #ifndef DISABLE_REMOTING
2666                         if (mono_class_is_marshalbyref (method->klass) || method->klass == mono_defaults.object_class) {
2667                                 /* 
2668                                  * The check above ensures method is not gshared, this is needed since
2669                                  * gshared methods can't have wrappers.
2670                                  */
2671                                 method = call->method = mono_marshal_get_remoting_invoke_with_check (method);
2672                         }
2673 #endif
2674
2675                         if (!method->string_ctor)
2676                                 MONO_EMIT_NEW_CHECK_THIS (cfg, this_reg);
2677
2678                         call->inst.opcode = callvirt_to_call (call->inst.opcode);
2679                 } else if ((method->flags & METHOD_ATTRIBUTE_VIRTUAL) && MONO_METHOD_IS_FINAL (method)) {
2680                         /*
2681                          * the method is virtual, but we can statically dispatch since either
2682                          * it's class or the method itself are sealed.
2683                          * But first we need to ensure it's not a null reference.
2684                          */
2685                         MONO_EMIT_NEW_CHECK_THIS (cfg, this_reg);
2686
2687                         call->inst.opcode = callvirt_to_call (call->inst.opcode);
2688                 } else if (call_target) {
2689                         vtable_reg = alloc_preg (cfg);
2690                         MONO_EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, vtable_reg, this_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
2691
2692                         call->inst.opcode = callvirt_to_call_reg (call->inst.opcode);
2693                         call->inst.sreg1 = call_target->dreg;
2694                         call->inst.flags &= !MONO_INST_HAS_METHOD;
2695                 } else {
2696                         vtable_reg = alloc_preg (cfg);
2697                         MONO_EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, vtable_reg, this_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
2698                         if (mono_class_is_interface (method->klass)) {
2699                                 guint32 imt_slot = mono_method_get_imt_slot (method);
2700                                 emit_imt_argument (cfg, call, call->method, imt_arg);
2701                                 slot_reg = vtable_reg;
2702                                 offset = ((gint32)imt_slot - MONO_IMT_SIZE) * SIZEOF_VOID_P;
2703                         } else {
2704                                 slot_reg = vtable_reg;
2705                                 offset = MONO_STRUCT_OFFSET (MonoVTable, vtable) +
2706                                         ((mono_method_get_vtable_index (method)) * (SIZEOF_VOID_P));
2707                                 if (imt_arg) {
2708                                         g_assert (mono_method_signature (method)->generic_param_count);
2709                                         emit_imt_argument (cfg, call, call->method, imt_arg);
2710                                 }
2711                         }
2712
2713                         call->inst.sreg1 = slot_reg;
2714                         call->inst.inst_offset = offset;
2715                         call->is_virtual = TRUE;
2716                 }
2717         }
2718
2719         MONO_ADD_INS (cfg->cbb, (MonoInst*)call);
2720
2721         if (rgctx_arg)
2722                 set_rgctx_arg (cfg, call, rgctx_reg, rgctx_arg);
2723
2724         return (MonoInst*)call;
2725 }
2726
2727 MonoInst*
2728 mono_emit_method_call (MonoCompile *cfg, MonoMethod *method, MonoInst **args, MonoInst *this_ins)
2729 {
2730         return mono_emit_method_call_full (cfg, method, mono_method_signature (method), FALSE, args, this_ins, NULL, NULL);
2731 }
2732
2733 MonoInst*
2734 mono_emit_native_call (MonoCompile *cfg, gconstpointer func, MonoMethodSignature *sig,
2735                                            MonoInst **args)
2736 {
2737         MonoCallInst *call;
2738
2739         g_assert (sig);
2740
2741         call = mono_emit_call_args (cfg, sig, args, FALSE, FALSE, FALSE, FALSE, FALSE);
2742         call->fptr = func;
2743
2744         MONO_ADD_INS (cfg->cbb, (MonoInst*)call);
2745
2746         return (MonoInst*)call;
2747 }
2748
2749 MonoInst*
2750 mono_emit_jit_icall (MonoCompile *cfg, gconstpointer func, MonoInst **args)
2751 {
2752         MonoJitICallInfo *info = mono_find_jit_icall_by_addr (func);
2753
2754         g_assert (info);
2755
2756         return mono_emit_native_call (cfg, mono_icall_get_wrapper (info), info->sig, args);
2757 }
2758
2759 /*
2760  * mono_emit_abs_call:
2761  *
2762  *   Emit a call to the runtime function described by PATCH_TYPE and DATA.
2763  */
2764 inline static MonoInst*
2765 mono_emit_abs_call (MonoCompile *cfg, MonoJumpInfoType patch_type, gconstpointer data, 
2766                                         MonoMethodSignature *sig, MonoInst **args)
2767 {
2768         MonoJumpInfo *ji = mono_patch_info_new (cfg->mempool, 0, patch_type, data);
2769         MonoInst *ins;
2770
2771         /* 
2772          * We pass ji as the call address, the PATCH_INFO_ABS resolving code will
2773          * handle it.
2774          */
2775         if (cfg->abs_patches == NULL)
2776                 cfg->abs_patches = g_hash_table_new (NULL, NULL);
2777         g_hash_table_insert (cfg->abs_patches, ji, ji);
2778         ins = mono_emit_native_call (cfg, ji, sig, args);
2779         ((MonoCallInst*)ins)->fptr_is_patch = TRUE;
2780         return ins;
2781 }
2782
2783 static MonoMethodSignature*
2784 sig_to_rgctx_sig (MonoMethodSignature *sig)
2785 {
2786         // FIXME: memory allocation
2787         MonoMethodSignature *res;
2788         int i;
2789
2790         res = (MonoMethodSignature *)g_malloc (MONO_SIZEOF_METHOD_SIGNATURE + (sig->param_count + 1) * sizeof (MonoType*));
2791         memcpy (res, sig, MONO_SIZEOF_METHOD_SIGNATURE);
2792         res->param_count = sig->param_count + 1;
2793         for (i = 0; i < sig->param_count; ++i)
2794                 res->params [i] = sig->params [i];
2795         res->params [sig->param_count] = &mono_defaults.int_class->this_arg;
2796         return res;
2797 }
2798
2799 /* Make an indirect call to FSIG passing an additional argument */
2800 static MonoInst*
2801 emit_extra_arg_calli (MonoCompile *cfg, MonoMethodSignature *fsig, MonoInst **orig_args, int arg_reg, MonoInst *call_target)
2802 {
2803         MonoMethodSignature *csig;
2804         MonoInst *args_buf [16];
2805         MonoInst **args;
2806         int i, pindex, tmp_reg;
2807
2808         /* Make a call with an rgctx/extra arg */
2809         if (fsig->param_count + 2 < 16)
2810                 args = args_buf;
2811         else
2812                 args = (MonoInst **)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst*) * (fsig->param_count + 2));
2813         pindex = 0;
2814         if (fsig->hasthis)
2815                 args [pindex ++] = orig_args [0];
2816         for (i = 0; i < fsig->param_count; ++i)
2817                 args [pindex ++] = orig_args [fsig->hasthis + i];
2818         tmp_reg = alloc_preg (cfg);
2819         EMIT_NEW_UNALU (cfg, args [pindex], OP_MOVE, tmp_reg, arg_reg);
2820         csig = sig_to_rgctx_sig (fsig);
2821         return mono_emit_calli (cfg, csig, args, call_target, NULL, NULL);
2822 }
2823
2824 /* Emit an indirect call to the function descriptor ADDR */
2825 static MonoInst*
2826 emit_llvmonly_calli (MonoCompile *cfg, MonoMethodSignature *fsig, MonoInst **args, MonoInst *addr)
2827 {
2828         int addr_reg, arg_reg;
2829         MonoInst *call_target;
2830
2831         g_assert (cfg->llvm_only);
2832
2833         /*
2834          * addr points to a <addr, arg> pair, load both of them, and
2835          * make a call to addr, passing arg as an extra arg.
2836          */
2837         addr_reg = alloc_preg (cfg);
2838         EMIT_NEW_LOAD_MEMBASE (cfg, call_target, OP_LOAD_MEMBASE, addr_reg, addr->dreg, 0);
2839         arg_reg = alloc_preg (cfg);
2840         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, arg_reg, addr->dreg, sizeof (gpointer));
2841
2842         return emit_extra_arg_calli (cfg, fsig, args, arg_reg, call_target);
2843 }
2844
2845 static gboolean
2846 direct_icalls_enabled (MonoCompile *cfg)
2847 {
2848         return FALSE;
2849
2850         /* LLVM on amd64 can't handle calls to non-32 bit addresses */
2851 #ifdef TARGET_AMD64
2852         if (cfg->compile_llvm && !cfg->llvm_only)
2853                 return FALSE;
2854 #endif
2855         if (cfg->gen_sdb_seq_points || cfg->disable_direct_icalls)
2856                 return FALSE;
2857         return TRUE;
2858 }
2859
2860 MonoInst*
2861 mono_emit_jit_icall_by_info (MonoCompile *cfg, int il_offset, MonoJitICallInfo *info, MonoInst **args)
2862 {
2863         /*
2864          * Call the jit icall without a wrapper if possible.
2865          * The wrapper is needed for the following reasons:
2866          * - to handle exceptions thrown using mono_raise_exceptions () from the
2867          *   icall function. The EH code needs the lmf frame pushed by the
2868          *   wrapper to be able to unwind back to managed code.
2869          * - to be able to do stack walks for asynchronously suspended
2870          *   threads when debugging.
2871          */
2872         if (info->no_raise && direct_icalls_enabled (cfg)) {
2873                 char *name;
2874                 int costs;
2875
2876                 if (!info->wrapper_method) {
2877                         name = g_strdup_printf ("__icall_wrapper_%s", info->name);
2878                         info->wrapper_method = mono_marshal_get_icall_wrapper (info->sig, name, info->func, TRUE);
2879                         g_free (name);
2880                         mono_memory_barrier ();
2881                 }
2882
2883                 /*
2884                  * Inline the wrapper method, which is basically a call to the C icall, and
2885                  * an exception check.
2886                  */
2887                 costs = inline_method (cfg, info->wrapper_method, NULL,
2888                                                            args, NULL, il_offset, TRUE);
2889                 g_assert (costs > 0);
2890                 g_assert (!MONO_TYPE_IS_VOID (info->sig->ret));
2891
2892                 return args [0];
2893         } else {
2894                 return mono_emit_native_call (cfg, mono_icall_get_wrapper (info), info->sig, args);
2895         }
2896 }
2897  
2898 static MonoInst*
2899 mono_emit_widen_call_res (MonoCompile *cfg, MonoInst *ins, MonoMethodSignature *fsig)
2900 {
2901         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
2902                 if ((fsig->pinvoke || LLVM_ENABLED) && !fsig->ret->byref) {
2903                         int widen_op = -1;
2904
2905                         /* 
2906                          * Native code might return non register sized integers 
2907                          * without initializing the upper bits.
2908                          */
2909                         switch (mono_type_to_load_membase (cfg, fsig->ret)) {
2910                         case OP_LOADI1_MEMBASE:
2911                                 widen_op = OP_ICONV_TO_I1;
2912                                 break;
2913                         case OP_LOADU1_MEMBASE:
2914                                 widen_op = OP_ICONV_TO_U1;
2915                                 break;
2916                         case OP_LOADI2_MEMBASE:
2917                                 widen_op = OP_ICONV_TO_I2;
2918                                 break;
2919                         case OP_LOADU2_MEMBASE:
2920                                 widen_op = OP_ICONV_TO_U2;
2921                                 break;
2922                         default:
2923                                 break;
2924                         }
2925
2926                         if (widen_op != -1) {
2927                                 int dreg = alloc_preg (cfg);
2928                                 MonoInst *widen;
2929
2930                                 EMIT_NEW_UNALU (cfg, widen, widen_op, dreg, ins->dreg);
2931                                 widen->type = ins->type;
2932                                 ins = widen;
2933                         }
2934                 }
2935         }
2936
2937         return ins;
2938 }
2939
2940
2941 static void
2942 emit_method_access_failure (MonoCompile *cfg, MonoMethod *caller, MonoMethod *callee)
2943 {
2944         MonoInst *args [16];
2945
2946         args [0] = emit_get_rgctx_method (cfg, mono_method_check_context_used (caller), caller, MONO_RGCTX_INFO_METHOD);
2947         args [1] = emit_get_rgctx_method (cfg, mono_method_check_context_used (callee), callee, MONO_RGCTX_INFO_METHOD);
2948
2949         mono_emit_jit_icall (cfg, mono_throw_method_access, args);
2950 }
2951
2952 static MonoMethod*
2953 get_memcpy_method (void)
2954 {
2955         static MonoMethod *memcpy_method = NULL;
2956         if (!memcpy_method) {
2957                 memcpy_method = mono_class_get_method_from_name (mono_defaults.string_class, "memcpy", 3);
2958                 if (!memcpy_method)
2959                         g_error ("Old corlib found. Install a new one");
2960         }
2961         return memcpy_method;
2962 }
2963
2964 static void
2965 create_write_barrier_bitmap (MonoCompile *cfg, MonoClass *klass, unsigned *wb_bitmap, int offset)
2966 {
2967         MonoClassField *field;
2968         gpointer iter = NULL;
2969
2970         while ((field = mono_class_get_fields (klass, &iter))) {
2971                 int foffset;
2972
2973                 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
2974                         continue;
2975                 foffset = klass->valuetype ? field->offset - sizeof (MonoObject): field->offset;
2976                 if (mini_type_is_reference (mono_field_get_type (field))) {
2977                         g_assert ((foffset % SIZEOF_VOID_P) == 0);
2978                         *wb_bitmap |= 1 << ((offset + foffset) / SIZEOF_VOID_P);
2979                 } else {
2980                         MonoClass *field_class = mono_class_from_mono_type (field->type);
2981                         if (field_class->has_references)
2982                                 create_write_barrier_bitmap (cfg, field_class, wb_bitmap, offset + foffset);
2983                 }
2984         }
2985 }
2986
2987 static void
2988 emit_write_barrier (MonoCompile *cfg, MonoInst *ptr, MonoInst *value)
2989 {
2990         int card_table_shift_bits;
2991         gpointer card_table_mask;
2992         guint8 *card_table;
2993         MonoInst *dummy_use;
2994         int nursery_shift_bits;
2995         size_t nursery_size;
2996
2997         if (!cfg->gen_write_barriers)
2998                 return;
2999
3000         card_table = mono_gc_get_card_table (&card_table_shift_bits, &card_table_mask);
3001
3002         mono_gc_get_nursery (&nursery_shift_bits, &nursery_size);
3003
3004         if (cfg->backend->have_card_table_wb && !cfg->compile_aot && card_table && nursery_shift_bits > 0 && !COMPILE_LLVM (cfg)) {
3005                 MonoInst *wbarrier;
3006
3007                 MONO_INST_NEW (cfg, wbarrier, OP_CARD_TABLE_WBARRIER);
3008                 wbarrier->sreg1 = ptr->dreg;
3009                 wbarrier->sreg2 = value->dreg;
3010                 MONO_ADD_INS (cfg->cbb, wbarrier);
3011         } else if (card_table) {
3012                 int offset_reg = alloc_preg (cfg);
3013                 int card_reg;
3014                 MonoInst *ins;
3015
3016                 /*
3017                  * We emit a fast light weight write barrier. This always marks cards as in the concurrent
3018                  * collector case, so, for the serial collector, it might slightly slow down nursery
3019                  * collections. We also expect that the host system and the target system have the same card
3020                  * table configuration, which is the case if they have the same pointer size.
3021                  */
3022
3023                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHR_UN_IMM, offset_reg, ptr->dreg, card_table_shift_bits);
3024                 if (card_table_mask)
3025                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PAND_IMM, offset_reg, offset_reg, card_table_mask);
3026
3027                 /*We can't use PADD_IMM since the cardtable might end up in high addresses and amd64 doesn't support
3028                  * IMM's larger than 32bits.
3029                  */
3030                 ins = emit_runtime_constant (cfg, MONO_PATCH_INFO_GC_CARD_TABLE_ADDR, NULL);
3031                 card_reg = ins->dreg;
3032
3033                 MONO_EMIT_NEW_BIALU (cfg, OP_PADD, offset_reg, offset_reg, card_reg);
3034                 MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STOREI1_MEMBASE_IMM, offset_reg, 0, 1);
3035         } else {
3036                 MonoMethod *write_barrier = mono_gc_get_write_barrier ();
3037                 mono_emit_method_call (cfg, write_barrier, &ptr, NULL);
3038         }
3039
3040         EMIT_NEW_DUMMY_USE (cfg, dummy_use, value);
3041 }
3042
3043 static gboolean
3044 mono_emit_wb_aware_memcpy (MonoCompile *cfg, MonoClass *klass, MonoInst *iargs[4], int size, int align)
3045 {
3046         int dest_ptr_reg, tmp_reg, destreg, srcreg, offset;
3047         unsigned need_wb = 0;
3048
3049         if (align == 0)
3050                 align = 4;
3051
3052         /*types with references can't have alignment smaller than sizeof(void*) */
3053         if (align < SIZEOF_VOID_P)
3054                 return FALSE;
3055
3056         /*This value cannot be bigger than 32 due to the way we calculate the required wb bitmap.*/
3057         if (size > 32 * SIZEOF_VOID_P)
3058                 return FALSE;
3059
3060         create_write_barrier_bitmap (cfg, klass, &need_wb, 0);
3061
3062         /* We don't unroll more than 5 stores to avoid code bloat. */
3063         if (size > 5 * SIZEOF_VOID_P) {
3064                 /*This is harmless and simplify mono_gc_wbarrier_value_copy_bitmap */
3065                 size += (SIZEOF_VOID_P - 1);
3066                 size &= ~(SIZEOF_VOID_P - 1);
3067
3068                 EMIT_NEW_ICONST (cfg, iargs [2], size);
3069                 EMIT_NEW_ICONST (cfg, iargs [3], need_wb);
3070                 mono_emit_jit_icall (cfg, mono_gc_wbarrier_value_copy_bitmap, iargs);
3071                 return TRUE;
3072         }
3073
3074         destreg = iargs [0]->dreg;
3075         srcreg = iargs [1]->dreg;
3076         offset = 0;
3077
3078         dest_ptr_reg = alloc_preg (cfg);
3079         tmp_reg = alloc_preg (cfg);
3080
3081         /*tmp = dreg*/
3082         EMIT_NEW_UNALU (cfg, iargs [0], OP_MOVE, dest_ptr_reg, destreg);
3083
3084         while (size >= SIZEOF_VOID_P) {
3085                 MonoInst *load_inst;
3086                 MONO_INST_NEW (cfg, load_inst, OP_LOAD_MEMBASE);
3087                 load_inst->dreg = tmp_reg;
3088                 load_inst->inst_basereg = srcreg;
3089                 load_inst->inst_offset = offset;
3090                 MONO_ADD_INS (cfg->cbb, load_inst);
3091
3092                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, dest_ptr_reg, 0, tmp_reg);
3093
3094                 if (need_wb & 0x1)
3095                         emit_write_barrier (cfg, iargs [0], load_inst);
3096
3097                 offset += SIZEOF_VOID_P;
3098                 size -= SIZEOF_VOID_P;
3099                 need_wb >>= 1;
3100
3101                 /*tmp += sizeof (void*)*/
3102                 if (size >= SIZEOF_VOID_P) {
3103                         NEW_BIALU_IMM (cfg, iargs [0], OP_PADD_IMM, dest_ptr_reg, dest_ptr_reg, SIZEOF_VOID_P);
3104                         MONO_ADD_INS (cfg->cbb, iargs [0]);
3105                 }
3106         }
3107
3108         /* Those cannot be references since size < sizeof (void*) */
3109         while (size >= 4) {
3110                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, tmp_reg, srcreg, offset);
3111                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI4_MEMBASE_REG, destreg, offset, tmp_reg);
3112                 offset += 4;
3113                 size -= 4;
3114         }
3115
3116         while (size >= 2) {
3117                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI2_MEMBASE, tmp_reg, srcreg, offset);
3118                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI2_MEMBASE_REG, destreg, offset, tmp_reg);
3119                 offset += 2;
3120                 size -= 2;
3121         }
3122
3123         while (size >= 1) {
3124                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI1_MEMBASE, tmp_reg, srcreg, offset);
3125                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI1_MEMBASE_REG, destreg, offset, tmp_reg);
3126                 offset += 1;
3127                 size -= 1;
3128         }
3129
3130         return TRUE;
3131 }
3132
3133 /*
3134  * Emit code to copy a valuetype of type @klass whose address is stored in
3135  * @src->dreg to memory whose address is stored at @dest->dreg.
3136  */
3137 void
3138 mini_emit_stobj (MonoCompile *cfg, MonoInst *dest, MonoInst *src, MonoClass *klass, gboolean native)
3139 {
3140         MonoInst *iargs [4];
3141         int n;
3142         guint32 align = 0;
3143         MonoMethod *memcpy_method;
3144         MonoInst *size_ins = NULL;
3145         MonoInst *memcpy_ins = NULL;
3146
3147         g_assert (klass);
3148         if (cfg->gshared)
3149                 klass = mono_class_from_mono_type (mini_get_underlying_type (&klass->byval_arg));
3150
3151         /*
3152          * This check breaks with spilled vars... need to handle it during verification anyway.
3153          * g_assert (klass && klass == src->klass && klass == dest->klass);
3154          */
3155
3156         if (mini_is_gsharedvt_klass (klass)) {
3157                 g_assert (!native);
3158                 size_ins = emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_VALUE_SIZE);
3159                 memcpy_ins = emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_MEMCPY);
3160         }
3161
3162         if (native)
3163                 n = mono_class_native_size (klass, &align);
3164         else
3165                 n = mono_class_value_size (klass, &align);
3166
3167         /* if native is true there should be no references in the struct */
3168         if (cfg->gen_write_barriers && (klass->has_references || size_ins) && !native) {
3169                 /* Avoid barriers when storing to the stack */
3170                 if (!((dest->opcode == OP_ADD_IMM && dest->sreg1 == cfg->frame_reg) ||
3171                           (dest->opcode == OP_LDADDR))) {
3172                         int context_used;
3173
3174                         iargs [0] = dest;
3175                         iargs [1] = src;
3176
3177                         context_used = mini_class_check_context_used (cfg, klass);
3178
3179                         /* It's ok to intrinsify under gsharing since shared code types are layout stable. */
3180                         if (!size_ins && (cfg->opt & MONO_OPT_INTRINS) && mono_emit_wb_aware_memcpy (cfg, klass, iargs, n, align)) {
3181                                 return;
3182                         } else if (context_used) {
3183                                 iargs [2] = mini_emit_get_rgctx_klass (cfg, context_used, klass, MONO_RGCTX_INFO_KLASS);
3184                         }  else {
3185                                 iargs [2] = emit_runtime_constant (cfg, MONO_PATCH_INFO_CLASS, klass);
3186                                 if (!cfg->compile_aot)
3187                                         mono_class_compute_gc_descriptor (klass);
3188                         }
3189
3190                         if (size_ins)
3191                                 mono_emit_jit_icall (cfg, mono_gsharedvt_value_copy, iargs);
3192                         else
3193                                 mono_emit_jit_icall (cfg, mono_value_copy, iargs);
3194                         return;
3195                 }
3196         }
3197
3198         if (!size_ins && (cfg->opt & MONO_OPT_INTRINS) && n <= sizeof (gpointer) * 8) {
3199                 /* FIXME: Optimize the case when src/dest is OP_LDADDR */
3200                 mini_emit_memcpy (cfg, dest->dreg, 0, src->dreg, 0, n, align);
3201         } else {
3202                 iargs [0] = dest;
3203                 iargs [1] = src;
3204                 if (size_ins)
3205                         iargs [2] = size_ins;
3206                 else
3207                         EMIT_NEW_ICONST (cfg, iargs [2], n);
3208                 
3209                 memcpy_method = get_memcpy_method ();
3210                 if (memcpy_ins)
3211                         mono_emit_calli (cfg, mono_method_signature (memcpy_method), iargs, memcpy_ins, NULL, NULL);
3212                 else
3213                         mono_emit_method_call (cfg, memcpy_method, iargs, NULL);
3214         }
3215 }
3216
3217 static MonoMethod*
3218 get_memset_method (void)
3219 {
3220         static MonoMethod *memset_method = NULL;
3221         if (!memset_method) {
3222                 memset_method = mono_class_get_method_from_name (mono_defaults.string_class, "memset", 3);
3223                 if (!memset_method)
3224                         g_error ("Old corlib found. Install a new one");
3225         }
3226         return memset_method;
3227 }
3228
3229 void
3230 mini_emit_initobj (MonoCompile *cfg, MonoInst *dest, const guchar *ip, MonoClass *klass)
3231 {
3232         MonoInst *iargs [3];
3233         int n;
3234         guint32 align;
3235         MonoMethod *memset_method;
3236         MonoInst *size_ins = NULL;
3237         MonoInst *bzero_ins = NULL;
3238         static MonoMethod *bzero_method;
3239
3240         /* FIXME: Optimize this for the case when dest is an LDADDR */
3241         mono_class_init (klass);
3242         if (mini_is_gsharedvt_klass (klass)) {
3243                 size_ins = emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_VALUE_SIZE);
3244                 bzero_ins = emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_BZERO);
3245                 if (!bzero_method)
3246                         bzero_method = mono_class_get_method_from_name (mono_defaults.string_class, "bzero_aligned_1", 2);
3247                 g_assert (bzero_method);
3248                 iargs [0] = dest;
3249                 iargs [1] = size_ins;
3250                 mono_emit_calli (cfg, mono_method_signature (bzero_method), iargs, bzero_ins, NULL, NULL);
3251                 return;
3252         }
3253
3254         klass = mono_class_from_mono_type (mini_get_underlying_type (&klass->byval_arg));
3255
3256         n = mono_class_value_size (klass, &align);
3257
3258         if (n <= sizeof (gpointer) * 8) {
3259                 mini_emit_memset (cfg, dest->dreg, 0, n, 0, align);
3260         }
3261         else {
3262                 memset_method = get_memset_method ();
3263                 iargs [0] = dest;
3264                 EMIT_NEW_ICONST (cfg, iargs [1], 0);
3265                 EMIT_NEW_ICONST (cfg, iargs [2], n);
3266                 mono_emit_method_call (cfg, memset_method, iargs, NULL);
3267         }
3268 }
3269
3270 /*
3271  * emit_get_rgctx:
3272  *
3273  *   Emit IR to return either the this pointer for instance method,
3274  * or the mrgctx for static methods.
3275  */
3276 static MonoInst*
3277 emit_get_rgctx (MonoCompile *cfg, MonoMethod *method, int context_used)
3278 {
3279         MonoInst *this_ins = NULL;
3280
3281         g_assert (cfg->gshared);
3282
3283         if (!(method->flags & METHOD_ATTRIBUTE_STATIC) &&
3284                         !(context_used & MONO_GENERIC_CONTEXT_USED_METHOD) &&
3285                 !method->klass->valuetype)
3286                 EMIT_NEW_VARLOAD (cfg, this_ins, cfg->this_arg, &mono_defaults.object_class->byval_arg);
3287
3288         if (context_used & MONO_GENERIC_CONTEXT_USED_METHOD) {
3289                 MonoInst *mrgctx_loc, *mrgctx_var;
3290
3291                 g_assert (!this_ins);
3292                 g_assert (method->is_inflated && mono_method_get_context (method)->method_inst);
3293
3294                 mrgctx_loc = mono_get_vtable_var (cfg);
3295                 EMIT_NEW_TEMPLOAD (cfg, mrgctx_var, mrgctx_loc->inst_c0);
3296
3297                 return mrgctx_var;
3298         } else if (MONO_CLASS_IS_INTERFACE (cfg->method->klass)) {
3299                 MonoInst *mrgctx_loc, *mrgctx_var;
3300
3301                 /* Default interface methods need an mrgctx since the vtabke at runtime points at an implementing class */
3302                 mrgctx_loc = mono_get_vtable_var (cfg);
3303                 EMIT_NEW_TEMPLOAD (cfg, mrgctx_var, mrgctx_loc->inst_c0);
3304
3305                 g_assert (mono_method_needs_static_rgctx_invoke (cfg->method, TRUE));
3306
3307                 return mrgctx_var;
3308         } else if (method->flags & METHOD_ATTRIBUTE_STATIC || method->klass->valuetype) {
3309                 MonoInst *vtable_loc, *vtable_var;
3310
3311                 g_assert (!this_ins);
3312
3313                 vtable_loc = mono_get_vtable_var (cfg);
3314                 EMIT_NEW_TEMPLOAD (cfg, vtable_var, vtable_loc->inst_c0);
3315
3316                 if (method->is_inflated && mono_method_get_context (method)->method_inst) {
3317                         MonoInst *mrgctx_var = vtable_var;
3318                         int vtable_reg;
3319
3320                         vtable_reg = alloc_preg (cfg);
3321                         EMIT_NEW_LOAD_MEMBASE (cfg, vtable_var, OP_LOAD_MEMBASE, vtable_reg, mrgctx_var->dreg, MONO_STRUCT_OFFSET (MonoMethodRuntimeGenericContext, class_vtable));
3322                         vtable_var->type = STACK_PTR;
3323                 }
3324
3325                 return vtable_var;
3326         } else {
3327                 MonoInst *ins;
3328                 int vtable_reg;
3329         
3330                 vtable_reg = alloc_preg (cfg);
3331                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, vtable_reg, this_ins->dreg, MONO_STRUCT_OFFSET (MonoObject, vtable));
3332                 return ins;
3333         }
3334 }
3335
3336 static MonoJumpInfoRgctxEntry *
3337 mono_patch_info_rgctx_entry_new (MonoMemPool *mp, MonoMethod *method, gboolean in_mrgctx, MonoJumpInfoType patch_type, gconstpointer patch_data, MonoRgctxInfoType info_type)
3338 {
3339         MonoJumpInfoRgctxEntry *res = (MonoJumpInfoRgctxEntry *)mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoRgctxEntry));
3340         res->method = method;
3341         res->in_mrgctx = in_mrgctx;
3342         res->data = (MonoJumpInfo *)mono_mempool_alloc0 (mp, sizeof (MonoJumpInfo));
3343         res->data->type = patch_type;
3344         res->data->data.target = patch_data;
3345         res->info_type = info_type;
3346
3347         return res;
3348 }
3349
3350 static inline MonoInst*
3351 emit_rgctx_fetch_inline (MonoCompile *cfg, MonoInst *rgctx, MonoJumpInfoRgctxEntry *entry)
3352 {
3353         MonoInst *args [16];
3354         MonoInst *call;
3355
3356         // FIXME: No fastpath since the slot is not a compile time constant
3357         args [0] = rgctx;
3358         EMIT_NEW_AOTCONST (cfg, args [1], MONO_PATCH_INFO_RGCTX_SLOT_INDEX, entry);
3359         if (entry->in_mrgctx)
3360                 call = mono_emit_jit_icall (cfg, mono_fill_method_rgctx, args);
3361         else
3362                 call = mono_emit_jit_icall (cfg, mono_fill_class_rgctx, args);
3363         return call;
3364 #if 0
3365         /*
3366          * FIXME: This can be called during decompose, which is a problem since it creates
3367          * new bblocks.
3368          * Also, the fastpath doesn't work since the slot number is dynamically allocated.
3369          */
3370         int i, slot, depth, index, rgctx_reg, val_reg, res_reg;
3371         gboolean mrgctx;
3372         MonoBasicBlock *is_null_bb, *end_bb;
3373         MonoInst *res, *ins, *call;
3374         MonoInst *args[16];
3375
3376         slot = mini_get_rgctx_entry_slot (entry);
3377
3378         mrgctx = MONO_RGCTX_SLOT_IS_MRGCTX (slot);
3379         index = MONO_RGCTX_SLOT_INDEX (slot);
3380         if (mrgctx)
3381                 index += MONO_SIZEOF_METHOD_RUNTIME_GENERIC_CONTEXT / sizeof (gpointer);
3382         for (depth = 0; ; ++depth) {
3383                 int size = mono_class_rgctx_get_array_size (depth, mrgctx);
3384
3385                 if (index < size - 1)
3386                         break;
3387                 index -= size - 1;
3388         }
3389
3390         NEW_BBLOCK (cfg, end_bb);
3391         NEW_BBLOCK (cfg, is_null_bb);
3392
3393         if (mrgctx) {
3394                 rgctx_reg = rgctx->dreg;
3395         } else {
3396                 rgctx_reg = alloc_preg (cfg);
3397
3398                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, rgctx_reg, rgctx->dreg, MONO_STRUCT_OFFSET (MonoVTable, runtime_generic_context));
3399                 // FIXME: Avoid this check by allocating the table when the vtable is created etc.
3400                 NEW_BBLOCK (cfg, is_null_bb);
3401
3402                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, rgctx_reg, 0);
3403                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, is_null_bb);
3404         }
3405
3406         for (i = 0; i < depth; ++i) {
3407                 int array_reg = alloc_preg (cfg);
3408
3409                 /* load ptr to next array */
3410                 if (mrgctx && i == 0)
3411                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, array_reg, rgctx_reg, MONO_SIZEOF_METHOD_RUNTIME_GENERIC_CONTEXT);
3412                 else
3413                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, array_reg, rgctx_reg, 0);
3414                 rgctx_reg = array_reg;
3415                 /* is the ptr null? */
3416                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, rgctx_reg, 0);
3417                 /* if yes, jump to actual trampoline */
3418                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, is_null_bb);
3419         }
3420
3421         /* fetch slot */
3422         val_reg = alloc_preg (cfg);
3423         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, val_reg, rgctx_reg, (index + 1) * sizeof (gpointer));
3424         /* is the slot null? */
3425         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, val_reg, 0);
3426         /* if yes, jump to actual trampoline */
3427         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, is_null_bb);
3428
3429         /* Fastpath */
3430         res_reg = alloc_preg (cfg);
3431         MONO_INST_NEW (cfg, ins, OP_MOVE);
3432         ins->dreg = res_reg;
3433         ins->sreg1 = val_reg;
3434         MONO_ADD_INS (cfg->cbb, ins);
3435         res = ins;
3436         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
3437
3438         /* Slowpath */
3439         MONO_START_BB (cfg, is_null_bb);
3440         args [0] = rgctx;
3441         EMIT_NEW_ICONST (cfg, args [1], index);
3442         if (mrgctx)
3443                 call = mono_emit_jit_icall (cfg, mono_fill_method_rgctx, args);
3444         else
3445                 call = mono_emit_jit_icall (cfg, mono_fill_class_rgctx, args);
3446         MONO_INST_NEW (cfg, ins, OP_MOVE);
3447         ins->dreg = res_reg;
3448         ins->sreg1 = call->dreg;
3449         MONO_ADD_INS (cfg->cbb, ins);
3450         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
3451
3452         MONO_START_BB (cfg, end_bb);
3453
3454         return res;
3455 #endif
3456 }
3457
3458 /*
3459  * emit_rgctx_fetch:
3460  *
3461  *   Emit IR to load the value of the rgctx entry ENTRY from the rgctx
3462  * given by RGCTX.
3463  */
3464 static inline MonoInst*
3465 emit_rgctx_fetch (MonoCompile *cfg, MonoInst *rgctx, MonoJumpInfoRgctxEntry *entry)
3466 {
3467         if (cfg->llvm_only)
3468                 return emit_rgctx_fetch_inline (cfg, rgctx, entry);
3469         else
3470                 return mono_emit_abs_call (cfg, MONO_PATCH_INFO_RGCTX_FETCH, entry, helper_sig_rgctx_lazy_fetch_trampoline, &rgctx);
3471 }
3472
3473 MonoInst*
3474 mini_emit_get_rgctx_klass (MonoCompile *cfg, int context_used,
3475                                           MonoClass *klass, MonoRgctxInfoType rgctx_type)
3476 {
3477         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);
3478         MonoInst *rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3479
3480         return emit_rgctx_fetch (cfg, rgctx, entry);
3481 }
3482
3483 static MonoInst*
3484 emit_get_rgctx_sig (MonoCompile *cfg, int context_used,
3485                                         MonoMethodSignature *sig, MonoRgctxInfoType rgctx_type)
3486 {
3487         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);
3488         MonoInst *rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3489
3490         return emit_rgctx_fetch (cfg, rgctx, entry);
3491 }
3492
3493 static MonoInst*
3494 emit_get_rgctx_gsharedvt_call (MonoCompile *cfg, int context_used,
3495                                                            MonoMethodSignature *sig, MonoMethod *cmethod, MonoRgctxInfoType rgctx_type)
3496 {
3497         MonoJumpInfoGSharedVtCall *call_info;
3498         MonoJumpInfoRgctxEntry *entry;
3499         MonoInst *rgctx;
3500
3501         call_info = (MonoJumpInfoGSharedVtCall *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoJumpInfoGSharedVtCall));
3502         call_info->sig = sig;
3503         call_info->method = cmethod;
3504
3505         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);
3506         rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3507
3508         return emit_rgctx_fetch (cfg, rgctx, entry);
3509 }
3510
3511 /*
3512  * emit_get_rgctx_virt_method:
3513  *
3514  *   Return data for method VIRT_METHOD for a receiver of type KLASS.
3515  */
3516 static MonoInst*
3517 emit_get_rgctx_virt_method (MonoCompile *cfg, int context_used,
3518                                                         MonoClass *klass, MonoMethod *virt_method, MonoRgctxInfoType rgctx_type)
3519 {
3520         MonoJumpInfoVirtMethod *info;
3521         MonoJumpInfoRgctxEntry *entry;
3522         MonoInst *rgctx;
3523
3524         info = (MonoJumpInfoVirtMethod *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoJumpInfoVirtMethod));
3525         info->klass = klass;
3526         info->method = virt_method;
3527
3528         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);
3529         rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3530
3531         return emit_rgctx_fetch (cfg, rgctx, entry);
3532 }
3533
3534 static MonoInst*
3535 emit_get_rgctx_gsharedvt_method (MonoCompile *cfg, int context_used,
3536                                                                  MonoMethod *cmethod, MonoGSharedVtMethodInfo *info)
3537 {
3538         MonoJumpInfoRgctxEntry *entry;
3539         MonoInst *rgctx;
3540
3541         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);
3542         rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3543
3544         return emit_rgctx_fetch (cfg, rgctx, entry);
3545 }
3546
3547 /*
3548  * emit_get_rgctx_method:
3549  *
3550  *   Emit IR to load the property RGCTX_TYPE of CMETHOD. If context_used is 0, emit
3551  * normal constants, else emit a load from the rgctx.
3552  */
3553 static MonoInst*
3554 emit_get_rgctx_method (MonoCompile *cfg, int context_used,
3555                                            MonoMethod *cmethod, MonoRgctxInfoType rgctx_type)
3556 {
3557         if (!context_used) {
3558                 MonoInst *ins;
3559
3560                 switch (rgctx_type) {
3561                 case MONO_RGCTX_INFO_METHOD:
3562                         EMIT_NEW_METHODCONST (cfg, ins, cmethod);
3563                         return ins;
3564                 case MONO_RGCTX_INFO_METHOD_RGCTX:
3565                         EMIT_NEW_METHOD_RGCTX_CONST (cfg, ins, cmethod);
3566                         return ins;
3567                 default:
3568                         g_assert_not_reached ();
3569                 }
3570         } else {
3571                 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);
3572                 MonoInst *rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3573
3574                 return emit_rgctx_fetch (cfg, rgctx, entry);
3575         }
3576 }
3577
3578 static MonoInst*
3579 emit_get_rgctx_field (MonoCompile *cfg, int context_used,
3580                                           MonoClassField *field, MonoRgctxInfoType rgctx_type)
3581 {
3582         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);
3583         MonoInst *rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3584
3585         return emit_rgctx_fetch (cfg, rgctx, entry);
3586 }
3587
3588 static int
3589 get_gsharedvt_info_slot (MonoCompile *cfg, gpointer data, MonoRgctxInfoType rgctx_type)
3590 {
3591         MonoGSharedVtMethodInfo *info = cfg->gsharedvt_info;
3592         MonoRuntimeGenericContextInfoTemplate *template_;
3593         int i, idx;
3594
3595         g_assert (info);
3596
3597         for (i = 0; i < info->num_entries; ++i) {
3598                 MonoRuntimeGenericContextInfoTemplate *otemplate = &info->entries [i];
3599
3600                 if (otemplate->info_type == rgctx_type && otemplate->data == data && rgctx_type != MONO_RGCTX_INFO_LOCAL_OFFSET)
3601                         return i;
3602         }
3603
3604         if (info->num_entries == info->count_entries) {
3605                 MonoRuntimeGenericContextInfoTemplate *new_entries;
3606                 int new_count_entries = info->count_entries ? info->count_entries * 2 : 16;
3607
3608                 new_entries = (MonoRuntimeGenericContextInfoTemplate *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoRuntimeGenericContextInfoTemplate) * new_count_entries);
3609
3610                 memcpy (new_entries, info->entries, sizeof (MonoRuntimeGenericContextInfoTemplate) * info->count_entries);
3611                 info->entries = new_entries;
3612                 info->count_entries = new_count_entries;
3613         }
3614
3615         idx = info->num_entries;
3616         template_ = &info->entries [idx];
3617         template_->info_type = rgctx_type;
3618         template_->data = data;
3619
3620         info->num_entries ++;
3621
3622         return idx;
3623 }
3624
3625 /*
3626  * emit_get_gsharedvt_info:
3627  *
3628  *   This is similar to emit_get_rgctx_.., but loads the data from the gsharedvt info var instead of calling an rgctx fetch trampoline.
3629  */
3630 static MonoInst*
3631 emit_get_gsharedvt_info (MonoCompile *cfg, gpointer data, MonoRgctxInfoType rgctx_type)
3632 {
3633         MonoInst *ins;
3634         int idx, dreg;
3635
3636         idx = get_gsharedvt_info_slot (cfg, data, rgctx_type);
3637         /* Load info->entries [idx] */
3638         dreg = alloc_preg (cfg);
3639         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, dreg, cfg->gsharedvt_info_var->dreg, MONO_STRUCT_OFFSET (MonoGSharedVtMethodRuntimeInfo, entries) + (idx * sizeof (gpointer)));
3640
3641         return ins;
3642 }
3643
3644 static MonoInst*
3645 emit_get_gsharedvt_info_klass (MonoCompile *cfg, MonoClass *klass, MonoRgctxInfoType rgctx_type)
3646 {
3647         return emit_get_gsharedvt_info (cfg, &klass->byval_arg, rgctx_type);
3648 }
3649
3650 /*
3651  * On return the caller must check @klass for load errors.
3652  */
3653 static void
3654 emit_class_init (MonoCompile *cfg, MonoClass *klass)
3655 {
3656         MonoInst *vtable_arg;
3657         int context_used;
3658
3659         context_used = mini_class_check_context_used (cfg, klass);
3660
3661         if (context_used) {
3662                 vtable_arg = mini_emit_get_rgctx_klass (cfg, context_used,
3663                                                                                    klass, MONO_RGCTX_INFO_VTABLE);
3664         } else {
3665                 MonoVTable *vtable = mono_class_vtable (cfg->domain, klass);
3666
3667                 if (!vtable)
3668                         return;
3669                 EMIT_NEW_VTABLECONST (cfg, vtable_arg, vtable);
3670         }
3671
3672         if (!COMPILE_LLVM (cfg) && cfg->backend->have_op_generic_class_init) {
3673                 MonoInst *ins;
3674
3675                 /*
3676                  * Using an opcode instead of emitting IR here allows the hiding of the call inside the opcode,
3677                  * so this doesn't have to clobber any regs and it doesn't break basic blocks.
3678                  */
3679                 MONO_INST_NEW (cfg, ins, OP_GENERIC_CLASS_INIT);
3680                 ins->sreg1 = vtable_arg->dreg;
3681                 MONO_ADD_INS (cfg->cbb, ins);
3682         } else {
3683                 int inited_reg;
3684                 MonoBasicBlock *inited_bb;
3685                 MonoInst *args [16];
3686
3687                 inited_reg = alloc_ireg (cfg);
3688
3689                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADU1_MEMBASE, inited_reg, vtable_arg->dreg, MONO_STRUCT_OFFSET (MonoVTable, initialized));
3690
3691                 NEW_BBLOCK (cfg, inited_bb);
3692
3693                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, inited_reg, 0);
3694                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBNE_UN, inited_bb);
3695
3696                 args [0] = vtable_arg;
3697                 mono_emit_jit_icall (cfg, mono_generic_class_init, args);
3698
3699                 MONO_START_BB (cfg, inited_bb);
3700         }
3701 }
3702
3703 static void
3704 emit_seq_point (MonoCompile *cfg, MonoMethod *method, guint8* ip, gboolean intr_loc, gboolean nonempty_stack)
3705 {
3706         MonoInst *ins;
3707
3708         if (cfg->gen_seq_points && cfg->method == method) {
3709                 NEW_SEQ_POINT (cfg, ins, ip - cfg->header->code, intr_loc);
3710                 if (nonempty_stack)
3711                         ins->flags |= MONO_INST_NONEMPTY_STACK;
3712                 MONO_ADD_INS (cfg->cbb, ins);
3713         }
3714 }
3715
3716 void
3717 mini_save_cast_details (MonoCompile *cfg, MonoClass *klass, int obj_reg, gboolean null_check)
3718 {
3719         if (mini_get_debug_options ()->better_cast_details) {
3720                 int vtable_reg = alloc_preg (cfg);
3721                 int klass_reg = alloc_preg (cfg);
3722                 MonoBasicBlock *is_null_bb = NULL;
3723                 MonoInst *tls_get;
3724                 int to_klass_reg, context_used;
3725
3726                 if (null_check) {
3727                         NEW_BBLOCK (cfg, is_null_bb);
3728
3729                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, obj_reg, 0);
3730                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, is_null_bb);
3731                 }
3732
3733                 tls_get = mono_create_tls_get (cfg, TLS_KEY_JIT_TLS);
3734                 if (!tls_get) {
3735                         fprintf (stderr, "error: --debug=casts not supported on this platform.\n.");
3736                         exit (1);
3737                 }
3738
3739                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, vtable_reg, obj_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
3740                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, klass));
3741
3742                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, tls_get->dreg, MONO_STRUCT_OFFSET (MonoJitTlsData, class_cast_from), klass_reg);
3743
3744                 context_used = mini_class_check_context_used (cfg, klass);
3745                 if (context_used) {
3746                         MonoInst *class_ins;
3747
3748                         class_ins = mini_emit_get_rgctx_klass (cfg, context_used, klass, MONO_RGCTX_INFO_KLASS);
3749                         to_klass_reg = class_ins->dreg;
3750                 } else {
3751                         to_klass_reg = alloc_preg (cfg);
3752                         MONO_EMIT_NEW_CLASSCONST (cfg, to_klass_reg, klass);
3753                 }
3754                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, tls_get->dreg, MONO_STRUCT_OFFSET (MonoJitTlsData, class_cast_to), to_klass_reg);
3755
3756                 if (null_check)
3757                         MONO_START_BB (cfg, is_null_bb);
3758         }
3759 }
3760
3761 void
3762 mini_reset_cast_details (MonoCompile *cfg)
3763 {
3764         /* Reset the variables holding the cast details */
3765         if (mini_get_debug_options ()->better_cast_details) {
3766                 MonoInst *tls_get = mono_create_tls_get (cfg, TLS_KEY_JIT_TLS);
3767                 /* It is enough to reset the from field */
3768                 MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STORE_MEMBASE_IMM, tls_get->dreg, MONO_STRUCT_OFFSET (MonoJitTlsData, class_cast_from), 0);
3769         }
3770 }
3771
3772 /*
3773  * On return the caller must check @array_class for load errors
3774  */
3775 static void
3776 mini_emit_check_array_type (MonoCompile *cfg, MonoInst *obj, MonoClass *array_class)
3777 {
3778         int vtable_reg = alloc_preg (cfg);
3779         int context_used;
3780
3781         context_used = mini_class_check_context_used (cfg, array_class);
3782
3783         mini_save_cast_details (cfg, array_class, obj->dreg, FALSE);
3784
3785         MONO_EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, vtable_reg, obj->dreg, MONO_STRUCT_OFFSET (MonoObject, vtable));
3786
3787         if (cfg->opt & MONO_OPT_SHARED) {
3788                 int class_reg = alloc_preg (cfg);
3789                 MonoInst *ins;
3790
3791                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, class_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, klass));
3792                 ins = emit_runtime_constant (cfg, MONO_PATCH_INFO_CLASS, array_class);
3793                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, class_reg, ins->dreg);
3794         } else if (context_used) {
3795                 MonoInst *vtable_ins;
3796
3797                 vtable_ins = mini_emit_get_rgctx_klass (cfg, context_used, array_class, MONO_RGCTX_INFO_VTABLE);
3798                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, vtable_reg, vtable_ins->dreg);
3799         } else {
3800                 if (cfg->compile_aot) {
3801                         int vt_reg;
3802                         MonoVTable *vtable;
3803
3804                         if (!(vtable = mono_class_vtable (cfg->domain, array_class)))
3805                                 return;
3806                         vt_reg = alloc_preg (cfg);
3807                         MONO_EMIT_NEW_VTABLECONST (cfg, vt_reg, vtable);
3808                         MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, vtable_reg, vt_reg);
3809                 } else {
3810                         MonoVTable *vtable;
3811                         if (!(vtable = mono_class_vtable (cfg->domain, array_class)))
3812                                 return;
3813                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, vtable_reg, vtable);
3814                 }
3815         }
3816         
3817         MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "ArrayTypeMismatchException");
3818
3819         mini_reset_cast_details (cfg);
3820 }
3821
3822 /**
3823  * Handles unbox of a Nullable<T>. If context_used is non zero, then shared 
3824  * generic code is generated.
3825  */
3826 static MonoInst*
3827 handle_unbox_nullable (MonoCompile* cfg, MonoInst* val, MonoClass* klass, int context_used)
3828 {
3829         MonoMethod* method = mono_class_get_method_from_name (klass, "Unbox", 1);
3830
3831         if (context_used) {
3832                 MonoInst *rgctx, *addr;
3833
3834                 /* FIXME: What if the class is shared?  We might not
3835                    have to get the address of the method from the
3836                    RGCTX. */
3837                 addr = emit_get_rgctx_method (cfg, context_used, method,
3838                                                                           MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
3839                 if (cfg->llvm_only) {
3840                         cfg->signatures = g_slist_prepend_mempool (cfg->mempool, cfg->signatures, mono_method_signature (method));
3841                         return emit_llvmonly_calli (cfg, mono_method_signature (method), &val, addr);
3842                 } else {
3843                         rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3844
3845                         return mono_emit_calli (cfg, mono_method_signature (method), &val, addr, NULL, rgctx);
3846                 }
3847         } else {
3848                 gboolean pass_vtable, pass_mrgctx;
3849                 MonoInst *rgctx_arg = NULL;
3850
3851                 check_method_sharing (cfg, method, &pass_vtable, &pass_mrgctx);
3852                 g_assert (!pass_mrgctx);
3853
3854                 if (pass_vtable) {
3855                         MonoVTable *vtable = mono_class_vtable (cfg->domain, method->klass);
3856
3857                         g_assert (vtable);
3858                         EMIT_NEW_VTABLECONST (cfg, rgctx_arg, vtable);
3859                 }
3860
3861                 return mono_emit_method_call_full (cfg, method, NULL, FALSE, &val, NULL, NULL, rgctx_arg);
3862         }
3863 }
3864
3865 static MonoInst*
3866 handle_unbox (MonoCompile *cfg, MonoClass *klass, MonoInst **sp, int context_used)
3867 {
3868         MonoInst *add;
3869         int obj_reg;
3870         int vtable_reg = alloc_dreg (cfg ,STACK_PTR);
3871         int klass_reg = alloc_dreg (cfg ,STACK_PTR);
3872         int eclass_reg = alloc_dreg (cfg ,STACK_PTR);
3873         int rank_reg = alloc_dreg (cfg ,STACK_I4);
3874
3875         obj_reg = sp [0]->dreg;
3876         MONO_EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, vtable_reg, obj_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
3877         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADU1_MEMBASE, rank_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, rank));
3878
3879         /* FIXME: generics */
3880         g_assert (klass->rank == 0);
3881                         
3882         // Check rank == 0
3883         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, rank_reg, 0);
3884         MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "InvalidCastException");
3885
3886         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, klass));
3887         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, eclass_reg, klass_reg, MONO_STRUCT_OFFSET (MonoClass, element_class));
3888
3889         if (context_used) {
3890                 MonoInst *element_class;
3891
3892                 /* This assertion is from the unboxcast insn */
3893                 g_assert (klass->rank == 0);
3894
3895                 element_class = mini_emit_get_rgctx_klass (cfg, context_used,
3896                                 klass, MONO_RGCTX_INFO_ELEMENT_KLASS);
3897
3898                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, eclass_reg, element_class->dreg);
3899                 MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "InvalidCastException");
3900         } else {
3901                 mini_save_cast_details (cfg, klass->element_class, obj_reg, FALSE);
3902                 mini_emit_class_check (cfg, eclass_reg, klass->element_class);
3903                 mini_reset_cast_details (cfg);
3904         }
3905
3906         NEW_BIALU_IMM (cfg, add, OP_ADD_IMM, alloc_dreg (cfg, STACK_MP), obj_reg, sizeof (MonoObject));
3907         MONO_ADD_INS (cfg->cbb, add);
3908         add->type = STACK_MP;
3909         add->klass = klass;
3910
3911         return add;
3912 }
3913
3914 static MonoInst*
3915 handle_unbox_gsharedvt (MonoCompile *cfg, MonoClass *klass, MonoInst *obj)
3916 {
3917         MonoInst *addr, *klass_inst, *is_ref, *args[16];
3918         MonoBasicBlock *is_ref_bb, *is_nullable_bb, *end_bb;
3919         MonoInst *ins;
3920         int dreg, addr_reg;
3921
3922         klass_inst = emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_KLASS);
3923
3924         /* obj */
3925         args [0] = obj;
3926
3927         /* klass */
3928         args [1] = klass_inst;
3929
3930         /* CASTCLASS */
3931         obj = mono_emit_jit_icall (cfg, mono_object_castclass_unbox, args);
3932
3933         NEW_BBLOCK (cfg, is_ref_bb);
3934         NEW_BBLOCK (cfg, is_nullable_bb);
3935         NEW_BBLOCK (cfg, end_bb);
3936         is_ref = emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_CLASS_BOX_TYPE);
3937         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, is_ref->dreg, MONO_GSHAREDVT_BOX_TYPE_REF);
3938         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, is_ref_bb);
3939
3940         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, is_ref->dreg, MONO_GSHAREDVT_BOX_TYPE_NULLABLE);
3941         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, is_nullable_bb);
3942
3943         /* This will contain either the address of the unboxed vtype, or an address of the temporary where the ref is stored */
3944         addr_reg = alloc_dreg (cfg, STACK_MP);
3945
3946         /* Non-ref case */
3947         /* UNBOX */
3948         NEW_BIALU_IMM (cfg, addr, OP_ADD_IMM, addr_reg, obj->dreg, sizeof (MonoObject));
3949         MONO_ADD_INS (cfg->cbb, addr);
3950
3951         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
3952
3953         /* Ref case */
3954         MONO_START_BB (cfg, is_ref_bb);
3955
3956         /* Save the ref to a temporary */
3957         dreg = alloc_ireg (cfg);
3958         EMIT_NEW_VARLOADA_VREG (cfg, addr, dreg, &klass->byval_arg);
3959         addr->dreg = addr_reg;
3960         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, addr->dreg, 0, obj->dreg);
3961         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
3962
3963         /* Nullable case */
3964         MONO_START_BB (cfg, is_nullable_bb);
3965
3966         {
3967                 MonoInst *addr = emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_NULLABLE_CLASS_UNBOX);
3968                 MonoInst *unbox_call;
3969                 MonoMethodSignature *unbox_sig;
3970
3971                 unbox_sig = (MonoMethodSignature *)mono_mempool_alloc0 (cfg->mempool, MONO_SIZEOF_METHOD_SIGNATURE + (1 * sizeof (MonoType *)));
3972                 unbox_sig->ret = &klass->byval_arg;
3973                 unbox_sig->param_count = 1;
3974                 unbox_sig->params [0] = &mono_defaults.object_class->byval_arg;
3975
3976                 if (cfg->llvm_only)
3977                         unbox_call = emit_llvmonly_calli (cfg, unbox_sig, &obj, addr);
3978                 else
3979                         unbox_call = mono_emit_calli (cfg, unbox_sig, &obj, addr, NULL, NULL);
3980
3981                 EMIT_NEW_VARLOADA_VREG (cfg, addr, unbox_call->dreg, &klass->byval_arg);
3982                 addr->dreg = addr_reg;
3983         }
3984
3985         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
3986
3987         /* End */
3988         MONO_START_BB (cfg, end_bb);
3989
3990         /* LDOBJ */
3991         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr_reg, 0);
3992
3993         return ins;
3994 }
3995
3996 /*
3997  * Returns NULL and set the cfg exception on error.
3998  */
3999 static MonoInst*
4000 handle_alloc (MonoCompile *cfg, MonoClass *klass, gboolean for_box, int context_used)
4001 {
4002         MonoInst *iargs [2];
4003         void *alloc_ftn;
4004
4005         if (context_used) {
4006                 MonoInst *data;
4007                 MonoRgctxInfoType rgctx_info;
4008                 MonoInst *iargs [2];
4009                 gboolean known_instance_size = !mini_is_gsharedvt_klass (klass);
4010
4011                 MonoMethod *managed_alloc = mono_gc_get_managed_allocator (klass, for_box, known_instance_size);
4012
4013                 if (cfg->opt & MONO_OPT_SHARED)
4014                         rgctx_info = MONO_RGCTX_INFO_KLASS;
4015                 else
4016                         rgctx_info = MONO_RGCTX_INFO_VTABLE;
4017                 data = mini_emit_get_rgctx_klass (cfg, context_used, klass, rgctx_info);
4018
4019                 if (cfg->opt & MONO_OPT_SHARED) {
4020                         EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
4021                         iargs [1] = data;
4022                         alloc_ftn = ves_icall_object_new;
4023                 } else {
4024                         iargs [0] = data;
4025                         alloc_ftn = ves_icall_object_new_specific;
4026                 }
4027
4028                 if (managed_alloc && !(cfg->opt & MONO_OPT_SHARED)) {
4029                         if (known_instance_size) {
4030                                 int size = mono_class_instance_size (klass);
4031                                 if (size < sizeof (MonoObject))
4032                                         g_error ("Invalid size %d for class %s", size, mono_type_get_full_name (klass));
4033
4034                                 EMIT_NEW_ICONST (cfg, iargs [1], size);
4035                         }
4036                         return mono_emit_method_call (cfg, managed_alloc, iargs, NULL);
4037                 }
4038
4039                 return mono_emit_jit_icall (cfg, alloc_ftn, iargs);
4040         }
4041
4042         if (cfg->opt & MONO_OPT_SHARED) {
4043                 EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
4044                 EMIT_NEW_CLASSCONST (cfg, iargs [1], klass);
4045
4046                 alloc_ftn = ves_icall_object_new;
4047         } else if (cfg->compile_aot && cfg->cbb->out_of_line && klass->type_token && klass->image == mono_defaults.corlib && !mono_class_is_ginst (klass)) {
4048                 /* This happens often in argument checking code, eg. throw new FooException... */
4049                 /* Avoid relocations and save some space by calling a helper function specialized to mscorlib */
4050                 EMIT_NEW_ICONST (cfg, iargs [0], mono_metadata_token_index (klass->type_token));
4051                 return mono_emit_jit_icall (cfg, mono_helper_newobj_mscorlib, iargs);
4052         } else {
4053                 MonoVTable *vtable = mono_class_vtable (cfg->domain, klass);
4054                 MonoMethod *managed_alloc = NULL;
4055                 gboolean pass_lw;
4056
4057                 if (!vtable) {
4058                         mono_cfg_set_exception (cfg, MONO_EXCEPTION_TYPE_LOAD);
4059                         cfg->exception_ptr = klass;
4060                         return NULL;
4061                 }
4062
4063                 managed_alloc = mono_gc_get_managed_allocator (klass, for_box, TRUE);
4064
4065                 if (managed_alloc) {
4066                         int size = mono_class_instance_size (klass);
4067                         if (size < sizeof (MonoObject))
4068                                 g_error ("Invalid size %d for class %s", size, mono_type_get_full_name (klass));
4069
4070                         EMIT_NEW_VTABLECONST (cfg, iargs [0], vtable);
4071                         EMIT_NEW_ICONST (cfg, iargs [1], size);
4072                         return mono_emit_method_call (cfg, managed_alloc, iargs, NULL);
4073                 }
4074                 alloc_ftn = mono_class_get_allocation_ftn (vtable, for_box, &pass_lw);
4075                 if (pass_lw) {
4076                         guint32 lw = vtable->klass->instance_size;
4077                         lw = ((lw + (sizeof (gpointer) - 1)) & ~(sizeof (gpointer) - 1)) / sizeof (gpointer);
4078                         EMIT_NEW_ICONST (cfg, iargs [0], lw);
4079                         EMIT_NEW_VTABLECONST (cfg, iargs [1], vtable);
4080                 }
4081                 else {
4082                         EMIT_NEW_VTABLECONST (cfg, iargs [0], vtable);
4083                 }
4084         }
4085
4086         return mono_emit_jit_icall (cfg, alloc_ftn, iargs);
4087 }
4088         
4089 /*
4090  * Returns NULL and set the cfg exception on error.
4091  */     
4092 static MonoInst*
4093 handle_box (MonoCompile *cfg, MonoInst *val, MonoClass *klass, int context_used)
4094 {
4095         MonoInst *alloc, *ins;
4096
4097         if (mono_class_is_nullable (klass)) {
4098                 MonoMethod* method = mono_class_get_method_from_name (klass, "Box", 1);
4099
4100                 if (context_used) {
4101                         if (cfg->llvm_only && cfg->gsharedvt) {
4102                                 MonoInst *addr = emit_get_rgctx_method (cfg, context_used, method,
4103                                                                                                                 MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
4104                                 return emit_llvmonly_calli (cfg, mono_method_signature (method), &val, addr);
4105                         } else {
4106                                 /* FIXME: What if the class is shared?  We might not
4107                                    have to get the method address from the RGCTX. */
4108                                 MonoInst *addr = emit_get_rgctx_method (cfg, context_used, method,
4109                                                                                                                 MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
4110                                 MonoInst *rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
4111
4112                                 return mono_emit_calli (cfg, mono_method_signature (method), &val, addr, NULL, rgctx);
4113                         }
4114                 } else {
4115                         gboolean pass_vtable, pass_mrgctx;
4116                         MonoInst *rgctx_arg = NULL;
4117
4118                         check_method_sharing (cfg, method, &pass_vtable, &pass_mrgctx);
4119                         g_assert (!pass_mrgctx);
4120
4121                         if (pass_vtable) {
4122                                 MonoVTable *vtable = mono_class_vtable (cfg->domain, method->klass);
4123
4124                                 g_assert (vtable);
4125                                 EMIT_NEW_VTABLECONST (cfg, rgctx_arg, vtable);
4126                         }
4127
4128                         return mono_emit_method_call_full (cfg, method, NULL, FALSE, &val, NULL, NULL, rgctx_arg);
4129                 }
4130         }
4131
4132         if (mini_is_gsharedvt_klass (klass)) {
4133                 MonoBasicBlock *is_ref_bb, *is_nullable_bb, *end_bb;
4134                 MonoInst *res, *is_ref, *src_var, *addr;
4135                 int dreg;
4136
4137                 dreg = alloc_ireg (cfg);
4138
4139                 NEW_BBLOCK (cfg, is_ref_bb);
4140                 NEW_BBLOCK (cfg, is_nullable_bb);
4141                 NEW_BBLOCK (cfg, end_bb);
4142                 is_ref = emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_CLASS_BOX_TYPE);
4143                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, is_ref->dreg, MONO_GSHAREDVT_BOX_TYPE_REF);
4144                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, is_ref_bb);
4145
4146                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, is_ref->dreg, MONO_GSHAREDVT_BOX_TYPE_NULLABLE);
4147                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, is_nullable_bb);
4148
4149                 /* Non-ref case */
4150                 alloc = handle_alloc (cfg, klass, TRUE, context_used);
4151                 if (!alloc)
4152                         return NULL;
4153                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, alloc->dreg, sizeof (MonoObject), val->dreg);
4154                 ins->opcode = OP_STOREV_MEMBASE;
4155
4156                 EMIT_NEW_UNALU (cfg, res, OP_MOVE, dreg, alloc->dreg);
4157                 res->type = STACK_OBJ;
4158                 res->klass = klass;
4159                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
4160                 
4161                 /* Ref case */
4162                 MONO_START_BB (cfg, is_ref_bb);
4163
4164                 /* val is a vtype, so has to load the value manually */
4165                 src_var = get_vreg_to_inst (cfg, val->dreg);
4166                 if (!src_var)
4167                         src_var = mono_compile_create_var_for_vreg (cfg, &klass->byval_arg, OP_LOCAL, val->dreg);
4168                 EMIT_NEW_VARLOADA (cfg, addr, src_var, src_var->inst_vtype);
4169                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, dreg, addr->dreg, 0);
4170                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
4171
4172                 /* Nullable case */
4173                 MONO_START_BB (cfg, is_nullable_bb);
4174
4175                 {
4176                         MonoInst *addr = emit_get_gsharedvt_info_klass (cfg, klass,
4177                                                                                                         MONO_RGCTX_INFO_NULLABLE_CLASS_BOX);
4178                         MonoInst *box_call;
4179                         MonoMethodSignature *box_sig;
4180
4181                         /*
4182                          * klass is Nullable<T>, need to call Nullable<T>.Box () using a gsharedvt signature, but we cannot
4183                          * construct that method at JIT time, so have to do things by hand.
4184                          */
4185                         box_sig = (MonoMethodSignature *)mono_mempool_alloc0 (cfg->mempool, MONO_SIZEOF_METHOD_SIGNATURE + (1 * sizeof (MonoType *)));
4186                         box_sig->ret = &mono_defaults.object_class->byval_arg;
4187                         box_sig->param_count = 1;
4188                         box_sig->params [0] = &klass->byval_arg;
4189
4190                         if (cfg->llvm_only)
4191                                 box_call = emit_llvmonly_calli (cfg, box_sig, &val, addr);
4192                         else
4193                                 box_call = mono_emit_calli (cfg, box_sig, &val, addr, NULL, NULL);
4194                         EMIT_NEW_UNALU (cfg, res, OP_MOVE, dreg, box_call->dreg);
4195                         res->type = STACK_OBJ;
4196                         res->klass = klass;
4197                 }
4198
4199                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
4200
4201                 MONO_START_BB (cfg, end_bb);
4202
4203                 return res;
4204         } else {
4205                 alloc = handle_alloc (cfg, klass, TRUE, context_used);
4206                 if (!alloc)
4207                         return NULL;
4208
4209                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, alloc->dreg, sizeof (MonoObject), val->dreg);
4210                 return alloc;
4211         }
4212 }
4213
4214 static GHashTable* direct_icall_type_hash;
4215
4216 static gboolean
4217 icall_is_direct_callable (MonoCompile *cfg, MonoMethod *cmethod)
4218 {
4219         /* LLVM on amd64 can't handle calls to non-32 bit addresses */
4220         if (!direct_icalls_enabled (cfg))
4221                 return FALSE;
4222
4223         /*
4224          * An icall is directly callable if it doesn't directly or indirectly call mono_raise_exception ().
4225          * Whitelist a few icalls for now.
4226          */
4227         if (!direct_icall_type_hash) {
4228                 GHashTable *h = g_hash_table_new (g_str_hash, g_str_equal);
4229
4230                 g_hash_table_insert (h, (char*)"Decimal", GUINT_TO_POINTER (1));
4231                 g_hash_table_insert (h, (char*)"Number", GUINT_TO_POINTER (1));
4232                 g_hash_table_insert (h, (char*)"Buffer", GUINT_TO_POINTER (1));
4233                 g_hash_table_insert (h, (char*)"Monitor", GUINT_TO_POINTER (1));
4234                 mono_memory_barrier ();
4235                 direct_icall_type_hash = h;
4236         }
4237
4238         if (cmethod->klass == mono_defaults.math_class)
4239                 return TRUE;
4240         /* No locking needed */
4241         if (cmethod->klass->image == mono_defaults.corlib && g_hash_table_lookup (direct_icall_type_hash, cmethod->klass->name))
4242                 return TRUE;
4243         return FALSE;
4244 }
4245
4246 static gboolean
4247 method_needs_stack_walk (MonoCompile *cfg, MonoMethod *cmethod)
4248 {
4249         if (cmethod->klass == mono_defaults.systemtype_class) {
4250                 if (!strcmp (cmethod->name, "GetType"))
4251                         return TRUE;
4252         }
4253         return FALSE;
4254 }
4255
4256 static G_GNUC_UNUSED MonoInst*
4257 handle_enum_has_flag (MonoCompile *cfg, MonoClass *klass, MonoInst *enum_this, MonoInst *enum_flag)
4258 {
4259         MonoType *enum_type = mono_type_get_underlying_type (&klass->byval_arg);
4260         guint32 load_opc = mono_type_to_load_membase (cfg, enum_type);
4261         gboolean is_i4;
4262
4263         switch (enum_type->type) {
4264         case MONO_TYPE_I8:
4265         case MONO_TYPE_U8:
4266 #if SIZEOF_REGISTER == 8
4267         case MONO_TYPE_I:
4268         case MONO_TYPE_U:
4269 #endif
4270                 is_i4 = FALSE;
4271                 break;
4272         default:
4273                 is_i4 = TRUE;
4274                 break;
4275         }
4276
4277         {
4278                 MonoInst *load, *and_, *cmp, *ceq;
4279                 int enum_reg = is_i4 ? alloc_ireg (cfg) : alloc_lreg (cfg);
4280                 int and_reg = is_i4 ? alloc_ireg (cfg) : alloc_lreg (cfg);
4281                 int dest_reg = alloc_ireg (cfg);
4282
4283                 EMIT_NEW_LOAD_MEMBASE (cfg, load, load_opc, enum_reg, enum_this->dreg, 0);
4284                 EMIT_NEW_BIALU (cfg, and_, is_i4 ? OP_IAND : OP_LAND, and_reg, enum_reg, enum_flag->dreg);
4285                 EMIT_NEW_BIALU (cfg, cmp, is_i4 ? OP_ICOMPARE : OP_LCOMPARE, -1, and_reg, enum_flag->dreg);
4286                 EMIT_NEW_UNALU (cfg, ceq, is_i4 ? OP_ICEQ : OP_LCEQ, dest_reg, -1);
4287
4288                 ceq->type = STACK_I4;
4289
4290                 if (!is_i4) {
4291                         load = mono_decompose_opcode (cfg, load);
4292                         and_ = mono_decompose_opcode (cfg, and_);
4293                         cmp = mono_decompose_opcode (cfg, cmp);
4294                         ceq = mono_decompose_opcode (cfg, ceq);
4295                 }
4296
4297                 return ceq;
4298         }
4299 }
4300
4301 /*
4302  * Returns NULL and set the cfg exception on error.
4303  */
4304 static G_GNUC_UNUSED MonoInst*
4305 handle_delegate_ctor (MonoCompile *cfg, MonoClass *klass, MonoInst *target, MonoMethod *method, int context_used, gboolean virtual_)
4306 {
4307         MonoInst *ptr;
4308         int dreg;
4309         gpointer trampoline;
4310         MonoInst *obj, *method_ins, *tramp_ins;
4311         MonoDomain *domain;
4312         guint8 **code_slot;
4313
4314         if (virtual_ && !cfg->llvm_only) {
4315                 MonoMethod *invoke = mono_get_delegate_invoke (klass);
4316                 g_assert (invoke);
4317
4318                 if (!mono_get_delegate_virtual_invoke_impl (mono_method_signature (invoke), context_used ? NULL : method))
4319                         return NULL;
4320         }
4321
4322         obj = handle_alloc (cfg, klass, FALSE, mono_class_check_context_used (klass));
4323         if (!obj)
4324                 return NULL;
4325
4326         /* Inline the contents of mono_delegate_ctor */
4327
4328         /* Set target field */
4329         /* Optimize away setting of NULL target */
4330         if (!MONO_INS_IS_PCONST_NULL (target)) {
4331                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, target), target->dreg);
4332                 if (cfg->gen_write_barriers) {
4333                         dreg = alloc_preg (cfg);
4334                         EMIT_NEW_BIALU_IMM (cfg, ptr, OP_PADD_IMM, dreg, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, target));
4335                         emit_write_barrier (cfg, ptr, target);
4336                 }
4337         }
4338
4339         /* Set method field */
4340         method_ins = emit_get_rgctx_method (cfg, context_used, method, MONO_RGCTX_INFO_METHOD);
4341         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, method), method_ins->dreg);
4342
4343         /* 
4344          * To avoid looking up the compiled code belonging to the target method
4345          * in mono_delegate_trampoline (), we allocate a per-domain memory slot to
4346          * store it, and we fill it after the method has been compiled.
4347          */
4348         if (!method->dynamic && !(cfg->opt & MONO_OPT_SHARED)) {
4349                 MonoInst *code_slot_ins;
4350
4351                 if (context_used) {
4352                         code_slot_ins = emit_get_rgctx_method (cfg, context_used, method, MONO_RGCTX_INFO_METHOD_DELEGATE_CODE);
4353                 } else {
4354                         domain = mono_domain_get ();
4355                         mono_domain_lock (domain);
4356                         if (!domain_jit_info (domain)->method_code_hash)
4357                                 domain_jit_info (domain)->method_code_hash = g_hash_table_new (NULL, NULL);
4358                         code_slot = (guint8 **)g_hash_table_lookup (domain_jit_info (domain)->method_code_hash, method);
4359                         if (!code_slot) {
4360                                 code_slot = (guint8 **)mono_domain_alloc0 (domain, sizeof (gpointer));
4361                                 g_hash_table_insert (domain_jit_info (domain)->method_code_hash, method, code_slot);
4362                         }
4363                         mono_domain_unlock (domain);
4364
4365                         code_slot_ins = emit_runtime_constant (cfg, MONO_PATCH_INFO_METHOD_CODE_SLOT, method);
4366                 }
4367                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, method_code), code_slot_ins->dreg);                
4368         }
4369
4370         if (cfg->llvm_only) {
4371                 MonoInst *args [16];
4372
4373                 if (virtual_) {
4374                         args [0] = obj;
4375                         args [1] = target;
4376                         args [2] = emit_get_rgctx_method (cfg, context_used, method, MONO_RGCTX_INFO_METHOD);
4377                         mono_emit_jit_icall (cfg, mono_llvmonly_init_delegate_virtual, args);
4378                 } else {
4379                         args [0] = obj;
4380                         mono_emit_jit_icall (cfg, mono_llvmonly_init_delegate, args);
4381                 }
4382
4383                 return obj;
4384         }
4385
4386         if (cfg->compile_aot) {
4387                 MonoDelegateClassMethodPair *del_tramp;
4388
4389                 del_tramp = (MonoDelegateClassMethodPair *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoDelegateClassMethodPair));
4390                 del_tramp->klass = klass;
4391                 del_tramp->method = context_used ? NULL : method;
4392                 del_tramp->is_virtual = virtual_;
4393                 EMIT_NEW_AOTCONST (cfg, tramp_ins, MONO_PATCH_INFO_DELEGATE_TRAMPOLINE, del_tramp);
4394         } else {
4395                 if (virtual_)
4396                         trampoline = mono_create_delegate_virtual_trampoline (cfg->domain, klass, context_used ? NULL : method);
4397                 else
4398                         trampoline = mono_create_delegate_trampoline_info (cfg->domain, klass, context_used ? NULL : method);
4399                 EMIT_NEW_PCONST (cfg, tramp_ins, trampoline);
4400         }
4401
4402         /* Set invoke_impl field */
4403         if (virtual_) {
4404                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, invoke_impl), tramp_ins->dreg);
4405         } else {
4406                 dreg = alloc_preg (cfg);
4407                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, dreg, tramp_ins->dreg, MONO_STRUCT_OFFSET (MonoDelegateTrampInfo, invoke_impl));
4408                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, invoke_impl), dreg);
4409
4410                 dreg = alloc_preg (cfg);
4411                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, dreg, tramp_ins->dreg, MONO_STRUCT_OFFSET (MonoDelegateTrampInfo, method_ptr));
4412                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, method_ptr), dreg);
4413         }
4414
4415         dreg = alloc_preg (cfg);
4416         MONO_EMIT_NEW_ICONST (cfg, dreg, virtual_ ? 1 : 0);
4417         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI1_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, method_is_virtual), dreg);
4418
4419         /* All the checks which are in mono_delegate_ctor () are done by the delegate trampoline */
4420
4421         return obj;
4422 }
4423
4424 static MonoInst*
4425 handle_array_new (MonoCompile *cfg, int rank, MonoInst **sp, unsigned char *ip)
4426 {
4427         MonoJitICallInfo *info;
4428
4429         /* Need to register the icall so it gets an icall wrapper */
4430         info = mono_get_array_new_va_icall (rank);
4431
4432         cfg->flags |= MONO_CFG_HAS_VARARGS;
4433
4434         /* mono_array_new_va () needs a vararg calling convention */
4435         cfg->exception_message = g_strdup ("array-new");
4436         cfg->disable_llvm = TRUE;
4437
4438         /* FIXME: This uses info->sig, but it should use the signature of the wrapper */
4439         return mono_emit_native_call (cfg, mono_icall_get_wrapper (info), info->sig, sp);
4440 }
4441
4442 /*
4443  * handle_constrained_gsharedvt_call:
4444  *
4445  *   Handle constrained calls where the receiver is a gsharedvt type.
4446  * Return the instruction representing the call. Set the cfg exception on failure.
4447  */
4448 static MonoInst*
4449 handle_constrained_gsharedvt_call (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **sp, MonoClass *constrained_class,
4450                                                                    gboolean *ref_emit_widen)
4451 {
4452         MonoInst *ins = NULL;
4453         gboolean emit_widen = *ref_emit_widen;
4454
4455         /*
4456          * Constrained calls need to behave differently at runtime dependending on whenever the receiver is instantiated as ref type or as a vtype.
4457          * 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
4458          * pack the arguments into an array, and do the rest of the work in in an icall.
4459          */
4460         if (((cmethod->klass == mono_defaults.object_class) || mono_class_is_interface (cmethod->klass) || (!cmethod->klass->valuetype && cmethod->klass->image != mono_defaults.corlib)) &&
4461                 (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)) &&
4462                 (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]))))) {
4463                 MonoInst *args [16];
4464
4465                 /*
4466                  * This case handles calls to
4467                  * - object:ToString()/Equals()/GetHashCode(),
4468                  * - System.IComparable<T>:CompareTo()
4469                  * - System.IEquatable<T>:Equals ()
4470                  * plus some simple interface calls enough to support AsyncTaskMethodBuilder.
4471                  */
4472
4473                 args [0] = sp [0];
4474                 if (mono_method_check_context_used (cmethod))
4475                         args [1] = emit_get_rgctx_method (cfg, mono_method_check_context_used (cmethod), cmethod, MONO_RGCTX_INFO_METHOD);
4476                 else
4477                         EMIT_NEW_METHODCONST (cfg, args [1], cmethod);
4478                 args [2] = mini_emit_get_rgctx_klass (cfg, mono_class_check_context_used (constrained_class), constrained_class, MONO_RGCTX_INFO_KLASS);
4479
4480                 /* !fsig->hasthis is for the wrapper for the Object.GetType () icall */
4481                 if (fsig->hasthis && fsig->param_count) {
4482                         /* Pass the arguments using a localloc-ed array using the format expected by runtime_invoke () */
4483                         MONO_INST_NEW (cfg, ins, OP_LOCALLOC_IMM);
4484                         ins->dreg = alloc_preg (cfg);
4485                         ins->inst_imm = fsig->param_count * sizeof (mgreg_t);
4486                         MONO_ADD_INS (cfg->cbb, ins);
4487                         args [4] = ins;
4488
4489                         if (mini_is_gsharedvt_type (fsig->params [0])) {
4490                                 int addr_reg, deref_arg_reg;
4491
4492                                 ins = emit_get_gsharedvt_info_klass (cfg, mono_class_from_mono_type (fsig->params [0]), MONO_RGCTX_INFO_CLASS_BOX_TYPE);
4493                                 deref_arg_reg = alloc_preg (cfg);
4494                                 /* deref_arg = BOX_TYPE != MONO_GSHAREDVT_BOX_TYPE_VTYPE */
4495                                 EMIT_NEW_BIALU_IMM (cfg, args [3], OP_ISUB_IMM, deref_arg_reg, ins->dreg, 1);
4496
4497                                 EMIT_NEW_VARLOADA_VREG (cfg, ins, sp [1]->dreg, fsig->params [0]);
4498                                 addr_reg = ins->dreg;
4499                                 EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STORE_MEMBASE_REG, args [4]->dreg, 0, addr_reg);
4500                         } else {
4501                                 EMIT_NEW_ICONST (cfg, args [3], 0);
4502                                 EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STORE_MEMBASE_REG, args [4]->dreg, 0, sp [1]->dreg);
4503                         }
4504                 } else {
4505                         EMIT_NEW_ICONST (cfg, args [3], 0);
4506                         EMIT_NEW_ICONST (cfg, args [4], 0);
4507                 }
4508                 ins = mono_emit_jit_icall (cfg, mono_gsharedvt_constrained_call, args);
4509                 emit_widen = FALSE;
4510
4511                 if (mini_is_gsharedvt_type (fsig->ret)) {
4512                         ins = handle_unbox_gsharedvt (cfg, mono_class_from_mono_type (fsig->ret), ins);
4513                 } else if (MONO_TYPE_IS_PRIMITIVE (fsig->ret) || MONO_TYPE_ISSTRUCT (fsig->ret) || mono_class_is_enum (mono_class_from_mono_type (fsig->ret))) {
4514                         MonoInst *add;
4515
4516                         /* Unbox */
4517                         NEW_BIALU_IMM (cfg, add, OP_ADD_IMM, alloc_dreg (cfg, STACK_MP), ins->dreg, sizeof (MonoObject));
4518                         MONO_ADD_INS (cfg->cbb, add);
4519                         /* Load value */
4520                         NEW_LOAD_MEMBASE_TYPE (cfg, ins, fsig->ret, add->dreg, 0);
4521                         MONO_ADD_INS (cfg->cbb, ins);
4522                         /* ins represents the call result */
4523                 }
4524         } else {
4525                 GSHAREDVT_FAILURE (CEE_CALLVIRT);
4526         }
4527
4528         *ref_emit_widen = emit_widen;
4529
4530         return ins;
4531
4532  exception_exit:
4533         return NULL;
4534 }
4535
4536 static void
4537 mono_emit_load_got_addr (MonoCompile *cfg)
4538 {
4539         MonoInst *getaddr, *dummy_use;
4540
4541         if (!cfg->got_var || cfg->got_var_allocated)
4542                 return;
4543
4544         MONO_INST_NEW (cfg, getaddr, OP_LOAD_GOTADDR);
4545         getaddr->cil_code = cfg->header->code;
4546         getaddr->dreg = cfg->got_var->dreg;
4547
4548         /* Add it to the start of the first bblock */
4549         if (cfg->bb_entry->code) {
4550                 getaddr->next = cfg->bb_entry->code;
4551                 cfg->bb_entry->code = getaddr;
4552         }
4553         else
4554                 MONO_ADD_INS (cfg->bb_entry, getaddr);
4555
4556         cfg->got_var_allocated = TRUE;
4557
4558         /* 
4559          * Add a dummy use to keep the got_var alive, since real uses might
4560          * only be generated by the back ends.
4561          * Add it to end_bblock, so the variable's lifetime covers the whole
4562          * method.
4563          * It would be better to make the usage of the got var explicit in all
4564          * cases when the backend needs it (i.e. calls, throw etc.), so this
4565          * wouldn't be needed.
4566          */
4567         NEW_DUMMY_USE (cfg, dummy_use, cfg->got_var);
4568         MONO_ADD_INS (cfg->bb_exit, dummy_use);
4569 }
4570
4571 static int inline_limit;
4572 static gboolean inline_limit_inited;
4573
4574 static gboolean
4575 mono_method_check_inlining (MonoCompile *cfg, MonoMethod *method)
4576 {
4577         MonoMethodHeaderSummary header;
4578         MonoVTable *vtable;
4579 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
4580         MonoMethodSignature *sig = mono_method_signature (method);
4581         int i;
4582 #endif
4583
4584         if (cfg->disable_inline)
4585                 return FALSE;
4586         if (cfg->gsharedvt)
4587                 return FALSE;
4588
4589         if (cfg->inline_depth > 10)
4590                 return FALSE;
4591
4592         if (!mono_method_get_header_summary (method, &header))
4593                 return FALSE;
4594
4595         /*runtime, icall and pinvoke are checked by summary call*/
4596         if ((method->iflags & METHOD_IMPL_ATTRIBUTE_NOINLINING) ||
4597             (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) ||
4598             (mono_class_is_marshalbyref (method->klass)) ||
4599             header.has_clauses)
4600                 return FALSE;
4601
4602         /* also consider num_locals? */
4603         /* Do the size check early to avoid creating vtables */
4604         if (!inline_limit_inited) {
4605                 char *inlinelimit;
4606                 if ((inlinelimit = g_getenv ("MONO_INLINELIMIT"))) {
4607                         inline_limit = atoi (inlinelimit);
4608                         g_free (inlinelimit);
4609                 } else
4610                         inline_limit = INLINE_LENGTH_LIMIT;
4611                 inline_limit_inited = TRUE;
4612         }
4613         if (header.code_size >= inline_limit && !(method->iflags & METHOD_IMPL_ATTRIBUTE_AGGRESSIVE_INLINING))
4614                 return FALSE;
4615
4616         /*
4617          * if we can initialize the class of the method right away, we do,
4618          * otherwise we don't allow inlining if the class needs initialization,
4619          * since it would mean inserting a call to mono_runtime_class_init()
4620          * inside the inlined code
4621          */
4622         if (cfg->gshared && method->klass->has_cctor && mini_class_check_context_used (cfg, method->klass))
4623                 return FALSE;
4624
4625         if (!(cfg->opt & MONO_OPT_SHARED)) {
4626                 /* The AggressiveInlining hint is a good excuse to force that cctor to run. */
4627                 if (method->iflags & METHOD_IMPL_ATTRIBUTE_AGGRESSIVE_INLINING) {
4628                         if (method->klass->has_cctor) {
4629                                 vtable = mono_class_vtable (cfg->domain, method->klass);
4630                                 if (!vtable)
4631                                         return FALSE;
4632                                 if (!cfg->compile_aot) {
4633                                         MonoError error;
4634                                         if (!mono_runtime_class_init_full (vtable, &error)) {
4635                                                 mono_error_cleanup (&error);
4636                                                 return FALSE;
4637                                         }
4638                                 }
4639                         }
4640                 } else if (mono_class_is_before_field_init (method->klass)) {
4641                         if (cfg->run_cctors && method->klass->has_cctor) {
4642                                 /*FIXME it would easier and lazier to just use mono_class_try_get_vtable */
4643                                 if (!method->klass->runtime_info)
4644                                         /* No vtable created yet */
4645                                         return FALSE;
4646                                 vtable = mono_class_vtable (cfg->domain, method->klass);
4647                                 if (!vtable)
4648                                         return FALSE;
4649                                 /* This makes so that inline cannot trigger */
4650                                 /* .cctors: too many apps depend on them */
4651                                 /* running with a specific order... */
4652                                 if (! vtable->initialized)
4653                                         return FALSE;
4654                                 MonoError error;
4655                                 if (!mono_runtime_class_init_full (vtable, &error)) {
4656                                         mono_error_cleanup (&error);
4657                                         return FALSE;
4658                                 }
4659                         }
4660                 } else if (mono_class_needs_cctor_run (method->klass, NULL)) {
4661                         if (!method->klass->runtime_info)
4662                                 /* No vtable created yet */
4663                                 return FALSE;
4664                         vtable = mono_class_vtable (cfg->domain, method->klass);
4665                         if (!vtable)
4666                                 return FALSE;
4667                         if (!vtable->initialized)
4668                                 return FALSE;
4669                 }
4670         } else {
4671                 /* 
4672                  * If we're compiling for shared code
4673                  * the cctor will need to be run at aot method load time, for example,
4674                  * or at the end of the compilation of the inlining method.
4675                  */
4676                 if (mono_class_needs_cctor_run (method->klass, NULL) && !mono_class_is_before_field_init (method->klass))
4677                         return FALSE;
4678         }
4679
4680 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
4681         if (mono_arch_is_soft_float ()) {
4682                 /* FIXME: */
4683                 if (sig->ret && sig->ret->type == MONO_TYPE_R4)
4684                         return FALSE;
4685                 for (i = 0; i < sig->param_count; ++i)
4686                         if (!sig->params [i]->byref && sig->params [i]->type == MONO_TYPE_R4)
4687                                 return FALSE;
4688         }
4689 #endif
4690
4691         if (g_list_find (cfg->dont_inline, method))
4692                 return FALSE;
4693
4694         return TRUE;
4695 }
4696
4697 static gboolean
4698 mini_field_access_needs_cctor_run (MonoCompile *cfg, MonoMethod *method, MonoClass *klass, MonoVTable *vtable)
4699 {
4700         if (!cfg->compile_aot) {
4701                 g_assert (vtable);
4702                 if (vtable->initialized)
4703                         return FALSE;
4704         }
4705
4706         if (mono_class_is_before_field_init (klass)) {
4707                 if (cfg->method == method)
4708                         return FALSE;
4709         }
4710
4711         if (!mono_class_needs_cctor_run (klass, method))
4712                 return FALSE;
4713
4714         if (! (method->flags & METHOD_ATTRIBUTE_STATIC) && (klass == method->klass))
4715                 /* The initialization is already done before the method is called */
4716                 return FALSE;
4717
4718         return TRUE;
4719 }
4720
4721 MonoInst*
4722 mini_emit_ldelema_1_ins (MonoCompile *cfg, MonoClass *klass, MonoInst *arr, MonoInst *index, gboolean bcheck)
4723 {
4724         MonoInst *ins;
4725         guint32 size;
4726         int mult_reg, add_reg, array_reg, index_reg, index2_reg;
4727         int context_used;
4728
4729         if (mini_is_gsharedvt_variable_klass (klass)) {
4730                 size = -1;
4731         } else {
4732                 mono_class_init (klass);
4733                 size = mono_class_array_element_size (klass);
4734         }
4735
4736         mult_reg = alloc_preg (cfg);
4737         array_reg = arr->dreg;
4738         index_reg = index->dreg;
4739
4740 #if SIZEOF_REGISTER == 8
4741         /* The array reg is 64 bits but the index reg is only 32 */
4742         if (COMPILE_LLVM (cfg)) {
4743                 /*
4744                  * abcrem can't handle the OP_SEXT_I4, so add this after abcrem,
4745                  * during OP_BOUNDS_CHECK decomposition, and in the implementation
4746                  * of OP_X86_LEA for llvm.
4747                  */
4748                 index2_reg = index_reg;
4749         } else {
4750                 index2_reg = alloc_preg (cfg);
4751                 MONO_EMIT_NEW_UNALU (cfg, OP_SEXT_I4, index2_reg, index_reg);
4752         }
4753 #else
4754         if (index->type == STACK_I8) {
4755                 index2_reg = alloc_preg (cfg);
4756                 MONO_EMIT_NEW_UNALU (cfg, OP_LCONV_TO_I4, index2_reg, index_reg);
4757         } else {
4758                 index2_reg = index_reg;
4759         }
4760 #endif
4761
4762         if (bcheck)
4763                 MONO_EMIT_BOUNDS_CHECK (cfg, array_reg, MonoArray, max_length, index2_reg);
4764
4765 #if defined(TARGET_X86) || defined(TARGET_AMD64)
4766         if (size == 1 || size == 2 || size == 4 || size == 8) {
4767                 static const int fast_log2 [] = { 1, 0, 1, -1, 2, -1, -1, -1, 3 };
4768
4769                 EMIT_NEW_X86_LEA (cfg, ins, array_reg, index2_reg, fast_log2 [size], MONO_STRUCT_OFFSET (MonoArray, vector));
4770                 ins->klass = mono_class_get_element_class (klass);
4771                 ins->type = STACK_MP;
4772
4773                 return ins;
4774         }
4775 #endif          
4776
4777         add_reg = alloc_ireg_mp (cfg);
4778
4779         if (size == -1) {
4780                 MonoInst *rgctx_ins;
4781
4782                 /* gsharedvt */
4783                 g_assert (cfg->gshared);
4784                 context_used = mini_class_check_context_used (cfg, klass);
4785                 g_assert (context_used);
4786                 rgctx_ins = emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_ARRAY_ELEMENT_SIZE);
4787                 MONO_EMIT_NEW_BIALU (cfg, OP_IMUL, mult_reg, index2_reg, rgctx_ins->dreg);
4788         } else {
4789                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_MUL_IMM, mult_reg, index2_reg, size);
4790         }
4791         MONO_EMIT_NEW_BIALU (cfg, OP_PADD, add_reg, array_reg, mult_reg);
4792         NEW_BIALU_IMM (cfg, ins, OP_PADD_IMM, add_reg, add_reg, MONO_STRUCT_OFFSET (MonoArray, vector));
4793         ins->klass = mono_class_get_element_class (klass);
4794         ins->type = STACK_MP;
4795         MONO_ADD_INS (cfg->cbb, ins);
4796
4797         return ins;
4798 }
4799
4800 static MonoInst*
4801 mini_emit_ldelema_2_ins (MonoCompile *cfg, MonoClass *klass, MonoInst *arr, MonoInst *index_ins1, MonoInst *index_ins2)
4802 {
4803         int bounds_reg = alloc_preg (cfg);
4804         int add_reg = alloc_ireg_mp (cfg);
4805         int mult_reg = alloc_preg (cfg);
4806         int mult2_reg = alloc_preg (cfg);
4807         int low1_reg = alloc_preg (cfg);
4808         int low2_reg = alloc_preg (cfg);
4809         int high1_reg = alloc_preg (cfg);
4810         int high2_reg = alloc_preg (cfg);
4811         int realidx1_reg = alloc_preg (cfg);
4812         int realidx2_reg = alloc_preg (cfg);
4813         int sum_reg = alloc_preg (cfg);
4814         int index1, index2, tmpreg;
4815         MonoInst *ins;
4816         guint32 size;
4817
4818         mono_class_init (klass);
4819         size = mono_class_array_element_size (klass);
4820
4821         index1 = index_ins1->dreg;
4822         index2 = index_ins2->dreg;
4823
4824 #if SIZEOF_REGISTER == 8
4825         /* The array reg is 64 bits but the index reg is only 32 */
4826         if (COMPILE_LLVM (cfg)) {
4827                 /* Not needed */
4828         } else {
4829                 tmpreg = alloc_preg (cfg);
4830                 MONO_EMIT_NEW_UNALU (cfg, OP_SEXT_I4, tmpreg, index1);
4831                 index1 = tmpreg;
4832                 tmpreg = alloc_preg (cfg);
4833                 MONO_EMIT_NEW_UNALU (cfg, OP_SEXT_I4, tmpreg, index2);
4834                 index2 = tmpreg;
4835         }
4836 #else
4837         // FIXME: Do we need to do something here for i8 indexes, like in ldelema_1_ins ?
4838         tmpreg = -1;
4839 #endif
4840
4841         /* range checking */
4842         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, bounds_reg, 
4843                                        arr->dreg, MONO_STRUCT_OFFSET (MonoArray, bounds));
4844
4845         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, low1_reg, 
4846                                        bounds_reg, MONO_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
4847         MONO_EMIT_NEW_BIALU (cfg, OP_PSUB, realidx1_reg, index1, low1_reg);
4848         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, high1_reg, 
4849                                        bounds_reg, MONO_STRUCT_OFFSET (MonoArrayBounds, length));
4850         MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, high1_reg, realidx1_reg);
4851         MONO_EMIT_NEW_COND_EXC (cfg, LE_UN, "IndexOutOfRangeException");
4852
4853         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, low2_reg, 
4854                                        bounds_reg, sizeof (MonoArrayBounds) + MONO_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
4855         MONO_EMIT_NEW_BIALU (cfg, OP_PSUB, realidx2_reg, index2, low2_reg);
4856         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, high2_reg, 
4857                                        bounds_reg, sizeof (MonoArrayBounds) + MONO_STRUCT_OFFSET (MonoArrayBounds, length));
4858         MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, high2_reg, realidx2_reg);
4859         MONO_EMIT_NEW_COND_EXC (cfg, LE_UN, "IndexOutOfRangeException");
4860
4861         MONO_EMIT_NEW_BIALU (cfg, OP_PMUL, mult_reg, high2_reg, realidx1_reg);
4862         MONO_EMIT_NEW_BIALU (cfg, OP_PADD, sum_reg, mult_reg, realidx2_reg);
4863         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PMUL_IMM, mult2_reg, sum_reg, size);
4864         MONO_EMIT_NEW_BIALU (cfg, OP_PADD, add_reg, mult2_reg, arr->dreg);
4865         NEW_BIALU_IMM (cfg, ins, OP_PADD_IMM, add_reg, add_reg, MONO_STRUCT_OFFSET (MonoArray, vector));
4866
4867         ins->type = STACK_MP;
4868         ins->klass = klass;
4869         MONO_ADD_INS (cfg->cbb, ins);
4870
4871         return ins;
4872 }
4873
4874 static MonoInst*
4875 mini_emit_ldelema_ins (MonoCompile *cfg, MonoMethod *cmethod, MonoInst **sp, unsigned char *ip, gboolean is_set)
4876 {
4877         int rank;
4878         MonoInst *addr;
4879         MonoMethod *addr_method;
4880         int element_size;
4881         MonoClass *eclass = cmethod->klass->element_class;
4882
4883         rank = mono_method_signature (cmethod)->param_count - (is_set? 1: 0);
4884
4885         if (rank == 1)
4886                 return mini_emit_ldelema_1_ins (cfg, eclass, sp [0], sp [1], TRUE);
4887
4888         /* emit_ldelema_2 depends on OP_LMUL */
4889         if (!cfg->backend->emulate_mul_div && rank == 2 && (cfg->opt & MONO_OPT_INTRINS) && !mini_is_gsharedvt_variable_klass (eclass)) {
4890                 return mini_emit_ldelema_2_ins (cfg, eclass, sp [0], sp [1], sp [2]);
4891         }
4892
4893         if (mini_is_gsharedvt_variable_klass (eclass))
4894                 element_size = 0;
4895         else
4896                 element_size = mono_class_array_element_size (eclass);
4897         addr_method = mono_marshal_get_array_address (rank, element_size);
4898         addr = mono_emit_method_call (cfg, addr_method, sp, NULL);
4899
4900         return addr;
4901 }
4902
4903 static MonoBreakPolicy
4904 always_insert_breakpoint (MonoMethod *method)
4905 {
4906         return MONO_BREAK_POLICY_ALWAYS;
4907 }
4908
4909 static MonoBreakPolicyFunc break_policy_func = always_insert_breakpoint;
4910
4911 /**
4912  * mono_set_break_policy:
4913  * \param policy_callback the new callback function
4914  *
4915  * Allow embedders to decide wherther to actually obey breakpoint instructions
4916  * (both break IL instructions and \c Debugger.Break method calls), for example
4917  * to not allow an app to be aborted by a perfectly valid IL opcode when executing
4918  * untrusted or semi-trusted code.
4919  *
4920  * \p policy_callback will be called every time a break point instruction needs to
4921  * be inserted with the method argument being the method that calls \c Debugger.Break
4922  * or has the IL \c break instruction. The callback should return \c MONO_BREAK_POLICY_NEVER
4923  * if it wants the breakpoint to not be effective in the given method.
4924  * \c MONO_BREAK_POLICY_ALWAYS is the default.
4925  */
4926 void
4927 mono_set_break_policy (MonoBreakPolicyFunc policy_callback)
4928 {
4929         if (policy_callback)
4930                 break_policy_func = policy_callback;
4931         else
4932                 break_policy_func = always_insert_breakpoint;
4933 }
4934
4935 static gboolean
4936 should_insert_brekpoint (MonoMethod *method) {
4937         switch (break_policy_func (method)) {
4938         case MONO_BREAK_POLICY_ALWAYS:
4939                 return TRUE;
4940         case MONO_BREAK_POLICY_NEVER:
4941                 return FALSE;
4942         case MONO_BREAK_POLICY_ON_DBG:
4943                 g_warning ("mdb no longer supported");
4944                 return FALSE;
4945         default:
4946                 g_warning ("Incorrect value returned from break policy callback");
4947                 return FALSE;
4948         }
4949 }
4950
4951 /* optimize the simple GetGenericValueImpl/SetGenericValueImpl generic icalls */
4952 static MonoInst*
4953 emit_array_generic_access (MonoCompile *cfg, MonoMethodSignature *fsig, MonoInst **args, int is_set)
4954 {
4955         MonoInst *addr, *store, *load;
4956         MonoClass *eklass = mono_class_from_mono_type (fsig->params [2]);
4957
4958         /* the bounds check is already done by the callers */
4959         addr = mini_emit_ldelema_1_ins (cfg, eklass, args [0], args [1], FALSE);
4960         if (is_set) {
4961                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, load, &eklass->byval_arg, args [2]->dreg, 0);
4962                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, store, &eklass->byval_arg, addr->dreg, 0, load->dreg);
4963                 if (mini_type_is_reference (&eklass->byval_arg))
4964                         emit_write_barrier (cfg, addr, load);
4965         } else {
4966                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, load, &eklass->byval_arg, addr->dreg, 0);
4967                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, store, &eklass->byval_arg, args [2]->dreg, 0, load->dreg);
4968         }
4969         return store;
4970 }
4971
4972
4973 static gboolean
4974 generic_class_is_reference_type (MonoCompile *cfg, MonoClass *klass)
4975 {
4976         return mini_type_is_reference (&klass->byval_arg);
4977 }
4978
4979 static MonoInst*
4980 emit_array_store (MonoCompile *cfg, MonoClass *klass, MonoInst **sp, gboolean safety_checks)
4981 {
4982         if (safety_checks && generic_class_is_reference_type (cfg, klass) &&
4983                 !(MONO_INS_IS_PCONST_NULL (sp [2]))) {
4984                 MonoClass *obj_array = mono_array_class_get_cached (mono_defaults.object_class, 1);
4985                 MonoMethod *helper = mono_marshal_get_virtual_stelemref (obj_array);
4986                 MonoInst *iargs [3];
4987
4988                 if (!helper->slot)
4989                         mono_class_setup_vtable (obj_array);
4990                 g_assert (helper->slot);
4991
4992                 if (sp [0]->type != STACK_OBJ)
4993                         return NULL;
4994                 if (sp [2]->type != STACK_OBJ)
4995                         return NULL;
4996
4997                 iargs [2] = sp [2];
4998                 iargs [1] = sp [1];
4999                 iargs [0] = sp [0];
5000
5001                 return mono_emit_method_call (cfg, helper, iargs, sp [0]);
5002         } else {
5003                 MonoInst *ins;
5004
5005                 if (mini_is_gsharedvt_variable_klass (klass)) {
5006                         MonoInst *addr;
5007
5008                         // FIXME-VT: OP_ICONST optimization
5009                         addr = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1], TRUE);
5010                         EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr->dreg, 0, sp [2]->dreg);
5011                         ins->opcode = OP_STOREV_MEMBASE;
5012                 } else if (sp [1]->opcode == OP_ICONST) {
5013                         int array_reg = sp [0]->dreg;
5014                         int index_reg = sp [1]->dreg;
5015                         int offset = (mono_class_array_element_size (klass) * sp [1]->inst_c0) + MONO_STRUCT_OFFSET (MonoArray, vector);
5016
5017                         if (SIZEOF_REGISTER == 8 && COMPILE_LLVM (cfg))
5018                                 MONO_EMIT_NEW_UNALU (cfg, OP_ZEXT_I4, index_reg, index_reg);
5019
5020                         if (safety_checks)
5021                                 MONO_EMIT_BOUNDS_CHECK (cfg, array_reg, MonoArray, max_length, index_reg);
5022                         EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, array_reg, offset, sp [2]->dreg);
5023                 } else {
5024                         MonoInst *addr = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1], safety_checks);
5025                         EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr->dreg, 0, sp [2]->dreg);
5026                         if (generic_class_is_reference_type (cfg, klass))
5027                                 emit_write_barrier (cfg, addr, sp [2]);
5028                 }
5029                 return ins;
5030         }
5031 }
5032
5033 static MonoInst*
5034 emit_array_unsafe_access (MonoCompile *cfg, MonoMethodSignature *fsig, MonoInst **args, int is_set)
5035 {
5036         MonoClass *eklass;
5037         
5038         if (is_set)
5039                 eklass = mono_class_from_mono_type (fsig->params [2]);
5040         else
5041                 eklass = mono_class_from_mono_type (fsig->ret);
5042
5043         if (is_set) {
5044                 return emit_array_store (cfg, eklass, args, FALSE);
5045         } else {
5046                 MonoInst *ins, *addr = mini_emit_ldelema_1_ins (cfg, eklass, args [0], args [1], FALSE);
5047                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &eklass->byval_arg, addr->dreg, 0);
5048                 return ins;
5049         }
5050 }
5051
5052 static gboolean
5053 is_unsafe_mov_compatible (MonoCompile *cfg, MonoClass *param_klass, MonoClass *return_klass)
5054 {
5055         uint32_t align;
5056         int param_size, return_size;
5057
5058         param_klass = mono_class_from_mono_type (mini_get_underlying_type (&param_klass->byval_arg));
5059         return_klass = mono_class_from_mono_type (mini_get_underlying_type (&return_klass->byval_arg));
5060
5061         if (cfg->verbose_level > 3)
5062                 printf ("[UNSAFE-MOV-INTRISIC] %s <- %s\n", return_klass->name, param_klass->name);
5063
5064         //Don't allow mixing reference types with value types
5065         if (param_klass->valuetype != return_klass->valuetype) {
5066                 if (cfg->verbose_level > 3)
5067                         printf ("[UNSAFE-MOV-INTRISIC]\tone of the args is a valuetype and the other is not\n");
5068                 return FALSE;
5069         }
5070
5071         if (!param_klass->valuetype) {
5072                 if (cfg->verbose_level > 3)
5073                         printf ("[UNSAFE-MOV-INTRISIC]\targs are reference types\n");
5074                 return TRUE;
5075         }
5076
5077         //That are blitable
5078         if (param_klass->has_references || return_klass->has_references)
5079                 return FALSE;
5080
5081         /* Avoid mixing structs and primitive types/enums, they need to be handled differently in the JIT */
5082         if ((MONO_TYPE_ISSTRUCT (&param_klass->byval_arg) && !MONO_TYPE_ISSTRUCT (&return_klass->byval_arg)) ||
5083                 (!MONO_TYPE_ISSTRUCT (&param_klass->byval_arg) && MONO_TYPE_ISSTRUCT (&return_klass->byval_arg))) {
5084                         if (cfg->verbose_level > 3)
5085                                 printf ("[UNSAFE-MOV-INTRISIC]\tmixing structs and scalars\n");
5086                 return FALSE;
5087         }
5088
5089         if (param_klass->byval_arg.type == MONO_TYPE_R4 || param_klass->byval_arg.type == MONO_TYPE_R8 ||
5090                 return_klass->byval_arg.type == MONO_TYPE_R4 || return_klass->byval_arg.type == MONO_TYPE_R8) {
5091                 if (cfg->verbose_level > 3)
5092                         printf ("[UNSAFE-MOV-INTRISIC]\tfloat or double are not supported\n");
5093                 return FALSE;
5094         }
5095
5096         param_size = mono_class_value_size (param_klass, &align);
5097         return_size = mono_class_value_size (return_klass, &align);
5098
5099         //We can do it if sizes match
5100         if (param_size == return_size) {
5101                 if (cfg->verbose_level > 3)
5102                         printf ("[UNSAFE-MOV-INTRISIC]\tsame size\n");
5103                 return TRUE;
5104         }
5105
5106         //No simple way to handle struct if sizes don't match
5107         if (MONO_TYPE_ISSTRUCT (&param_klass->byval_arg)) {
5108                 if (cfg->verbose_level > 3)
5109                         printf ("[UNSAFE-MOV-INTRISIC]\tsize mismatch and type is a struct\n");
5110                 return FALSE;
5111         }
5112
5113         /*
5114          * Same reg size category.
5115          * A quick note on why we don't require widening here.
5116          * The intrinsic is "R Array.UnsafeMov<S,R> (S s)".
5117          *
5118          * Since the source value comes from a function argument, the JIT will already have
5119          * the value in a VREG and performed any widening needed before (say, when loading from a field).
5120          */
5121         if (param_size <= 4 && return_size <= 4) {
5122                 if (cfg->verbose_level > 3)
5123                         printf ("[UNSAFE-MOV-INTRISIC]\tsize mismatch but both are of the same reg class\n");
5124                 return TRUE;
5125         }
5126
5127         return FALSE;
5128 }
5129
5130 static MonoInst*
5131 emit_array_unsafe_mov (MonoCompile *cfg, MonoMethodSignature *fsig, MonoInst **args)
5132 {
5133         MonoClass *param_klass = mono_class_from_mono_type (fsig->params [0]);
5134         MonoClass *return_klass = mono_class_from_mono_type (fsig->ret);
5135
5136         if (mini_is_gsharedvt_variable_type (fsig->ret))
5137                 return NULL;
5138
5139         //Valuetypes that are semantically equivalent or numbers than can be widened to
5140         if (is_unsafe_mov_compatible (cfg, param_klass, return_klass))
5141                 return args [0];
5142
5143         //Arrays of valuetypes that are semantically equivalent
5144         if (param_klass->rank == 1 && return_klass->rank == 1 && is_unsafe_mov_compatible (cfg, param_klass->element_class, return_klass->element_class))
5145                 return args [0];
5146
5147         return NULL;
5148 }
5149
5150 static MonoInst*
5151 mini_emit_inst_for_ctor (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
5152 {
5153 #ifdef MONO_ARCH_SIMD_INTRINSICS
5154         MonoInst *ins = NULL;
5155
5156         if (cfg->opt & MONO_OPT_SIMD) {
5157                 ins = mono_emit_simd_intrinsics (cfg, cmethod, fsig, args);
5158                 if (ins)
5159                         return ins;
5160         }
5161 #endif
5162
5163         return mono_emit_native_types_intrinsics (cfg, cmethod, fsig, args);
5164 }
5165
5166 static MonoInst*
5167 emit_memory_barrier (MonoCompile *cfg, int kind)
5168 {
5169         MonoInst *ins = NULL;
5170         MONO_INST_NEW (cfg, ins, OP_MEMORY_BARRIER);
5171         MONO_ADD_INS (cfg->cbb, ins);
5172         ins->backend.memory_barrier_kind = kind;
5173
5174         return ins;
5175 }
5176
5177 static MonoInst*
5178 llvm_emit_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
5179 {
5180         MonoInst *ins = NULL;
5181         int opcode = 0;
5182
5183         /* The LLVM backend supports these intrinsics */
5184         if (cmethod->klass == mono_defaults.math_class) {
5185                 if (strcmp (cmethod->name, "Sin") == 0) {
5186                         opcode = OP_SIN;
5187                 } else if (strcmp (cmethod->name, "Cos") == 0) {
5188                         opcode = OP_COS;
5189                 } else if (strcmp (cmethod->name, "Sqrt") == 0) {
5190                         opcode = OP_SQRT;
5191                 } else if (strcmp (cmethod->name, "Abs") == 0 && fsig->params [0]->type == MONO_TYPE_R8) {
5192                         opcode = OP_ABS;
5193                 }
5194
5195                 if (opcode && fsig->param_count == 1) {
5196                         MONO_INST_NEW (cfg, ins, opcode);
5197                         ins->type = STACK_R8;
5198                         ins->dreg = mono_alloc_dreg (cfg, ins->type);
5199                         ins->sreg1 = args [0]->dreg;
5200                         MONO_ADD_INS (cfg->cbb, ins);
5201                 }
5202
5203                 opcode = 0;
5204                 if (cfg->opt & MONO_OPT_CMOV) {
5205                         if (strcmp (cmethod->name, "Min") == 0) {
5206                                 if (fsig->params [0]->type == MONO_TYPE_I4)
5207                                         opcode = OP_IMIN;
5208                                 if (fsig->params [0]->type == MONO_TYPE_U4)
5209                                         opcode = OP_IMIN_UN;
5210                                 else if (fsig->params [0]->type == MONO_TYPE_I8)
5211                                         opcode = OP_LMIN;
5212                                 else if (fsig->params [0]->type == MONO_TYPE_U8)
5213                                         opcode = OP_LMIN_UN;
5214                         } else if (strcmp (cmethod->name, "Max") == 0) {
5215                                 if (fsig->params [0]->type == MONO_TYPE_I4)
5216                                         opcode = OP_IMAX;
5217                                 if (fsig->params [0]->type == MONO_TYPE_U4)
5218                                         opcode = OP_IMAX_UN;
5219                                 else if (fsig->params [0]->type == MONO_TYPE_I8)
5220                                         opcode = OP_LMAX;
5221                                 else if (fsig->params [0]->type == MONO_TYPE_U8)
5222                                         opcode = OP_LMAX_UN;
5223                         }
5224                 }
5225
5226                 if (opcode && fsig->param_count == 2) {
5227                         MONO_INST_NEW (cfg, ins, opcode);
5228                         ins->type = fsig->params [0]->type == MONO_TYPE_I4 ? STACK_I4 : STACK_I8;
5229                         ins->dreg = mono_alloc_dreg (cfg, ins->type);
5230                         ins->sreg1 = args [0]->dreg;
5231                         ins->sreg2 = args [1]->dreg;
5232                         MONO_ADD_INS (cfg->cbb, ins);
5233                 }
5234         }
5235
5236         return ins;
5237 }
5238
5239 static MonoInst*
5240 mini_emit_inst_for_sharable_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
5241 {
5242         if (cmethod->klass == mono_defaults.array_class) {
5243                 if (strcmp (cmethod->name, "UnsafeStore") == 0)
5244                         return emit_array_unsafe_access (cfg, fsig, args, TRUE);
5245                 else if (strcmp (cmethod->name, "UnsafeLoad") == 0)
5246                         return emit_array_unsafe_access (cfg, fsig, args, FALSE);
5247                 else if (strcmp (cmethod->name, "UnsafeMov") == 0)
5248                         return emit_array_unsafe_mov (cfg, fsig, args);
5249         }
5250
5251         return NULL;
5252 }
5253
5254 static MonoInst*
5255 mini_emit_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
5256 {
5257         MonoInst *ins = NULL;
5258         MonoClass *runtime_helpers_class = mono_class_get_runtime_helpers_class ();
5259
5260         if (cmethod->klass == mono_defaults.string_class) {
5261                 if (strcmp (cmethod->name, "get_Chars") == 0 && fsig->param_count + fsig->hasthis == 2) {
5262                         int dreg = alloc_ireg (cfg);
5263                         int index_reg = alloc_preg (cfg);
5264                         int add_reg = alloc_preg (cfg);
5265
5266 #if SIZEOF_REGISTER == 8
5267                         if (COMPILE_LLVM (cfg)) {
5268                                 MONO_EMIT_NEW_UNALU (cfg, OP_ZEXT_I4, index_reg, args [1]->dreg);
5269                         } else {
5270                                 /* The array reg is 64 bits but the index reg is only 32 */
5271                                 MONO_EMIT_NEW_UNALU (cfg, OP_SEXT_I4, index_reg, args [1]->dreg);
5272                         }
5273 #else
5274                         index_reg = args [1]->dreg;
5275 #endif  
5276                         MONO_EMIT_BOUNDS_CHECK (cfg, args [0]->dreg, MonoString, length, index_reg);
5277
5278 #if defined(TARGET_X86) || defined(TARGET_AMD64)
5279                         EMIT_NEW_X86_LEA (cfg, ins, args [0]->dreg, index_reg, 1, MONO_STRUCT_OFFSET (MonoString, chars));
5280                         add_reg = ins->dreg;
5281                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADU2_MEMBASE, dreg, 
5282                                                                    add_reg, 0);
5283 #else
5284                         int mult_reg = alloc_preg (cfg);
5285                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHL_IMM, mult_reg, index_reg, 1);
5286                         MONO_EMIT_NEW_BIALU (cfg, OP_PADD, add_reg, mult_reg, args [0]->dreg);
5287                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADU2_MEMBASE, dreg, 
5288                                                                    add_reg, MONO_STRUCT_OFFSET (MonoString, chars));
5289 #endif
5290                         type_from_op (cfg, ins, NULL, NULL);
5291                         return ins;
5292                 } else if (strcmp (cmethod->name, "get_Length") == 0 && fsig->param_count + fsig->hasthis == 1) {
5293                         int dreg = alloc_ireg (cfg);
5294                         /* Decompose later to allow more optimizations */
5295                         EMIT_NEW_UNALU (cfg, ins, OP_STRLEN, dreg, args [0]->dreg);
5296                         ins->type = STACK_I4;
5297                         ins->flags |= MONO_INST_FAULT;
5298                         cfg->cbb->has_array_access = TRUE;
5299                         cfg->flags |= MONO_CFG_HAS_ARRAY_ACCESS;
5300
5301                         return ins;
5302                 } else 
5303                         return NULL;
5304         } else if (cmethod->klass == mono_defaults.object_class) {
5305                 if (strcmp (cmethod->name, "GetType") == 0 && fsig->param_count + fsig->hasthis == 1) {
5306                         int dreg = alloc_ireg_ref (cfg);
5307                         int vt_reg = alloc_preg (cfg);
5308                         MONO_EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, vt_reg, args [0]->dreg, MONO_STRUCT_OFFSET (MonoObject, vtable));
5309                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, dreg, vt_reg, MONO_STRUCT_OFFSET (MonoVTable, type));
5310                         type_from_op (cfg, ins, NULL, NULL);
5311
5312                         return ins;
5313                 } else if (!cfg->backend->emulate_mul_div && strcmp (cmethod->name, "InternalGetHashCode") == 0 && fsig->param_count == 1 && !mono_gc_is_moving ()) {
5314                         int dreg = alloc_ireg (cfg);
5315                         int t1 = alloc_ireg (cfg);
5316         
5317                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHL_IMM, t1, args [0]->dreg, 3);
5318                         EMIT_NEW_BIALU_IMM (cfg, ins, OP_MUL_IMM, dreg, t1, 2654435761u);
5319                         ins->type = STACK_I4;
5320
5321                         return ins;
5322                 } else if (strcmp (cmethod->name, ".ctor") == 0 && fsig->param_count == 0) {
5323                         MONO_INST_NEW (cfg, ins, OP_NOP);
5324                         MONO_ADD_INS (cfg->cbb, ins);
5325                         return ins;
5326                 } else
5327                         return NULL;
5328         } else if (cmethod->klass == mono_defaults.array_class) {
5329                 if (strcmp (cmethod->name, "GetGenericValueImpl") == 0 && fsig->param_count + fsig->hasthis == 3 && !cfg->gsharedvt)
5330                         return emit_array_generic_access (cfg, fsig, args, FALSE);
5331                 else if (strcmp (cmethod->name, "SetGenericValueImpl") == 0 && fsig->param_count + fsig->hasthis == 3 && !cfg->gsharedvt)
5332                         return emit_array_generic_access (cfg, fsig, args, TRUE);
5333
5334 #ifndef MONO_BIG_ARRAYS
5335                 /*
5336                  * This is an inline version of GetLength/GetLowerBound(0) used frequently in
5337                  * Array methods.
5338                  */
5339                 else if (((strcmp (cmethod->name, "GetLength") == 0 && fsig->param_count + fsig->hasthis == 2) ||
5340                          (strcmp (cmethod->name, "GetLowerBound") == 0 && fsig->param_count + fsig->hasthis == 2)) &&
5341                          args [1]->opcode == OP_ICONST && args [1]->inst_c0 == 0) {
5342                         int dreg = alloc_ireg (cfg);
5343                         int bounds_reg = alloc_ireg_mp (cfg);
5344                         MonoBasicBlock *end_bb, *szarray_bb;
5345                         gboolean get_length = strcmp (cmethod->name, "GetLength") == 0;
5346
5347                         NEW_BBLOCK (cfg, end_bb);
5348                         NEW_BBLOCK (cfg, szarray_bb);
5349
5350                         EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, ins, OP_LOAD_MEMBASE, bounds_reg,
5351                                                                                  args [0]->dreg, MONO_STRUCT_OFFSET (MonoArray, bounds));
5352                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, bounds_reg, 0);
5353                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, szarray_bb);
5354                         /* Non-szarray case */
5355                         if (get_length)
5356                                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADI4_MEMBASE, dreg,
5357                                                                            bounds_reg, MONO_STRUCT_OFFSET (MonoArrayBounds, length));
5358                         else
5359                                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADI4_MEMBASE, dreg,
5360                                                                            bounds_reg, MONO_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
5361                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
5362                         MONO_START_BB (cfg, szarray_bb);
5363                         /* Szarray case */
5364                         if (get_length)
5365                                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADI4_MEMBASE, dreg,
5366                                                                            args [0]->dreg, MONO_STRUCT_OFFSET (MonoArray, max_length));
5367                         else
5368                                 MONO_EMIT_NEW_ICONST (cfg, dreg, 0);
5369                         MONO_START_BB (cfg, end_bb);
5370
5371                         EMIT_NEW_UNALU (cfg, ins, OP_MOVE, dreg, dreg);
5372                         ins->type = STACK_I4;
5373                         
5374                         return ins;
5375                 }
5376 #endif
5377
5378                 if (cmethod->name [0] != 'g')
5379                         return NULL;
5380
5381                 if (strcmp (cmethod->name, "get_Rank") == 0 && fsig->param_count + fsig->hasthis == 1) {
5382                         int dreg = alloc_ireg (cfg);
5383                         int vtable_reg = alloc_preg (cfg);
5384                         MONO_EMIT_NEW_LOAD_MEMBASE_OP_FAULT (cfg, OP_LOAD_MEMBASE, vtable_reg, 
5385                                                                                                  args [0]->dreg, MONO_STRUCT_OFFSET (MonoObject, vtable));
5386                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADU1_MEMBASE, dreg,
5387                                                                    vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, rank));
5388                         type_from_op (cfg, ins, NULL, NULL);
5389
5390                         return ins;
5391                 } else if (strcmp (cmethod->name, "get_Length") == 0 && fsig->param_count + fsig->hasthis == 1) {
5392                         int dreg = alloc_ireg (cfg);
5393
5394                         EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, ins, OP_LOADI4_MEMBASE, dreg, 
5395                                                                                  args [0]->dreg, MONO_STRUCT_OFFSET (MonoArray, max_length));
5396                         type_from_op (cfg, ins, NULL, NULL);
5397
5398                         return ins;
5399                 } else
5400                         return NULL;
5401         } else if (cmethod->klass == runtime_helpers_class) {
5402                 if (strcmp (cmethod->name, "get_OffsetToStringData") == 0 && fsig->param_count == 0) {
5403                         EMIT_NEW_ICONST (cfg, ins, MONO_STRUCT_OFFSET (MonoString, chars));
5404                         return ins;
5405                 } else if (strcmp (cmethod->name, "IsReferenceOrContainsReferences") == 0 && fsig->param_count == 0) {
5406                         MonoGenericContext *ctx = mono_method_get_context (cmethod);
5407                         g_assert (ctx);
5408                         g_assert (ctx->method_inst);
5409                         g_assert (ctx->method_inst->type_argc == 1);
5410                         MonoType *t = mini_get_underlying_type (ctx->method_inst->type_argv [0]);
5411                         MonoClass *klass = mono_class_from_mono_type (t);
5412
5413                         ins = NULL;
5414
5415                         mono_class_init (klass);
5416                         if (MONO_TYPE_IS_REFERENCE (t))
5417                                 EMIT_NEW_ICONST (cfg, ins, 1);
5418                         else if (MONO_TYPE_IS_PRIMITIVE (t))
5419                                 EMIT_NEW_ICONST (cfg, ins, 0);
5420                         else if (cfg->gshared && (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR) && !mini_type_var_is_vt (t))
5421                                 EMIT_NEW_ICONST (cfg, ins, 1);
5422                         else if (!cfg->gshared || !mini_class_check_context_used (cfg, klass))
5423                                 EMIT_NEW_ICONST (cfg, ins, klass->has_references ? 1 : 0);
5424                         else {
5425                                 g_assert (cfg->gshared);
5426
5427                                 int context_used = mini_class_check_context_used (cfg, klass);
5428
5429                                 /* This returns 1 or 2 */
5430                                 MonoInst *info = mini_emit_get_rgctx_klass (cfg, context_used, klass,   MONO_RGCTX_INFO_CLASS_IS_REF_OR_CONTAINS_REFS);
5431                                 int dreg = alloc_ireg (cfg);
5432                                 EMIT_NEW_BIALU_IMM (cfg, ins, OP_ISUB_IMM, dreg, info->dreg, 1);
5433                         }
5434
5435                         return ins;
5436                 } else
5437                         return NULL;
5438         } else if (cmethod->klass == mono_defaults.monitor_class) {
5439                 gboolean is_enter = FALSE;
5440                 gboolean is_v4 = FALSE;
5441
5442                 if (!strcmp (cmethod->name, "Enter") && fsig->param_count == 2 && fsig->params [1]->byref) {
5443                         is_enter = TRUE;
5444                         is_v4 = TRUE;
5445                 }
5446                 if (!strcmp (cmethod->name, "Enter") && fsig->param_count == 1)
5447                         is_enter = TRUE;
5448
5449                 if (is_enter) {
5450                         /*
5451                          * To make async stack traces work, icalls which can block should have a wrapper.
5452                          * For Monitor.Enter, emit two calls: a fastpath which doesn't have a wrapper, and a slowpath, which does.
5453                          */
5454                         MonoBasicBlock *end_bb;
5455
5456                         NEW_BBLOCK (cfg, end_bb);
5457
5458                         ins = mono_emit_jit_icall (cfg, is_v4 ? (gpointer)mono_monitor_enter_v4_fast : (gpointer)mono_monitor_enter_fast, args);
5459                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ICOMPARE_IMM, -1, ins->dreg, 0);
5460                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBNE_UN, end_bb);
5461                         ins = mono_emit_jit_icall (cfg, is_v4 ? (gpointer)mono_monitor_enter_v4_internal : (gpointer)mono_monitor_enter_internal, args);
5462                         MONO_START_BB (cfg, end_bb);
5463                         return ins;
5464                 }
5465         } else if (cmethod->klass == mono_defaults.thread_class) {
5466                 if (strcmp (cmethod->name, "SpinWait_nop") == 0 && fsig->param_count == 0) {
5467                         MONO_INST_NEW (cfg, ins, OP_RELAXED_NOP);
5468                         MONO_ADD_INS (cfg->cbb, ins);
5469                         return ins;
5470                 } else if (strcmp (cmethod->name, "MemoryBarrier") == 0 && fsig->param_count == 0) {
5471                         return emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
5472                 } else if (!strcmp (cmethod->name, "VolatileRead") && fsig->param_count == 1) {
5473                         guint32 opcode = 0;
5474                         gboolean is_ref = mini_type_is_reference (fsig->params [0]);
5475
5476                         if (fsig->params [0]->type == MONO_TYPE_I1)
5477                                 opcode = OP_LOADI1_MEMBASE;
5478                         else if (fsig->params [0]->type == MONO_TYPE_U1)
5479                                 opcode = OP_LOADU1_MEMBASE;
5480                         else if (fsig->params [0]->type == MONO_TYPE_I2)
5481                                 opcode = OP_LOADI2_MEMBASE;
5482                         else if (fsig->params [0]->type == MONO_TYPE_U2)
5483                                 opcode = OP_LOADU2_MEMBASE;
5484                         else if (fsig->params [0]->type == MONO_TYPE_I4)
5485                                 opcode = OP_LOADI4_MEMBASE;
5486                         else if (fsig->params [0]->type == MONO_TYPE_U4)
5487                                 opcode = OP_LOADU4_MEMBASE;
5488                         else if (fsig->params [0]->type == MONO_TYPE_I8 || fsig->params [0]->type == MONO_TYPE_U8)
5489                                 opcode = OP_LOADI8_MEMBASE;
5490                         else if (fsig->params [0]->type == MONO_TYPE_R4)
5491                                 opcode = OP_LOADR4_MEMBASE;
5492                         else if (fsig->params [0]->type == MONO_TYPE_R8)
5493                                 opcode = OP_LOADR8_MEMBASE;
5494                         else if (is_ref || fsig->params [0]->type == MONO_TYPE_I || fsig->params [0]->type == MONO_TYPE_U)
5495                                 opcode = OP_LOAD_MEMBASE;
5496
5497                         if (opcode) {
5498                                 MONO_INST_NEW (cfg, ins, opcode);
5499                                 ins->inst_basereg = args [0]->dreg;
5500                                 ins->inst_offset = 0;
5501                                 MONO_ADD_INS (cfg->cbb, ins);
5502
5503                                 switch (fsig->params [0]->type) {
5504                                 case MONO_TYPE_I1:
5505                                 case MONO_TYPE_U1:
5506                                 case MONO_TYPE_I2:
5507                                 case MONO_TYPE_U2:
5508                                 case MONO_TYPE_I4:
5509                                 case MONO_TYPE_U4:
5510                                         ins->dreg = mono_alloc_ireg (cfg);
5511                                         ins->type = STACK_I4;
5512                                         break;
5513                                 case MONO_TYPE_I8:
5514                                 case MONO_TYPE_U8:
5515                                         ins->dreg = mono_alloc_lreg (cfg);
5516                                         ins->type = STACK_I8;
5517                                         break;
5518                                 case MONO_TYPE_I:
5519                                 case MONO_TYPE_U:
5520                                         ins->dreg = mono_alloc_ireg (cfg);
5521 #if SIZEOF_REGISTER == 8
5522                                         ins->type = STACK_I8;
5523 #else
5524                                         ins->type = STACK_I4;
5525 #endif
5526                                         break;
5527                                 case MONO_TYPE_R4:
5528                                 case MONO_TYPE_R8:
5529                                         ins->dreg = mono_alloc_freg (cfg);
5530                                         ins->type = STACK_R8;
5531                                         break;
5532                                 default:
5533                                         g_assert (mini_type_is_reference (fsig->params [0]));
5534                                         ins->dreg = mono_alloc_ireg_ref (cfg);
5535                                         ins->type = STACK_OBJ;
5536                                         break;
5537                                 }
5538
5539                                 if (opcode == OP_LOADI8_MEMBASE)
5540                                         ins = mono_decompose_opcode (cfg, ins);
5541
5542                                 emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
5543
5544                                 return ins;
5545                         }
5546                 } else if (!strcmp (cmethod->name, "VolatileWrite") && fsig->param_count == 2) {
5547                         guint32 opcode = 0;
5548                         gboolean is_ref = mini_type_is_reference (fsig->params [0]);
5549
5550                         if (fsig->params [0]->type == MONO_TYPE_I1 || fsig->params [0]->type == MONO_TYPE_U1)
5551                                 opcode = OP_STOREI1_MEMBASE_REG;
5552                         else if (fsig->params [0]->type == MONO_TYPE_I2 || fsig->params [0]->type == MONO_TYPE_U2)
5553                                 opcode = OP_STOREI2_MEMBASE_REG;
5554                         else if (fsig->params [0]->type == MONO_TYPE_I4 || fsig->params [0]->type == MONO_TYPE_U4)
5555                                 opcode = OP_STOREI4_MEMBASE_REG;
5556                         else if (fsig->params [0]->type == MONO_TYPE_I8 || fsig->params [0]->type == MONO_TYPE_U8)
5557                                 opcode = OP_STOREI8_MEMBASE_REG;
5558                         else if (fsig->params [0]->type == MONO_TYPE_R4)
5559                                 opcode = OP_STORER4_MEMBASE_REG;
5560                         else if (fsig->params [0]->type == MONO_TYPE_R8)
5561                                 opcode = OP_STORER8_MEMBASE_REG;
5562                         else if (is_ref || fsig->params [0]->type == MONO_TYPE_I || fsig->params [0]->type == MONO_TYPE_U)
5563                                 opcode = OP_STORE_MEMBASE_REG;
5564
5565                         if (opcode) {
5566                                 emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
5567
5568                                 MONO_INST_NEW (cfg, ins, opcode);
5569                                 ins->sreg1 = args [1]->dreg;
5570                                 ins->inst_destbasereg = args [0]->dreg;
5571                                 ins->inst_offset = 0;
5572                                 MONO_ADD_INS (cfg->cbb, ins);
5573
5574                                 if (opcode == OP_STOREI8_MEMBASE_REG)
5575                                         ins = mono_decompose_opcode (cfg, ins);
5576
5577                                 return ins;
5578                         }
5579                 }
5580         } else if (cmethod->klass->image == mono_defaults.corlib &&
5581                            (strcmp (cmethod->klass->name_space, "System.Threading") == 0) &&
5582                            (strcmp (cmethod->klass->name, "Interlocked") == 0)) {
5583                 ins = NULL;
5584
5585 #if SIZEOF_REGISTER == 8
5586                 if (!cfg->llvm_only && strcmp (cmethod->name, "Read") == 0 && fsig->param_count == 1 && (fsig->params [0]->type == MONO_TYPE_I8)) {
5587                         if (!cfg->llvm_only && mono_arch_opcode_supported (OP_ATOMIC_LOAD_I8)) {
5588                                 MONO_INST_NEW (cfg, ins, OP_ATOMIC_LOAD_I8);
5589                                 ins->dreg = mono_alloc_preg (cfg);
5590                                 ins->sreg1 = args [0]->dreg;
5591                                 ins->type = STACK_I8;
5592                                 ins->backend.memory_barrier_kind = MONO_MEMORY_BARRIER_SEQ;
5593                                 MONO_ADD_INS (cfg->cbb, ins);
5594                         } else {
5595                                 MonoInst *load_ins;
5596
5597                                 emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
5598
5599                                 /* 64 bit reads are already atomic */
5600                                 MONO_INST_NEW (cfg, load_ins, OP_LOADI8_MEMBASE);
5601                                 load_ins->dreg = mono_alloc_preg (cfg);
5602                                 load_ins->inst_basereg = args [0]->dreg;
5603                                 load_ins->inst_offset = 0;
5604                                 load_ins->type = STACK_I8;
5605                                 MONO_ADD_INS (cfg->cbb, load_ins);
5606
5607                                 emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
5608
5609                                 ins = load_ins;
5610                         }
5611                 }
5612 #endif
5613
5614                 if (strcmp (cmethod->name, "Increment") == 0 && fsig->param_count == 1) {
5615                         MonoInst *ins_iconst;
5616                         guint32 opcode = 0;
5617
5618                         if (fsig->params [0]->type == MONO_TYPE_I4) {
5619                                 opcode = OP_ATOMIC_ADD_I4;
5620                                 cfg->has_atomic_add_i4 = TRUE;
5621                         }
5622 #if SIZEOF_REGISTER == 8
5623                         else if (fsig->params [0]->type == MONO_TYPE_I8)
5624                                 opcode = OP_ATOMIC_ADD_I8;
5625 #endif
5626                         if (opcode) {
5627                                 if (!mono_arch_opcode_supported (opcode))
5628                                         return NULL;
5629                                 MONO_INST_NEW (cfg, ins_iconst, OP_ICONST);
5630                                 ins_iconst->inst_c0 = 1;
5631                                 ins_iconst->dreg = mono_alloc_ireg (cfg);
5632                                 MONO_ADD_INS (cfg->cbb, ins_iconst);
5633
5634                                 MONO_INST_NEW (cfg, ins, opcode);
5635                                 ins->dreg = mono_alloc_ireg (cfg);
5636                                 ins->inst_basereg = args [0]->dreg;
5637                                 ins->inst_offset = 0;
5638                                 ins->sreg2 = ins_iconst->dreg;
5639                                 ins->type = (opcode == OP_ATOMIC_ADD_I4) ? STACK_I4 : STACK_I8;
5640                                 MONO_ADD_INS (cfg->cbb, ins);
5641                         }
5642                 } else if (strcmp (cmethod->name, "Decrement") == 0 && fsig->param_count == 1) {
5643                         MonoInst *ins_iconst;
5644                         guint32 opcode = 0;
5645
5646                         if (fsig->params [0]->type == MONO_TYPE_I4) {
5647                                 opcode = OP_ATOMIC_ADD_I4;
5648                                 cfg->has_atomic_add_i4 = TRUE;
5649                         }
5650 #if SIZEOF_REGISTER == 8
5651                         else if (fsig->params [0]->type == MONO_TYPE_I8)
5652                                 opcode = OP_ATOMIC_ADD_I8;
5653 #endif
5654                         if (opcode) {
5655                                 if (!mono_arch_opcode_supported (opcode))
5656                                         return NULL;
5657                                 MONO_INST_NEW (cfg, ins_iconst, OP_ICONST);
5658                                 ins_iconst->inst_c0 = -1;
5659                                 ins_iconst->dreg = mono_alloc_ireg (cfg);
5660                                 MONO_ADD_INS (cfg->cbb, ins_iconst);
5661
5662                                 MONO_INST_NEW (cfg, ins, opcode);
5663                                 ins->dreg = mono_alloc_ireg (cfg);
5664                                 ins->inst_basereg = args [0]->dreg;
5665                                 ins->inst_offset = 0;
5666                                 ins->sreg2 = ins_iconst->dreg;
5667                                 ins->type = (opcode == OP_ATOMIC_ADD_I4) ? STACK_I4 : STACK_I8;
5668                                 MONO_ADD_INS (cfg->cbb, ins);
5669                         }
5670                 } else if (strcmp (cmethod->name, "Add") == 0 && fsig->param_count == 2) {
5671                         guint32 opcode = 0;
5672
5673                         if (fsig->params [0]->type == MONO_TYPE_I4) {
5674                                 opcode = OP_ATOMIC_ADD_I4;
5675                                 cfg->has_atomic_add_i4 = TRUE;
5676                         }
5677 #if SIZEOF_REGISTER == 8
5678                         else if (fsig->params [0]->type == MONO_TYPE_I8)
5679                                 opcode = OP_ATOMIC_ADD_I8;
5680 #endif
5681                         if (opcode) {
5682                                 if (!mono_arch_opcode_supported (opcode))
5683                                         return NULL;
5684                                 MONO_INST_NEW (cfg, ins, opcode);
5685                                 ins->dreg = mono_alloc_ireg (cfg);
5686                                 ins->inst_basereg = args [0]->dreg;
5687                                 ins->inst_offset = 0;
5688                                 ins->sreg2 = args [1]->dreg;
5689                                 ins->type = (opcode == OP_ATOMIC_ADD_I4) ? STACK_I4 : STACK_I8;
5690                                 MONO_ADD_INS (cfg->cbb, ins);
5691                         }
5692                 }
5693                 else if (strcmp (cmethod->name, "Exchange") == 0 && fsig->param_count == 2) {
5694                         MonoInst *f2i = NULL, *i2f;
5695                         guint32 opcode, f2i_opcode, i2f_opcode;
5696                         gboolean is_ref = mini_type_is_reference (fsig->params [0]);
5697                         gboolean is_float = fsig->params [0]->type == MONO_TYPE_R4 || fsig->params [0]->type == MONO_TYPE_R8;
5698
5699                         if (fsig->params [0]->type == MONO_TYPE_I4 ||
5700                             fsig->params [0]->type == MONO_TYPE_R4) {
5701                                 opcode = OP_ATOMIC_EXCHANGE_I4;
5702                                 f2i_opcode = OP_MOVE_F_TO_I4;
5703                                 i2f_opcode = OP_MOVE_I4_TO_F;
5704                                 cfg->has_atomic_exchange_i4 = TRUE;
5705                         }
5706 #if SIZEOF_REGISTER == 8
5707                         else if (is_ref ||
5708                                  fsig->params [0]->type == MONO_TYPE_I8 ||
5709                                  fsig->params [0]->type == MONO_TYPE_R8 ||
5710                                  fsig->params [0]->type == MONO_TYPE_I) {
5711                                 opcode = OP_ATOMIC_EXCHANGE_I8;
5712                                 f2i_opcode = OP_MOVE_F_TO_I8;
5713                                 i2f_opcode = OP_MOVE_I8_TO_F;
5714                         }
5715 #else
5716                         else if (is_ref || fsig->params [0]->type == MONO_TYPE_I) {
5717                                 opcode = OP_ATOMIC_EXCHANGE_I4;
5718                                 cfg->has_atomic_exchange_i4 = TRUE;
5719                         }
5720 #endif
5721                         else
5722                                 return NULL;
5723
5724                         if (!mono_arch_opcode_supported (opcode))
5725                                 return NULL;
5726
5727                         if (is_float) {
5728                                 /* TODO: Decompose these opcodes instead of bailing here. */
5729                                 if (COMPILE_SOFT_FLOAT (cfg))
5730                                         return NULL;
5731
5732                                 MONO_INST_NEW (cfg, f2i, f2i_opcode);
5733                                 f2i->dreg = mono_alloc_ireg (cfg);
5734                                 f2i->sreg1 = args [1]->dreg;
5735                                 if (f2i_opcode == OP_MOVE_F_TO_I4)
5736                                         f2i->backend.spill_var = mini_get_int_to_float_spill_area (cfg);
5737                                 MONO_ADD_INS (cfg->cbb, f2i);
5738                         }
5739
5740                         MONO_INST_NEW (cfg, ins, opcode);
5741                         ins->dreg = is_ref ? mono_alloc_ireg_ref (cfg) : mono_alloc_ireg (cfg);
5742                         ins->inst_basereg = args [0]->dreg;
5743                         ins->inst_offset = 0;
5744                         ins->sreg2 = is_float ? f2i->dreg : args [1]->dreg;
5745                         MONO_ADD_INS (cfg->cbb, ins);
5746
5747                         switch (fsig->params [0]->type) {
5748                         case MONO_TYPE_I4:
5749                                 ins->type = STACK_I4;
5750                                 break;
5751                         case MONO_TYPE_I8:
5752                                 ins->type = STACK_I8;
5753                                 break;
5754                         case MONO_TYPE_I:
5755 #if SIZEOF_REGISTER == 8
5756                                 ins->type = STACK_I8;
5757 #else
5758                                 ins->type = STACK_I4;
5759 #endif
5760                                 break;
5761                         case MONO_TYPE_R4:
5762                         case MONO_TYPE_R8:
5763                                 ins->type = STACK_R8;
5764                                 break;
5765                         default:
5766                                 g_assert (mini_type_is_reference (fsig->params [0]));
5767                                 ins->type = STACK_OBJ;
5768                                 break;
5769                         }
5770
5771                         if (is_float) {
5772                                 MONO_INST_NEW (cfg, i2f, i2f_opcode);
5773                                 i2f->dreg = mono_alloc_freg (cfg);
5774                                 i2f->sreg1 = ins->dreg;
5775                                 i2f->type = STACK_R8;
5776                                 if (i2f_opcode == OP_MOVE_I4_TO_F)
5777                                         i2f->backend.spill_var = mini_get_int_to_float_spill_area (cfg);
5778                                 MONO_ADD_INS (cfg->cbb, i2f);
5779
5780                                 ins = i2f;
5781                         }
5782
5783                         if (cfg->gen_write_barriers && is_ref)
5784                                 emit_write_barrier (cfg, args [0], args [1]);
5785                 }
5786                 else if ((strcmp (cmethod->name, "CompareExchange") == 0) && fsig->param_count == 3) {
5787                         MonoInst *f2i_new = NULL, *f2i_cmp = NULL, *i2f;
5788                         guint32 opcode, f2i_opcode, i2f_opcode;
5789                         gboolean is_ref = mini_type_is_reference (fsig->params [1]);
5790                         gboolean is_float = fsig->params [1]->type == MONO_TYPE_R4 || fsig->params [1]->type == MONO_TYPE_R8;
5791
5792                         if (fsig->params [1]->type == MONO_TYPE_I4 ||
5793                             fsig->params [1]->type == MONO_TYPE_R4) {
5794                                 opcode = OP_ATOMIC_CAS_I4;
5795                                 f2i_opcode = OP_MOVE_F_TO_I4;
5796                                 i2f_opcode = OP_MOVE_I4_TO_F;
5797                                 cfg->has_atomic_cas_i4 = TRUE;
5798                         }
5799 #if SIZEOF_REGISTER == 8
5800                         else if (is_ref ||
5801                                  fsig->params [1]->type == MONO_TYPE_I8 ||
5802                                  fsig->params [1]->type == MONO_TYPE_R8 ||
5803                                  fsig->params [1]->type == MONO_TYPE_I) {
5804                                 opcode = OP_ATOMIC_CAS_I8;
5805                                 f2i_opcode = OP_MOVE_F_TO_I8;
5806                                 i2f_opcode = OP_MOVE_I8_TO_F;
5807                         }
5808 #else
5809                         else if (is_ref || fsig->params [1]->type == MONO_TYPE_I) {
5810                                 opcode = OP_ATOMIC_CAS_I4;
5811                                 cfg->has_atomic_cas_i4 = TRUE;
5812                         }
5813 #endif
5814                         else
5815                                 return NULL;
5816
5817                         if (!mono_arch_opcode_supported (opcode))
5818                                 return NULL;
5819
5820                         if (is_float) {
5821                                 /* TODO: Decompose these opcodes instead of bailing here. */
5822                                 if (COMPILE_SOFT_FLOAT (cfg))
5823                                         return NULL;
5824
5825                                 MONO_INST_NEW (cfg, f2i_new, f2i_opcode);
5826                                 f2i_new->dreg = mono_alloc_ireg (cfg);
5827                                 f2i_new->sreg1 = args [1]->dreg;
5828                                 if (f2i_opcode == OP_MOVE_F_TO_I4)
5829                                         f2i_new->backend.spill_var = mini_get_int_to_float_spill_area (cfg);
5830                                 MONO_ADD_INS (cfg->cbb, f2i_new);
5831
5832                                 MONO_INST_NEW (cfg, f2i_cmp, f2i_opcode);
5833                                 f2i_cmp->dreg = mono_alloc_ireg (cfg);
5834                                 f2i_cmp->sreg1 = args [2]->dreg;
5835                                 if (f2i_opcode == OP_MOVE_F_TO_I4)
5836                                         f2i_cmp->backend.spill_var = mini_get_int_to_float_spill_area (cfg);
5837                                 MONO_ADD_INS (cfg->cbb, f2i_cmp);
5838                         }
5839
5840                         MONO_INST_NEW (cfg, ins, opcode);
5841                         ins->dreg = is_ref ? alloc_ireg_ref (cfg) : alloc_ireg (cfg);
5842                         ins->sreg1 = args [0]->dreg;
5843                         ins->sreg2 = is_float ? f2i_new->dreg : args [1]->dreg;
5844                         ins->sreg3 = is_float ? f2i_cmp->dreg : args [2]->dreg;
5845                         MONO_ADD_INS (cfg->cbb, ins);
5846
5847                         switch (fsig->params [1]->type) {
5848                         case MONO_TYPE_I4:
5849                                 ins->type = STACK_I4;
5850                                 break;
5851                         case MONO_TYPE_I8:
5852                                 ins->type = STACK_I8;
5853                                 break;
5854                         case MONO_TYPE_I:
5855 #if SIZEOF_REGISTER == 8
5856                                 ins->type = STACK_I8;
5857 #else
5858                                 ins->type = STACK_I4;
5859 #endif
5860                                 break;
5861                         case MONO_TYPE_R4:
5862                                 ins->type = cfg->r4_stack_type;
5863                                 break;
5864                         case MONO_TYPE_R8:
5865                                 ins->type = STACK_R8;
5866                                 break;
5867                         default:
5868                                 g_assert (mini_type_is_reference (fsig->params [1]));
5869                                 ins->type = STACK_OBJ;
5870                                 break;
5871                         }
5872
5873                         if (is_float) {
5874                                 MONO_INST_NEW (cfg, i2f, i2f_opcode);
5875                                 i2f->dreg = mono_alloc_freg (cfg);
5876                                 i2f->sreg1 = ins->dreg;
5877                                 i2f->type = STACK_R8;
5878                                 if (i2f_opcode == OP_MOVE_I4_TO_F)
5879                                         i2f->backend.spill_var = mini_get_int_to_float_spill_area (cfg);
5880                                 MONO_ADD_INS (cfg->cbb, i2f);
5881
5882                                 ins = i2f;
5883                         }
5884
5885                         if (cfg->gen_write_barriers && is_ref)
5886                                 emit_write_barrier (cfg, args [0], args [1]);
5887                 }
5888                 else if ((strcmp (cmethod->name, "CompareExchange") == 0) && fsig->param_count == 4 &&
5889                          fsig->params [1]->type == MONO_TYPE_I4) {
5890                         MonoInst *cmp, *ceq;
5891
5892                         if (!mono_arch_opcode_supported (OP_ATOMIC_CAS_I4))
5893                                 return NULL;
5894
5895                         /* int32 r = CAS (location, value, comparand); */
5896                         MONO_INST_NEW (cfg, ins, OP_ATOMIC_CAS_I4);
5897                         ins->dreg = alloc_ireg (cfg);
5898                         ins->sreg1 = args [0]->dreg;
5899                         ins->sreg2 = args [1]->dreg;
5900                         ins->sreg3 = args [2]->dreg;
5901                         ins->type = STACK_I4;
5902                         MONO_ADD_INS (cfg->cbb, ins);
5903
5904                         /* bool result = r == comparand; */
5905                         MONO_INST_NEW (cfg, cmp, OP_ICOMPARE);
5906                         cmp->sreg1 = ins->dreg;
5907                         cmp->sreg2 = args [2]->dreg;
5908                         cmp->type = STACK_I4;
5909                         MONO_ADD_INS (cfg->cbb, cmp);
5910
5911                         MONO_INST_NEW (cfg, ceq, OP_ICEQ);
5912                         ceq->dreg = alloc_ireg (cfg);
5913                         ceq->type = STACK_I4;
5914                         MONO_ADD_INS (cfg->cbb, ceq);
5915
5916                         /* *success = result; */
5917                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI1_MEMBASE_REG, args [3]->dreg, 0, ceq->dreg);
5918
5919                         cfg->has_atomic_cas_i4 = TRUE;
5920                 }
5921                 else if (strcmp (cmethod->name, "MemoryBarrier") == 0 && fsig->param_count == 0)
5922                         ins = emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
5923
5924                 if (ins)
5925                         return ins;
5926         } else if (cmethod->klass->image == mono_defaults.corlib &&
5927                            (strcmp (cmethod->klass->name_space, "System.Threading") == 0) &&
5928                            (strcmp (cmethod->klass->name, "Volatile") == 0)) {
5929                 ins = NULL;
5930
5931                 if (!cfg->llvm_only && !strcmp (cmethod->name, "Read") && fsig->param_count == 1) {
5932                         guint32 opcode = 0;
5933                         MonoType *t = fsig->params [0];
5934                         gboolean is_ref;
5935                         gboolean is_float = t->type == MONO_TYPE_R4 || t->type == MONO_TYPE_R8;
5936
5937                         g_assert (t->byref);
5938                         /* t is a byref type, so the reference check is more complicated */
5939                         is_ref = mini_type_is_reference (&mono_class_from_mono_type (t)->byval_arg);
5940                         if (t->type == MONO_TYPE_I1)
5941                                 opcode = OP_ATOMIC_LOAD_I1;
5942                         else if (t->type == MONO_TYPE_U1 || t->type == MONO_TYPE_BOOLEAN)
5943                                 opcode = OP_ATOMIC_LOAD_U1;
5944                         else if (t->type == MONO_TYPE_I2)
5945                                 opcode = OP_ATOMIC_LOAD_I2;
5946                         else if (t->type == MONO_TYPE_U2)
5947                                 opcode = OP_ATOMIC_LOAD_U2;
5948                         else if (t->type == MONO_TYPE_I4)
5949                                 opcode = OP_ATOMIC_LOAD_I4;
5950                         else if (t->type == MONO_TYPE_U4)
5951                                 opcode = OP_ATOMIC_LOAD_U4;
5952                         else if (t->type == MONO_TYPE_R4)
5953                                 opcode = OP_ATOMIC_LOAD_R4;
5954                         else if (t->type == MONO_TYPE_R8)
5955                                 opcode = OP_ATOMIC_LOAD_R8;
5956 #if SIZEOF_REGISTER == 8
5957                         else if (t->type == MONO_TYPE_I8 || t->type == MONO_TYPE_I)
5958                                 opcode = OP_ATOMIC_LOAD_I8;
5959                         else if (is_ref || t->type == MONO_TYPE_U8 || t->type == MONO_TYPE_U)
5960                                 opcode = OP_ATOMIC_LOAD_U8;
5961 #else
5962                         else if (t->type == MONO_TYPE_I)
5963                                 opcode = OP_ATOMIC_LOAD_I4;
5964                         else if (is_ref || t->type == MONO_TYPE_U)
5965                                 opcode = OP_ATOMIC_LOAD_U4;
5966 #endif
5967
5968                         if (opcode) {
5969                                 if (!mono_arch_opcode_supported (opcode))
5970                                         return NULL;
5971
5972                                 MONO_INST_NEW (cfg, ins, opcode);
5973                                 ins->dreg = is_ref ? mono_alloc_ireg_ref (cfg) : (is_float ? mono_alloc_freg (cfg) : mono_alloc_ireg (cfg));
5974                                 ins->sreg1 = args [0]->dreg;
5975                                 ins->backend.memory_barrier_kind = MONO_MEMORY_BARRIER_ACQ;
5976                                 MONO_ADD_INS (cfg->cbb, ins);
5977
5978                                 switch (t->type) {
5979                                 case MONO_TYPE_BOOLEAN:
5980                                 case MONO_TYPE_I1:
5981                                 case MONO_TYPE_U1:
5982                                 case MONO_TYPE_I2:
5983                                 case MONO_TYPE_U2:
5984                                 case MONO_TYPE_I4:
5985                                 case MONO_TYPE_U4:
5986                                         ins->type = STACK_I4;
5987                                         break;
5988                                 case MONO_TYPE_I8:
5989                                 case MONO_TYPE_U8:
5990                                         ins->type = STACK_I8;
5991                                         break;
5992                                 case MONO_TYPE_I:
5993                                 case MONO_TYPE_U:
5994 #if SIZEOF_REGISTER == 8
5995                                         ins->type = STACK_I8;
5996 #else
5997                                         ins->type = STACK_I4;
5998 #endif
5999                                         break;
6000                                 case MONO_TYPE_R4:
6001                                         ins->type = cfg->r4_stack_type;
6002                                         break;
6003                                 case MONO_TYPE_R8:
6004                                         ins->type = STACK_R8;
6005                                         break;
6006                                 default:
6007                                         g_assert (is_ref);
6008                                         ins->type = STACK_OBJ;
6009                                         break;
6010                                 }
6011                         }
6012                 }
6013
6014                 if (!cfg->llvm_only && !strcmp (cmethod->name, "Write") && fsig->param_count == 2) {
6015                         guint32 opcode = 0;
6016                         MonoType *t = fsig->params [0];
6017                         gboolean is_ref;
6018
6019                         g_assert (t->byref);
6020                         is_ref = mini_type_is_reference (&mono_class_from_mono_type (t)->byval_arg);
6021                         if (t->type == MONO_TYPE_I1)
6022                                 opcode = OP_ATOMIC_STORE_I1;
6023                         else if (t->type == MONO_TYPE_U1 || t->type == MONO_TYPE_BOOLEAN)
6024                                 opcode = OP_ATOMIC_STORE_U1;
6025                         else if (t->type == MONO_TYPE_I2)
6026                                 opcode = OP_ATOMIC_STORE_I2;
6027                         else if (t->type == MONO_TYPE_U2)
6028                                 opcode = OP_ATOMIC_STORE_U2;
6029                         else if (t->type == MONO_TYPE_I4)
6030                                 opcode = OP_ATOMIC_STORE_I4;
6031                         else if (t->type == MONO_TYPE_U4)
6032                                 opcode = OP_ATOMIC_STORE_U4;
6033                         else if (t->type == MONO_TYPE_R4)
6034                                 opcode = OP_ATOMIC_STORE_R4;
6035                         else if (t->type == MONO_TYPE_R8)
6036                                 opcode = OP_ATOMIC_STORE_R8;
6037 #if SIZEOF_REGISTER == 8
6038                         else if (t->type == MONO_TYPE_I8 || t->type == MONO_TYPE_I)
6039                                 opcode = OP_ATOMIC_STORE_I8;
6040                         else if (is_ref || t->type == MONO_TYPE_U8 || t->type == MONO_TYPE_U)
6041                                 opcode = OP_ATOMIC_STORE_U8;
6042 #else
6043                         else if (t->type == MONO_TYPE_I)
6044                                 opcode = OP_ATOMIC_STORE_I4;
6045                         else if (is_ref || t->type == MONO_TYPE_U)
6046                                 opcode = OP_ATOMIC_STORE_U4;
6047 #endif
6048
6049                         if (opcode) {
6050                                 if (!mono_arch_opcode_supported (opcode))
6051                                         return NULL;
6052
6053                                 MONO_INST_NEW (cfg, ins, opcode);
6054                                 ins->dreg = args [0]->dreg;
6055                                 ins->sreg1 = args [1]->dreg;
6056                                 ins->backend.memory_barrier_kind = MONO_MEMORY_BARRIER_REL;
6057                                 MONO_ADD_INS (cfg->cbb, ins);
6058
6059                                 if (cfg->gen_write_barriers && is_ref)
6060                                         emit_write_barrier (cfg, args [0], args [1]);
6061                         }
6062                 }
6063
6064                 if (ins)
6065                         return ins;
6066         } else if (cmethod->klass->image == mono_defaults.corlib &&
6067                            (strcmp (cmethod->klass->name_space, "System.Diagnostics") == 0) &&
6068                            (strcmp (cmethod->klass->name, "Debugger") == 0)) {
6069                 if (!strcmp (cmethod->name, "Break") && fsig->param_count == 0) {
6070                         if (should_insert_brekpoint (cfg->method)) {
6071                                 ins = mono_emit_jit_icall (cfg, mono_debugger_agent_user_break, NULL);
6072                         } else {
6073                                 MONO_INST_NEW (cfg, ins, OP_NOP);
6074                                 MONO_ADD_INS (cfg->cbb, ins);
6075                         }
6076                         return ins;
6077                 }
6078         } else if (cmethod->klass->image == mono_defaults.corlib &&
6079                    (strcmp (cmethod->klass->name_space, "System") == 0) &&
6080                    (strcmp (cmethod->klass->name, "Environment") == 0)) {
6081                 if (!strcmp (cmethod->name, "get_IsRunningOnWindows") && fsig->param_count == 0) {
6082 #ifdef TARGET_WIN32
6083                         EMIT_NEW_ICONST (cfg, ins, 1);
6084 #else
6085                         EMIT_NEW_ICONST (cfg, ins, 0);
6086 #endif
6087                 }
6088         } else if (cmethod->klass->image == mono_defaults.corlib &&
6089                            (strcmp (cmethod->klass->name_space, "System.Reflection") == 0) &&
6090                            (strcmp (cmethod->klass->name, "Assembly") == 0)) {
6091                 if (cfg->llvm_only && !strcmp (cmethod->name, "GetExecutingAssembly")) {
6092                         /* No stack walks are currently available, so implement this as an intrinsic */
6093                         MonoInst *assembly_ins;
6094
6095                         EMIT_NEW_AOTCONST (cfg, assembly_ins, MONO_PATCH_INFO_IMAGE, cfg->method->klass->image);
6096                         ins = mono_emit_jit_icall (cfg, mono_get_assembly_object, &assembly_ins);
6097                         return ins;
6098                 }
6099         } else if (cmethod->klass->image == mono_defaults.corlib &&
6100                            (strcmp (cmethod->klass->name_space, "System.Reflection") == 0) &&
6101                            (strcmp (cmethod->klass->name, "MethodBase") == 0)) {
6102                 if (cfg->llvm_only && !strcmp (cmethod->name, "GetCurrentMethod")) {
6103                         /* No stack walks are currently available, so implement this as an intrinsic */
6104                         MonoInst *method_ins;
6105                         MonoMethod *declaring = cfg->method;
6106
6107                         /* This returns the declaring generic method */
6108                         if (declaring->is_inflated)
6109                                 declaring = ((MonoMethodInflated*)cfg->method)->declaring;
6110                         EMIT_NEW_AOTCONST (cfg, method_ins, MONO_PATCH_INFO_METHODCONST, declaring);
6111                         ins = mono_emit_jit_icall (cfg, mono_get_method_object, &method_ins);
6112                         cfg->no_inline = TRUE;
6113                         if (cfg->method != cfg->current_method)
6114                                 inline_failure (cfg, "MethodBase:GetCurrentMethod ()");
6115                         return ins;
6116                 }
6117         } else if (cmethod->klass == mono_defaults.math_class) {
6118                 /* 
6119                  * There is general branchless code for Min/Max, but it does not work for 
6120                  * all inputs:
6121                  * http://everything2.com/?node_id=1051618
6122                  */
6123         } else if (cmethod->klass == mono_defaults.systemtype_class && !strcmp (cmethod->name, "op_Equality")) {
6124                 EMIT_NEW_BIALU (cfg, ins, OP_COMPARE, -1, args [0]->dreg, args [1]->dreg);
6125                 MONO_INST_NEW (cfg, ins, OP_PCEQ);
6126                 ins->dreg = alloc_preg (cfg);
6127                 ins->type = STACK_I4;
6128                 MONO_ADD_INS (cfg->cbb, ins);
6129                 return ins;
6130         } else if (((!strcmp (cmethod->klass->image->assembly->aname.name, "MonoMac") ||
6131                     !strcmp (cmethod->klass->image->assembly->aname.name, "monotouch")) &&
6132                                 !strcmp (cmethod->klass->name_space, "XamCore.ObjCRuntime") &&
6133                                 !strcmp (cmethod->klass->name, "Selector")) ||
6134                            ((!strcmp (cmethod->klass->image->assembly->aname.name, "Xamarin.iOS") ||
6135                                  !strcmp (cmethod->klass->image->assembly->aname.name, "Xamarin.Mac")) &&
6136                                 !strcmp (cmethod->klass->name_space, "ObjCRuntime") &&
6137                                 !strcmp (cmethod->klass->name, "Selector"))
6138                            ) {
6139                 if ((cfg->backend->have_objc_get_selector || cfg->compile_llvm) &&
6140                         !strcmp (cmethod->name, "GetHandle") && fsig->param_count == 1 &&
6141                     (args [0]->opcode == OP_GOT_ENTRY || args [0]->opcode == OP_AOTCONST) &&
6142                     cfg->compile_aot) {
6143                         MonoInst *pi;
6144                         MonoJumpInfoToken *ji;
6145                         char *s;
6146
6147                         if (args [0]->opcode == OP_GOT_ENTRY) {
6148                                 pi = (MonoInst *)args [0]->inst_p1;
6149                                 g_assert (pi->opcode == OP_PATCH_INFO);
6150                                 g_assert (GPOINTER_TO_INT (pi->inst_p1) == MONO_PATCH_INFO_LDSTR);
6151                                 ji = (MonoJumpInfoToken *)pi->inst_p0;
6152                         } else {
6153                                 g_assert (GPOINTER_TO_INT (args [0]->inst_p1) == MONO_PATCH_INFO_LDSTR);
6154                                 ji = (MonoJumpInfoToken *)args [0]->inst_p0;
6155                         }
6156
6157                         NULLIFY_INS (args [0]);
6158
6159                         s = mono_ldstr_utf8 (ji->image, mono_metadata_token_index (ji->token), &cfg->error);
6160                         return_val_if_nok (&cfg->error, NULL);
6161
6162                         MONO_INST_NEW (cfg, ins, OP_OBJC_GET_SELECTOR);
6163                         ins->dreg = mono_alloc_ireg (cfg);
6164                         // FIXME: Leaks
6165                         ins->inst_p0 = s;
6166                         MONO_ADD_INS (cfg->cbb, ins);
6167                         return ins;
6168                 }
6169         }
6170
6171 #ifdef MONO_ARCH_SIMD_INTRINSICS
6172         if (cfg->opt & MONO_OPT_SIMD) {
6173                 ins = mono_emit_simd_intrinsics (cfg, cmethod, fsig, args);
6174                 if (ins)
6175                         return ins;
6176         }
6177 #endif
6178
6179         ins = mono_emit_native_types_intrinsics (cfg, cmethod, fsig, args);
6180         if (ins)
6181                 return ins;
6182
6183         if (COMPILE_LLVM (cfg)) {
6184                 ins = llvm_emit_inst_for_method (cfg, cmethod, fsig, args);
6185                 if (ins)
6186                         return ins;
6187         }
6188
6189         return mono_arch_emit_inst_for_method (cfg, cmethod, fsig, args);
6190 }
6191
6192 /*
6193  * This entry point could be used later for arbitrary method
6194  * redirection.
6195  */
6196 inline static MonoInst*
6197 mini_redirect_call (MonoCompile *cfg, MonoMethod *method,  
6198                                         MonoMethodSignature *signature, MonoInst **args, MonoInst *this_ins)
6199 {
6200         if (method->klass == mono_defaults.string_class) {
6201                 /* managed string allocation support */
6202                 if (strcmp (method->name, "InternalAllocateStr") == 0 && !(mono_profiler_events & MONO_PROFILE_ALLOCATIONS) && !(cfg->opt & MONO_OPT_SHARED)) {
6203                         MonoInst *iargs [2];
6204                         MonoVTable *vtable = mono_class_vtable (cfg->domain, method->klass);
6205                         MonoMethod *managed_alloc = NULL;
6206
6207                         g_assert (vtable); /*Should not fail since it System.String*/
6208 #ifndef MONO_CROSS_COMPILE
6209                         managed_alloc = mono_gc_get_managed_allocator (method->klass, FALSE, FALSE);
6210 #endif
6211                         if (!managed_alloc)
6212                                 return NULL;
6213                         EMIT_NEW_VTABLECONST (cfg, iargs [0], vtable);
6214                         iargs [1] = args [0];
6215                         return mono_emit_method_call (cfg, managed_alloc, iargs, this_ins);
6216                 }
6217         }
6218         return NULL;
6219 }
6220
6221 static void
6222 mono_save_args (MonoCompile *cfg, MonoMethodSignature *sig, MonoInst **sp)
6223 {
6224         MonoInst *store, *temp;
6225         int i;
6226
6227         for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
6228                 MonoType *argtype = (sig->hasthis && (i == 0)) ? type_from_stack_type (*sp) : sig->params [i - sig->hasthis];
6229
6230                 /*
6231                  * FIXME: We should use *args++ = sp [0], but that would mean the arg
6232                  * would be different than the MonoInst's used to represent arguments, and
6233                  * the ldelema implementation can't deal with that.
6234                  * Solution: When ldelema is used on an inline argument, create a var for 
6235                  * it, emit ldelema on that var, and emit the saving code below in
6236                  * inline_method () if needed.
6237                  */
6238                 temp = mono_compile_create_var (cfg, argtype, OP_LOCAL);
6239                 cfg->args [i] = temp;
6240                 /* This uses cfg->args [i] which is set by the preceeding line */
6241                 EMIT_NEW_ARGSTORE (cfg, store, i, *sp);
6242                 store->cil_code = sp [0]->cil_code;
6243                 sp++;
6244         }
6245 }
6246
6247 #define MONO_INLINE_CALLED_LIMITED_METHODS 1
6248 #define MONO_INLINE_CALLER_LIMITED_METHODS 1
6249
6250 #if (MONO_INLINE_CALLED_LIMITED_METHODS)
6251 static gboolean
6252 check_inline_called_method_name_limit (MonoMethod *called_method)
6253 {
6254         int strncmp_result;
6255         static const char *limit = NULL;
6256         
6257         if (limit == NULL) {
6258                 const char *limit_string = g_getenv ("MONO_INLINE_CALLED_METHOD_NAME_LIMIT");
6259
6260                 if (limit_string != NULL)
6261                         limit = limit_string;
6262                 else
6263                         limit = "";
6264         }
6265
6266         if (limit [0] != '\0') {
6267                 char *called_method_name = mono_method_full_name (called_method, TRUE);
6268
6269                 strncmp_result = strncmp (called_method_name, limit, strlen (limit));
6270                 g_free (called_method_name);
6271         
6272                 //return (strncmp_result <= 0);
6273                 return (strncmp_result == 0);
6274         } else {
6275                 return TRUE;
6276         }
6277 }
6278 #endif
6279
6280 #if (MONO_INLINE_CALLER_LIMITED_METHODS)
6281 static gboolean
6282 check_inline_caller_method_name_limit (MonoMethod *caller_method)
6283 {
6284         int strncmp_result;
6285         static const char *limit = NULL;
6286         
6287         if (limit == NULL) {
6288                 const char *limit_string = g_getenv ("MONO_INLINE_CALLER_METHOD_NAME_LIMIT");
6289                 if (limit_string != NULL) {
6290                         limit = limit_string;
6291                 } else {
6292                         limit = "";
6293                 }
6294         }
6295
6296         if (limit [0] != '\0') {
6297                 char *caller_method_name = mono_method_full_name (caller_method, TRUE);
6298
6299                 strncmp_result = strncmp (caller_method_name, limit, strlen (limit));
6300                 g_free (caller_method_name);
6301         
6302                 //return (strncmp_result <= 0);
6303                 return (strncmp_result == 0);
6304         } else {
6305                 return TRUE;
6306         }
6307 }
6308 #endif
6309
6310 static void
6311 emit_init_rvar (MonoCompile *cfg, int dreg, MonoType *rtype)
6312 {
6313         static double r8_0 = 0.0;
6314         static float r4_0 = 0.0;
6315         MonoInst *ins;
6316         int t;
6317
6318         rtype = mini_get_underlying_type (rtype);
6319         t = rtype->type;
6320
6321         if (rtype->byref) {
6322                 MONO_EMIT_NEW_PCONST (cfg, dreg, NULL);
6323         } else if (t >= MONO_TYPE_BOOLEAN && t <= MONO_TYPE_U4) {
6324                 MONO_EMIT_NEW_ICONST (cfg, dreg, 0);
6325         } else if (t == MONO_TYPE_I8 || t == MONO_TYPE_U8) {
6326                 MONO_EMIT_NEW_I8CONST (cfg, dreg, 0);
6327         } else if (cfg->r4fp && t == MONO_TYPE_R4) {
6328                 MONO_INST_NEW (cfg, ins, OP_R4CONST);
6329                 ins->type = STACK_R4;
6330                 ins->inst_p0 = (void*)&r4_0;
6331                 ins->dreg = dreg;
6332                 MONO_ADD_INS (cfg->cbb, ins);
6333         } else if (t == MONO_TYPE_R4 || t == MONO_TYPE_R8) {
6334                 MONO_INST_NEW (cfg, ins, OP_R8CONST);
6335                 ins->type = STACK_R8;
6336                 ins->inst_p0 = (void*)&r8_0;
6337                 ins->dreg = dreg;
6338                 MONO_ADD_INS (cfg->cbb, ins);
6339         } else if ((t == MONO_TYPE_VALUETYPE) || (t == MONO_TYPE_TYPEDBYREF) ||
6340                    ((t == MONO_TYPE_GENERICINST) && mono_type_generic_inst_is_valuetype (rtype))) {
6341                 MONO_EMIT_NEW_VZERO (cfg, dreg, mono_class_from_mono_type (rtype));
6342         } else if (((t == MONO_TYPE_VAR) || (t == MONO_TYPE_MVAR)) && mini_type_var_is_vt (rtype)) {
6343                 MONO_EMIT_NEW_VZERO (cfg, dreg, mono_class_from_mono_type (rtype));
6344         } else {
6345                 MONO_EMIT_NEW_PCONST (cfg, dreg, NULL);
6346         }
6347 }
6348
6349 static void
6350 emit_dummy_init_rvar (MonoCompile *cfg, int dreg, MonoType *rtype)
6351 {
6352         int t;
6353
6354         rtype = mini_get_underlying_type (rtype);
6355         t = rtype->type;
6356
6357         if (rtype->byref) {
6358                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_PCONST);
6359         } else if (t >= MONO_TYPE_BOOLEAN && t <= MONO_TYPE_U4) {
6360                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_ICONST);
6361         } else if (t == MONO_TYPE_I8 || t == MONO_TYPE_U8) {
6362                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_I8CONST);
6363         } else if (cfg->r4fp && t == MONO_TYPE_R4) {
6364                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_R4CONST);
6365         } else if (t == MONO_TYPE_R4 || t == MONO_TYPE_R8) {
6366                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_R8CONST);
6367         } else if ((t == MONO_TYPE_VALUETYPE) || (t == MONO_TYPE_TYPEDBYREF) ||
6368                    ((t == MONO_TYPE_GENERICINST) && mono_type_generic_inst_is_valuetype (rtype))) {
6369                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_VZERO);
6370         } else if (((t == MONO_TYPE_VAR) || (t == MONO_TYPE_MVAR)) && mini_type_var_is_vt (rtype)) {
6371                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_VZERO);
6372         } else {
6373                 emit_init_rvar (cfg, dreg, rtype);
6374         }
6375 }
6376
6377 /* If INIT is FALSE, emit dummy initialization statements to keep the IR valid */
6378 static void
6379 emit_init_local (MonoCompile *cfg, int local, MonoType *type, gboolean init)
6380 {
6381         MonoInst *var = cfg->locals [local];
6382         if (COMPILE_SOFT_FLOAT (cfg)) {
6383                 MonoInst *store;
6384                 int reg = alloc_dreg (cfg, (MonoStackType)var->type);
6385                 emit_init_rvar (cfg, reg, type);
6386                 EMIT_NEW_LOCSTORE (cfg, store, local, cfg->cbb->last_ins);
6387         } else {
6388                 if (init)
6389                         emit_init_rvar (cfg, var->dreg, type);
6390                 else
6391                         emit_dummy_init_rvar (cfg, var->dreg, type);
6392         }
6393 }
6394
6395 int
6396 mini_inline_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **sp, guchar *ip, guint real_offset, gboolean inline_always)
6397 {
6398         return inline_method (cfg, cmethod, fsig, sp, ip, real_offset, inline_always);
6399 }
6400
6401 /*
6402  * inline_method:
6403  *
6404  * Return the cost of inlining CMETHOD, or zero if it should not be inlined.
6405  */
6406 static int
6407 inline_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **sp,
6408                guchar *ip, guint real_offset, gboolean inline_always)
6409 {
6410         MonoError error;
6411         MonoInst *ins, *rvar = NULL;
6412         MonoMethodHeader *cheader;
6413         MonoBasicBlock *ebblock, *sbblock;
6414         int i, costs;
6415         MonoMethod *prev_inlined_method;
6416         MonoInst **prev_locals, **prev_args;
6417         MonoType **prev_arg_types;
6418         guint prev_real_offset;
6419         GHashTable *prev_cbb_hash;
6420         MonoBasicBlock **prev_cil_offset_to_bb;
6421         MonoBasicBlock *prev_cbb;
6422         const unsigned char *prev_ip;
6423         unsigned char *prev_cil_start;
6424         guint32 prev_cil_offset_to_bb_len;
6425         MonoMethod *prev_current_method;
6426         MonoGenericContext *prev_generic_context;
6427         gboolean ret_var_set, prev_ret_var_set, prev_disable_inline, virtual_ = FALSE;
6428
6429         g_assert (cfg->exception_type == MONO_EXCEPTION_NONE);
6430
6431 #if (MONO_INLINE_CALLED_LIMITED_METHODS)
6432         if ((! inline_always) && ! check_inline_called_method_name_limit (cmethod))
6433                 return 0;
6434 #endif
6435 #if (MONO_INLINE_CALLER_LIMITED_METHODS)
6436         if ((! inline_always) && ! check_inline_caller_method_name_limit (cfg->method))
6437                 return 0;
6438 #endif
6439
6440         if (!fsig)
6441                 fsig = mono_method_signature (cmethod);
6442
6443         if (cfg->verbose_level > 2)
6444                 printf ("INLINE START %p %s -> %s\n", cmethod,  mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
6445
6446         if (!cmethod->inline_info) {
6447                 cfg->stat_inlineable_methods++;
6448                 cmethod->inline_info = 1;
6449         }
6450
6451         /* allocate local variables */
6452         cheader = mono_method_get_header_checked (cmethod, &error);
6453         if (!cheader) {
6454                 if (inline_always) {
6455                         mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
6456                         mono_error_move (&cfg->error, &error);
6457                 } else {
6458                         mono_error_cleanup (&error);
6459                 }
6460                 return 0;
6461         }
6462
6463         /*Must verify before creating locals as it can cause the JIT to assert.*/
6464         if (mono_compile_is_broken (cfg, cmethod, FALSE)) {
6465                 mono_metadata_free_mh (cheader);
6466                 return 0;
6467         }
6468
6469         /* allocate space to store the return value */
6470         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
6471                 rvar = mono_compile_create_var (cfg, fsig->ret, OP_LOCAL);
6472         }
6473
6474         prev_locals = cfg->locals;
6475         cfg->locals = (MonoInst **)mono_mempool_alloc0 (cfg->mempool, cheader->num_locals * sizeof (MonoInst*));
6476         for (i = 0; i < cheader->num_locals; ++i)
6477                 cfg->locals [i] = mono_compile_create_var (cfg, cheader->locals [i], OP_LOCAL);
6478
6479         /* allocate start and end blocks */
6480         /* This is needed so if the inline is aborted, we can clean up */
6481         NEW_BBLOCK (cfg, sbblock);
6482         sbblock->real_offset = real_offset;
6483
6484         NEW_BBLOCK (cfg, ebblock);
6485         ebblock->block_num = cfg->num_bblocks++;
6486         ebblock->real_offset = real_offset;
6487
6488         prev_args = cfg->args;
6489         prev_arg_types = cfg->arg_types;
6490         prev_inlined_method = cfg->inlined_method;
6491         cfg->inlined_method = cmethod;
6492         cfg->ret_var_set = FALSE;
6493         cfg->inline_depth ++;
6494         prev_real_offset = cfg->real_offset;
6495         prev_cbb_hash = cfg->cbb_hash;
6496         prev_cil_offset_to_bb = cfg->cil_offset_to_bb;
6497         prev_cil_offset_to_bb_len = cfg->cil_offset_to_bb_len;
6498         prev_cil_start = cfg->cil_start;
6499         prev_ip = cfg->ip;
6500         prev_cbb = cfg->cbb;
6501         prev_current_method = cfg->current_method;
6502         prev_generic_context = cfg->generic_context;
6503         prev_ret_var_set = cfg->ret_var_set;
6504         prev_disable_inline = cfg->disable_inline;
6505
6506         if (ip && *ip == CEE_CALLVIRT && !(cmethod->flags & METHOD_ATTRIBUTE_STATIC))
6507                 virtual_ = TRUE;
6508
6509         costs = mono_method_to_ir (cfg, cmethod, sbblock, ebblock, rvar, sp, real_offset, virtual_);
6510
6511         ret_var_set = cfg->ret_var_set;
6512
6513         cfg->inlined_method = prev_inlined_method;
6514         cfg->real_offset = prev_real_offset;
6515         cfg->cbb_hash = prev_cbb_hash;
6516         cfg->cil_offset_to_bb = prev_cil_offset_to_bb;
6517         cfg->cil_offset_to_bb_len = prev_cil_offset_to_bb_len;
6518         cfg->cil_start = prev_cil_start;
6519         cfg->ip = prev_ip;
6520         cfg->locals = prev_locals;
6521         cfg->args = prev_args;
6522         cfg->arg_types = prev_arg_types;
6523         cfg->current_method = prev_current_method;
6524         cfg->generic_context = prev_generic_context;
6525         cfg->ret_var_set = prev_ret_var_set;
6526         cfg->disable_inline = prev_disable_inline;
6527         cfg->inline_depth --;
6528
6529         if ((costs >= 0 && costs < 60) || inline_always || (costs >= 0 && (cmethod->iflags & METHOD_IMPL_ATTRIBUTE_AGGRESSIVE_INLINING))) {
6530                 if (cfg->verbose_level > 2)
6531                         printf ("INLINE END %s -> %s\n", mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
6532
6533                 cfg->stat_inlined_methods++;
6534
6535                 /* always add some code to avoid block split failures */
6536                 MONO_INST_NEW (cfg, ins, OP_NOP);
6537                 MONO_ADD_INS (prev_cbb, ins);
6538
6539                 prev_cbb->next_bb = sbblock;
6540                 link_bblock (cfg, prev_cbb, sbblock);
6541
6542                 /* 
6543                  * Get rid of the begin and end bblocks if possible to aid local
6544                  * optimizations.
6545                  */
6546                 if (prev_cbb->out_count == 1)
6547                         mono_merge_basic_blocks (cfg, prev_cbb, sbblock);
6548
6549                 if ((prev_cbb->out_count == 1) && (prev_cbb->out_bb [0]->in_count == 1) && (prev_cbb->out_bb [0] != ebblock))
6550                         mono_merge_basic_blocks (cfg, prev_cbb, prev_cbb->out_bb [0]);
6551
6552                 if ((ebblock->in_count == 1) && ebblock->in_bb [0]->out_count == 1) {
6553                         MonoBasicBlock *prev = ebblock->in_bb [0];
6554
6555                         if (prev->next_bb == ebblock) {
6556                                 mono_merge_basic_blocks (cfg, prev, ebblock);
6557                                 cfg->cbb = prev;
6558                                 if ((prev_cbb->out_count == 1) && (prev_cbb->out_bb [0]->in_count == 1) && (prev_cbb->out_bb [0] == prev)) {
6559                                         mono_merge_basic_blocks (cfg, prev_cbb, prev);
6560                                         cfg->cbb = prev_cbb;
6561                                 }
6562                         } else {
6563                                 /* There could be a bblock after 'prev', and making 'prev' the current bb could cause problems */
6564                                 cfg->cbb = ebblock;
6565                         }
6566                 } else {
6567                         /* 
6568                          * Its possible that the rvar is set in some prev bblock, but not in others.
6569                          * (#1835).
6570                          */
6571                         if (rvar) {
6572                                 MonoBasicBlock *bb;
6573
6574                                 for (i = 0; i < ebblock->in_count; ++i) {
6575                                         bb = ebblock->in_bb [i];
6576
6577                                         if (bb->last_ins && bb->last_ins->opcode == OP_NOT_REACHED) {
6578                                                 cfg->cbb = bb;
6579
6580                                                 emit_init_rvar (cfg, rvar->dreg, fsig->ret);
6581                                         }
6582                                 }
6583                         }
6584
6585                         cfg->cbb = ebblock;
6586                 }
6587
6588                 if (rvar) {
6589                         /*
6590                          * If the inlined method contains only a throw, then the ret var is not 
6591                          * set, so set it to a dummy value.
6592                          */
6593                         if (!ret_var_set)
6594                                 emit_init_rvar (cfg, rvar->dreg, fsig->ret);
6595
6596                         EMIT_NEW_TEMPLOAD (cfg, ins, rvar->inst_c0);
6597                         *sp++ = ins;
6598                 }
6599                 cfg->headers_to_free = g_slist_prepend_mempool (cfg->mempool, cfg->headers_to_free, cheader);
6600                 return costs + 1;
6601         } else {
6602                 if (cfg->verbose_level > 2)
6603                         printf ("INLINE ABORTED %s (cost %d)\n", mono_method_full_name (cmethod, TRUE), costs);
6604                 cfg->exception_type = MONO_EXCEPTION_NONE;
6605
6606                 /* This gets rid of the newly added bblocks */
6607                 cfg->cbb = prev_cbb;
6608         }
6609         cfg->headers_to_free = g_slist_prepend_mempool (cfg->mempool, cfg->headers_to_free, cheader);
6610         return 0;
6611 }
6612
6613 /*
6614  * Some of these comments may well be out-of-date.
6615  * Design decisions: we do a single pass over the IL code (and we do bblock 
6616  * splitting/merging in the few cases when it's required: a back jump to an IL
6617  * address that was not already seen as bblock starting point).
6618  * Code is validated as we go (full verification is still better left to metadata/verify.c).
6619  * Complex operations are decomposed in simpler ones right away. We need to let the 
6620  * arch-specific code peek and poke inside this process somehow (except when the 
6621  * optimizations can take advantage of the full semantic info of coarse opcodes).
6622  * All the opcodes of the form opcode.s are 'normalized' to opcode.
6623  * MonoInst->opcode initially is the IL opcode or some simplification of that 
6624  * (OP_LOAD, OP_STORE). The arch-specific code may rearrange it to an arch-specific 
6625  * opcode with value bigger than OP_LAST.
6626  * At this point the IR can be handed over to an interpreter, a dumb code generator
6627  * or to the optimizing code generator that will translate it to SSA form.
6628  *
6629  * Profiling directed optimizations.
6630  * We may compile by default with few or no optimizations and instrument the code
6631  * or the user may indicate what methods to optimize the most either in a config file
6632  * or through repeated runs where the compiler applies offline the optimizations to 
6633  * each method and then decides if it was worth it.
6634  */
6635
6636 #define CHECK_TYPE(ins) if (!(ins)->type) UNVERIFIED
6637 #define CHECK_STACK(num) if ((sp - stack_start) < (num)) UNVERIFIED
6638 #define CHECK_STACK_OVF(num) if (((sp - stack_start) + (num)) > header->max_stack) UNVERIFIED
6639 #define CHECK_ARG(num) if ((unsigned)(num) >= (unsigned)num_args) UNVERIFIED
6640 #define CHECK_LOCAL(num) if ((unsigned)(num) >= (unsigned)header->num_locals) UNVERIFIED
6641 #define CHECK_OPSIZE(size) if (ip + size > end) UNVERIFIED
6642 #define CHECK_UNVERIFIABLE(cfg) if (cfg->unverifiable) UNVERIFIED
6643 #define CHECK_TYPELOAD(klass) if (!(klass) || mono_class_has_failure (klass)) TYPE_LOAD_ERROR ((klass))
6644
6645 /* offset from br.s -> br like opcodes */
6646 #define BIG_BRANCH_OFFSET 13
6647
6648 static gboolean
6649 ip_in_bb (MonoCompile *cfg, MonoBasicBlock *bb, const guint8* ip)
6650 {
6651         MonoBasicBlock *b = cfg->cil_offset_to_bb [ip - cfg->cil_start];
6652
6653         return b == NULL || b == bb;
6654 }
6655
6656 static int
6657 get_basic_blocks (MonoCompile *cfg, MonoMethodHeader* header, guint real_offset, unsigned char *start, unsigned char *end, unsigned char **pos)
6658 {
6659         unsigned char *ip = start;
6660         unsigned char *target;
6661         int i;
6662         guint cli_addr;
6663         MonoBasicBlock *bblock;
6664         const MonoOpcode *opcode;
6665
6666         while (ip < end) {
6667                 cli_addr = ip - start;
6668                 i = mono_opcode_value ((const guint8 **)&ip, end);
6669                 if (i < 0)
6670                         UNVERIFIED;
6671                 opcode = &mono_opcodes [i];
6672                 switch (opcode->argument) {
6673                 case MonoInlineNone:
6674                         ip++; 
6675                         break;
6676                 case MonoInlineString:
6677                 case MonoInlineType:
6678                 case MonoInlineField:
6679                 case MonoInlineMethod:
6680                 case MonoInlineTok:
6681                 case MonoInlineSig:
6682                 case MonoShortInlineR:
6683                 case MonoInlineI:
6684                         ip += 5;
6685                         break;
6686                 case MonoInlineVar:
6687                         ip += 3;
6688                         break;
6689                 case MonoShortInlineVar:
6690                 case MonoShortInlineI:
6691                         ip += 2;
6692                         break;
6693                 case MonoShortInlineBrTarget:
6694                         target = start + cli_addr + 2 + (signed char)ip [1];
6695                         GET_BBLOCK (cfg, bblock, target);
6696                         ip += 2;
6697                         if (ip < end)
6698                                 GET_BBLOCK (cfg, bblock, ip);
6699                         break;
6700                 case MonoInlineBrTarget:
6701                         target = start + cli_addr + 5 + (gint32)read32 (ip + 1);
6702                         GET_BBLOCK (cfg, bblock, target);
6703                         ip += 5;
6704                         if (ip < end)
6705                                 GET_BBLOCK (cfg, bblock, ip);
6706                         break;
6707                 case MonoInlineSwitch: {
6708                         guint32 n = read32 (ip + 1);
6709                         guint32 j;
6710                         ip += 5;
6711                         cli_addr += 5 + 4 * n;
6712                         target = start + cli_addr;
6713                         GET_BBLOCK (cfg, bblock, target);
6714                         
6715                         for (j = 0; j < n; ++j) {
6716                                 target = start + cli_addr + (gint32)read32 (ip);
6717                                 GET_BBLOCK (cfg, bblock, target);
6718                                 ip += 4;
6719                         }
6720                         break;
6721                 }
6722                 case MonoInlineR:
6723                 case MonoInlineI8:
6724                         ip += 9;
6725                         break;
6726                 default:
6727                         g_assert_not_reached ();
6728                 }
6729
6730                 if (i == CEE_THROW) {
6731                         unsigned char *bb_start = ip - 1;
6732                         
6733                         /* Find the start of the bblock containing the throw */
6734                         bblock = NULL;
6735                         while ((bb_start >= start) && !bblock) {
6736                                 bblock = cfg->cil_offset_to_bb [(bb_start) - start];
6737                                 bb_start --;
6738                         }
6739                         if (bblock)
6740                                 bblock->out_of_line = 1;
6741                 }
6742         }
6743         return 0;
6744 unverified:
6745 exception_exit:
6746         *pos = ip;
6747         return 1;
6748 }
6749
6750 static inline MonoMethod *
6751 mini_get_method_allow_open (MonoMethod *m, guint32 token, MonoClass *klass, MonoGenericContext *context, MonoError *error)
6752 {
6753         MonoMethod *method;
6754
6755         error_init (error);
6756
6757         if (m->wrapper_type != MONO_WRAPPER_NONE) {
6758                 method = (MonoMethod *)mono_method_get_wrapper_data (m, token);
6759                 if (context) {
6760                         method = mono_class_inflate_generic_method_checked (method, context, error);
6761                 }
6762         } else {
6763                 method = mono_get_method_checked (m->klass->image, token, klass, context, error);
6764         }
6765
6766         return method;
6767 }
6768
6769 static inline MonoMethod *
6770 mini_get_method (MonoCompile *cfg, MonoMethod *m, guint32 token, MonoClass *klass, MonoGenericContext *context)
6771 {
6772         MonoError error;
6773         MonoMethod *method = mini_get_method_allow_open (m, token, klass, context, cfg ? &cfg->error : &error);
6774
6775         if (method && cfg && !cfg->gshared && mono_class_is_open_constructed_type (&method->klass->byval_arg)) {
6776                 mono_error_set_bad_image (&cfg->error, cfg->method->klass->image, "Method with open type while not compiling gshared");
6777                 method = NULL;
6778         }
6779
6780         if (!method && !cfg)
6781                 mono_error_cleanup (&error); /* FIXME don't swallow the error */
6782
6783         return method;
6784 }
6785
6786 static inline MonoClass*
6787 mini_get_class (MonoMethod *method, guint32 token, MonoGenericContext *context)
6788 {
6789         MonoError error;
6790         MonoClass *klass;
6791
6792         if (method->wrapper_type != MONO_WRAPPER_NONE) {
6793                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
6794                 if (context) {
6795                         klass = mono_class_inflate_generic_class_checked (klass, context, &error);
6796                         mono_error_cleanup (&error); /* FIXME don't swallow the error */
6797                 }
6798         } else {
6799                 klass = mono_class_get_and_inflate_typespec_checked (method->klass->image, token, context, &error);
6800                 mono_error_cleanup (&error); /* FIXME don't swallow the error */
6801         }
6802         if (klass)
6803                 mono_class_init (klass);
6804         return klass;
6805 }
6806
6807 static inline MonoMethodSignature*
6808 mini_get_signature (MonoMethod *method, guint32 token, MonoGenericContext *context, MonoError *error)
6809 {
6810         MonoMethodSignature *fsig;
6811
6812         error_init (error);
6813         if (method->wrapper_type != MONO_WRAPPER_NONE) {
6814                 fsig = (MonoMethodSignature *)mono_method_get_wrapper_data (method, token);
6815         } else {
6816                 fsig = mono_metadata_parse_signature_checked (method->klass->image, token, error);
6817                 return_val_if_nok (error, NULL);
6818         }
6819         if (context) {
6820                 fsig = mono_inflate_generic_signature(fsig, context, error);
6821         }
6822         return fsig;
6823 }
6824
6825 static MonoMethod*
6826 throw_exception (void)
6827 {
6828         static MonoMethod *method = NULL;
6829
6830         if (!method) {
6831                 MonoSecurityManager *secman = mono_security_manager_get_methods ();
6832                 method = mono_class_get_method_from_name (secman->securitymanager, "ThrowException", 1);
6833         }
6834         g_assert (method);
6835         return method;
6836 }
6837
6838 static void
6839 emit_throw_exception (MonoCompile *cfg, MonoException *ex)
6840 {
6841         MonoMethod *thrower = throw_exception ();
6842         MonoInst *args [1];
6843
6844         EMIT_NEW_PCONST (cfg, args [0], ex);
6845         mono_emit_method_call (cfg, thrower, args, NULL);
6846 }
6847
6848 /*
6849  * Return the original method is a wrapper is specified. We can only access 
6850  * the custom attributes from the original method.
6851  */
6852 static MonoMethod*
6853 get_original_method (MonoMethod *method)
6854 {
6855         if (method->wrapper_type == MONO_WRAPPER_NONE)
6856                 return method;
6857
6858         /* native code (which is like Critical) can call any managed method XXX FIXME XXX to validate all usages */
6859         if (method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED)
6860                 return NULL;
6861
6862         /* in other cases we need to find the original method */
6863         return mono_marshal_method_from_wrapper (method);
6864 }
6865
6866 static void
6867 ensure_method_is_allowed_to_access_field (MonoCompile *cfg, MonoMethod *caller, MonoClassField *field)
6868 {
6869         /* we can't get the coreclr security level on wrappers since they don't have the attributes */
6870         MonoException *ex = mono_security_core_clr_is_field_access_allowed (get_original_method (caller), field);
6871         if (ex)
6872                 emit_throw_exception (cfg, ex);
6873 }
6874
6875 static void
6876 ensure_method_is_allowed_to_call_method (MonoCompile *cfg, MonoMethod *caller, MonoMethod *callee)
6877 {
6878         /* we can't get the coreclr security level on wrappers since they don't have the attributes */
6879         MonoException *ex = mono_security_core_clr_is_call_allowed (get_original_method (caller), callee);
6880         if (ex)
6881                 emit_throw_exception (cfg, ex);
6882 }
6883
6884 /*
6885  * Check that the IL instructions at ip are the array initialization
6886  * sequence and return the pointer to the data and the size.
6887  */
6888 static const char*
6889 initialize_array_data (MonoMethod *method, gboolean aot, unsigned char *ip, MonoClass *klass, guint32 len, int *out_size, guint32 *out_field_token)
6890 {
6891         /*
6892          * newarr[System.Int32]
6893          * dup
6894          * ldtoken field valuetype ...
6895          * call void class [mscorlib]System.Runtime.CompilerServices.RuntimeHelpers::InitializeArray(class [mscorlib]System.Array, valuetype [mscorlib]System.RuntimeFieldHandle)
6896          */
6897         if (ip [0] == CEE_DUP && ip [1] == CEE_LDTOKEN && ip [5] == 0x4 && ip [6] == CEE_CALL) {
6898                 MonoError error;
6899                 guint32 token = read32 (ip + 7);
6900                 guint32 field_token = read32 (ip + 2);
6901                 guint32 field_index = field_token & 0xffffff;
6902                 guint32 rva;
6903                 const char *data_ptr;
6904                 int size = 0;
6905                 MonoMethod *cmethod;
6906                 MonoClass *dummy_class;
6907                 MonoClassField *field = mono_field_from_token_checked (method->klass->image, field_token, &dummy_class, NULL, &error);
6908                 int dummy_align;
6909
6910                 if (!field) {
6911                         mono_error_cleanup (&error); /* FIXME don't swallow the error */
6912                         return NULL;
6913                 }
6914
6915                 *out_field_token = field_token;
6916
6917                 cmethod = mini_get_method (NULL, method, token, NULL, NULL);
6918                 if (!cmethod)
6919                         return NULL;
6920                 if (strcmp (cmethod->name, "InitializeArray") || strcmp (cmethod->klass->name, "RuntimeHelpers") || cmethod->klass->image != mono_defaults.corlib)
6921                         return NULL;
6922                 switch (mini_get_underlying_type (&klass->byval_arg)->type) {
6923                 case MONO_TYPE_I1:
6924                 case MONO_TYPE_U1:
6925                         size = 1; break;
6926                 /* we need to swap on big endian, so punt. Should we handle R4 and R8 as well? */
6927 #if TARGET_BYTE_ORDER == G_LITTLE_ENDIAN
6928                 case MONO_TYPE_I2:
6929                 case MONO_TYPE_U2:
6930                         size = 2; break;
6931                 case MONO_TYPE_I4:
6932                 case MONO_TYPE_U4:
6933                 case MONO_TYPE_R4:
6934                         size = 4; break;
6935                 case MONO_TYPE_R8:
6936                 case MONO_TYPE_I8:
6937                 case MONO_TYPE_U8:
6938                         size = 8; break;
6939 #endif
6940                 default:
6941                         return NULL;
6942                 }
6943                 size *= len;
6944                 if (size > mono_type_size (field->type, &dummy_align))
6945                     return NULL;
6946                 *out_size = size;
6947                 /*g_print ("optimized in %s: size: %d, numelems: %d\n", method->name, size, newarr->inst_newa_len->inst_c0);*/
6948                 if (!image_is_dynamic (method->klass->image)) {
6949                         field_index = read32 (ip + 2) & 0xffffff;
6950                         mono_metadata_field_info (method->klass->image, field_index - 1, NULL, &rva, NULL);
6951                         data_ptr = mono_image_rva_map (method->klass->image, rva);
6952                         /*g_print ("field: 0x%08x, rva: %d, rva_ptr: %p\n", read32 (ip + 2), rva, data_ptr);*/
6953                         /* for aot code we do the lookup on load */
6954                         if (aot && data_ptr)
6955                                 return (const char *)GUINT_TO_POINTER (rva);
6956                 } else {
6957                         /*FIXME is it possible to AOT a SRE assembly not meant to be saved? */ 
6958                         g_assert (!aot);
6959                         data_ptr = mono_field_get_data (field);
6960                 }
6961                 return data_ptr;
6962         }
6963         return NULL;
6964 }
6965
6966 static void
6967 set_exception_type_from_invalid_il (MonoCompile *cfg, MonoMethod *method, unsigned char *ip)
6968 {
6969         MonoError error;
6970         char *method_fname = mono_method_full_name (method, TRUE);
6971         char *method_code;
6972         MonoMethodHeader *header = mono_method_get_header_checked (method, &error);
6973
6974         if (!header) {
6975                 method_code = g_strdup_printf ("could not parse method body due to %s", mono_error_get_message (&error));
6976                 mono_error_cleanup (&error);
6977         } else if (header->code_size == 0)
6978                 method_code = g_strdup ("method body is empty.");
6979         else
6980                 method_code = mono_disasm_code_one (NULL, method, ip, NULL);
6981         mono_cfg_set_exception_invalid_program (cfg, g_strdup_printf ("Invalid IL code in %s: %s\n", method_fname, method_code));
6982         g_free (method_fname);
6983         g_free (method_code);
6984         cfg->headers_to_free = g_slist_prepend_mempool (cfg->mempool, cfg->headers_to_free, header);
6985 }
6986
6987 static void
6988 emit_stloc_ir (MonoCompile *cfg, MonoInst **sp, MonoMethodHeader *header, int n)
6989 {
6990         MonoInst *ins;
6991         guint32 opcode = mono_type_to_regmove (cfg, header->locals [n]);
6992         if ((opcode == OP_MOVE) && cfg->cbb->last_ins == sp [0]  &&
6993                         ((sp [0]->opcode == OP_ICONST) || (sp [0]->opcode == OP_I8CONST))) {
6994                 /* Optimize reg-reg moves away */
6995                 /* 
6996                  * Can't optimize other opcodes, since sp[0] might point to
6997                  * the last ins of a decomposed opcode.
6998                  */
6999                 sp [0]->dreg = (cfg)->locals [n]->dreg;
7000         } else {
7001                 EMIT_NEW_LOCSTORE (cfg, ins, n, *sp);
7002         }
7003 }
7004
7005 /*
7006  * ldloca inhibits many optimizations so try to get rid of it in common
7007  * cases.
7008  */
7009 static inline unsigned char *
7010 emit_optimized_ldloca_ir (MonoCompile *cfg, unsigned char *ip, unsigned char *end, int size)
7011 {
7012         int local, token;
7013         MonoClass *klass;
7014         MonoType *type;
7015
7016         if (size == 1) {
7017                 local = ip [1];
7018                 ip += 2;
7019         } else {
7020                 local = read16 (ip + 2);
7021                 ip += 4;
7022         }
7023         
7024         if (ip + 6 < end && (ip [0] == CEE_PREFIX1) && (ip [1] == CEE_INITOBJ) && ip_in_bb (cfg, cfg->cbb, ip + 1)) {
7025                 /* From the INITOBJ case */
7026                 token = read32 (ip + 2);
7027                 klass = mini_get_class (cfg->current_method, token, cfg->generic_context);
7028                 CHECK_TYPELOAD (klass);
7029                 type = mini_get_underlying_type (&klass->byval_arg);
7030                 emit_init_local (cfg, local, type, TRUE);
7031                 return ip + 6;
7032         }
7033  exception_exit:
7034         return NULL;
7035 }
7036
7037 static MonoInst*
7038 emit_llvmonly_virtual_call (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, int context_used, MonoInst **sp)
7039 {
7040         MonoInst *icall_args [16];
7041         MonoInst *call_target, *ins, *vtable_ins;
7042         int arg_reg, this_reg, vtable_reg;
7043         gboolean is_iface = mono_class_is_interface (cmethod->klass);
7044         gboolean is_gsharedvt = cfg->gsharedvt && mini_is_gsharedvt_variable_signature (fsig);
7045         gboolean variant_iface = FALSE;
7046         guint32 slot;
7047         int offset;
7048         gboolean special_array_interface = cmethod->klass->is_array_special_interface;
7049
7050         /*
7051          * In llvm-only mode, vtables contain function descriptors instead of
7052          * method addresses/trampolines.
7053          */
7054         MONO_EMIT_NULL_CHECK (cfg, sp [0]->dreg);
7055
7056         if (is_iface)
7057                 slot = mono_method_get_imt_slot (cmethod);
7058         else
7059                 slot = mono_method_get_vtable_index (cmethod);
7060
7061         this_reg = sp [0]->dreg;
7062
7063         if (is_iface && mono_class_has_variant_generic_params (cmethod->klass))
7064                 variant_iface = TRUE;
7065
7066         if (!fsig->generic_param_count && !is_iface && !is_gsharedvt) {
7067                 /*
7068                  * The simplest case, a normal virtual call.
7069                  */
7070                 int slot_reg = alloc_preg (cfg);
7071                 int addr_reg = alloc_preg (cfg);
7072                 int arg_reg = alloc_preg (cfg);
7073                 MonoBasicBlock *non_null_bb;
7074
7075                 vtable_reg = alloc_preg (cfg);
7076                 EMIT_NEW_LOAD_MEMBASE (cfg, vtable_ins, OP_LOAD_MEMBASE, vtable_reg, this_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
7077                 offset = MONO_STRUCT_OFFSET (MonoVTable, vtable) + (slot * SIZEOF_VOID_P);
7078
7079                 /* Load the vtable slot, which contains a function descriptor. */
7080                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, slot_reg, vtable_reg, offset);
7081
7082                 NEW_BBLOCK (cfg, non_null_bb);
7083
7084                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, slot_reg, 0);
7085                 cfg->cbb->last_ins->flags |= MONO_INST_LIKELY;
7086                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, non_null_bb);
7087
7088                 /* Slow path */
7089                 // FIXME: Make the wrapper use the preserveall cconv
7090                 // FIXME: Use one icall per slot for small slot numbers ?
7091                 icall_args [0] = vtable_ins;
7092                 EMIT_NEW_ICONST (cfg, icall_args [1], slot);
7093                 /* Make the icall return the vtable slot value to save some code space */
7094                 ins = mono_emit_jit_icall (cfg, mono_init_vtable_slot, icall_args);
7095                 ins->dreg = slot_reg;
7096                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, non_null_bb);
7097
7098                 /* Fastpath */
7099                 MONO_START_BB (cfg, non_null_bb);
7100                 /* Load the address + arg from the vtable slot */
7101                 EMIT_NEW_LOAD_MEMBASE (cfg, call_target, OP_LOAD_MEMBASE, addr_reg, slot_reg, 0);
7102                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, arg_reg, slot_reg, SIZEOF_VOID_P);
7103
7104                 return emit_extra_arg_calli (cfg, fsig, sp, arg_reg, call_target);
7105         }
7106
7107         if (!fsig->generic_param_count && is_iface && !variant_iface && !is_gsharedvt && !special_array_interface) {
7108                 /*
7109                  * A simple interface call
7110                  *
7111                  * We make a call through an imt slot to obtain the function descriptor we need to call.
7112                  * The imt slot contains a function descriptor for a runtime function + arg.
7113                  */
7114                 int slot_reg = alloc_preg (cfg);
7115                 int addr_reg = alloc_preg (cfg);
7116                 int arg_reg = alloc_preg (cfg);
7117                 MonoInst *thunk_addr_ins, *thunk_arg_ins, *ftndesc_ins;
7118
7119                 vtable_reg = alloc_preg (cfg);
7120                 EMIT_NEW_LOAD_MEMBASE (cfg, vtable_ins, OP_LOAD_MEMBASE, vtable_reg, this_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
7121                 offset = ((gint32)slot - MONO_IMT_SIZE) * SIZEOF_VOID_P;
7122
7123                 /*
7124                  * The slot is already initialized when the vtable is created so there is no need
7125                  * to check it here.
7126                  */
7127
7128                 /* Load the imt slot, which contains a function descriptor. */
7129                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, slot_reg, vtable_reg, offset);
7130
7131                 /* Load the address + arg of the imt thunk from the imt slot */
7132                 EMIT_NEW_LOAD_MEMBASE (cfg, thunk_addr_ins, OP_LOAD_MEMBASE, addr_reg, slot_reg, 0);
7133                 EMIT_NEW_LOAD_MEMBASE (cfg, thunk_arg_ins, OP_LOAD_MEMBASE, arg_reg, slot_reg, SIZEOF_VOID_P);
7134                 /*
7135                  * IMT thunks in llvm-only mode are C functions which take an info argument
7136                  * plus the imt method and return the ftndesc to call.
7137                  */
7138                 icall_args [0] = thunk_arg_ins;
7139                 icall_args [1] = emit_get_rgctx_method (cfg, context_used,
7140                                                                                                 cmethod, MONO_RGCTX_INFO_METHOD);
7141                 ftndesc_ins = mono_emit_calli (cfg, helper_sig_llvmonly_imt_trampoline, icall_args, thunk_addr_ins, NULL, NULL);
7142
7143                 return emit_llvmonly_calli (cfg, fsig, sp, ftndesc_ins);
7144         }
7145
7146         if ((fsig->generic_param_count || variant_iface || special_array_interface) && !is_gsharedvt) {
7147                 /*
7148                  * This is similar to the interface case, the vtable slot points to an imt thunk which is
7149                  * dynamically extended as more instantiations are discovered.
7150                  * This handles generic virtual methods both on classes and interfaces.
7151                  */
7152                 int slot_reg = alloc_preg (cfg);
7153                 int addr_reg = alloc_preg (cfg);
7154                 int arg_reg = alloc_preg (cfg);
7155                 int ftndesc_reg = alloc_preg (cfg);
7156                 MonoInst *thunk_addr_ins, *thunk_arg_ins, *ftndesc_ins;
7157                 MonoBasicBlock *slowpath_bb, *end_bb;
7158
7159                 NEW_BBLOCK (cfg, slowpath_bb);
7160                 NEW_BBLOCK (cfg, end_bb);
7161
7162                 vtable_reg = alloc_preg (cfg);
7163                 EMIT_NEW_LOAD_MEMBASE (cfg, vtable_ins, OP_LOAD_MEMBASE, vtable_reg, this_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
7164                 if (is_iface)
7165                         offset = ((gint32)slot - MONO_IMT_SIZE) * SIZEOF_VOID_P;
7166                 else
7167                         offset = MONO_STRUCT_OFFSET (MonoVTable, vtable) + (slot * SIZEOF_VOID_P);
7168
7169                 /* Load the slot, which contains a function descriptor. */
7170                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, slot_reg, vtable_reg, offset);
7171
7172                 /* These slots are not initialized, so fall back to the slow path until they are initialized */
7173                 /* That happens when mono_method_add_generic_virtual_invocation () creates an IMT thunk */
7174                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, slot_reg, 0);
7175                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, slowpath_bb);
7176
7177                 /* Fastpath */
7178                 /* Same as with iface calls */
7179                 EMIT_NEW_LOAD_MEMBASE (cfg, thunk_addr_ins, OP_LOAD_MEMBASE, addr_reg, slot_reg, 0);
7180                 EMIT_NEW_LOAD_MEMBASE (cfg, thunk_arg_ins, OP_LOAD_MEMBASE, arg_reg, slot_reg, SIZEOF_VOID_P);
7181                 icall_args [0] = thunk_arg_ins;
7182                 icall_args [1] = emit_get_rgctx_method (cfg, context_used,
7183                                                                                                 cmethod, MONO_RGCTX_INFO_METHOD);
7184                 ftndesc_ins = mono_emit_calli (cfg, helper_sig_llvmonly_imt_trampoline, icall_args, thunk_addr_ins, NULL, NULL);
7185                 ftndesc_ins->dreg = ftndesc_reg;
7186                 /*
7187                  * Unlike normal iface calls, these imt thunks can return NULL, i.e. when they are passed an instantiation
7188                  * they don't know about yet. Fall back to the slowpath in that case.
7189                  */
7190                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, ftndesc_reg, 0);
7191                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, slowpath_bb);
7192
7193                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
7194
7195                 /* Slowpath */
7196                 MONO_START_BB (cfg, slowpath_bb);
7197                 icall_args [0] = vtable_ins;
7198                 EMIT_NEW_ICONST (cfg, icall_args [1], slot);
7199                 icall_args [2] = emit_get_rgctx_method (cfg, context_used,
7200                                                                                                 cmethod, MONO_RGCTX_INFO_METHOD);
7201                 if (is_iface)
7202                         ftndesc_ins = mono_emit_jit_icall (cfg, mono_resolve_generic_virtual_iface_call, icall_args);
7203                 else
7204                         ftndesc_ins = mono_emit_jit_icall (cfg, mono_resolve_generic_virtual_call, icall_args);
7205                 ftndesc_ins->dreg = ftndesc_reg;
7206                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
7207
7208                 /* Common case */
7209                 MONO_START_BB (cfg, end_bb);
7210                 return emit_llvmonly_calli (cfg, fsig, sp, ftndesc_ins);
7211         }
7212
7213         /*
7214          * Non-optimized cases
7215          */
7216         icall_args [0] = sp [0];
7217         EMIT_NEW_ICONST (cfg, icall_args [1], slot);
7218
7219         icall_args [2] = emit_get_rgctx_method (cfg, context_used,
7220                                                                                         cmethod, MONO_RGCTX_INFO_METHOD);
7221
7222         arg_reg = alloc_preg (cfg);
7223         MONO_EMIT_NEW_PCONST (cfg, arg_reg, NULL);
7224         EMIT_NEW_VARLOADA_VREG (cfg, icall_args [3], arg_reg, &mono_defaults.int_class->byval_arg);
7225
7226         g_assert (is_gsharedvt);
7227         if (is_iface)
7228                 call_target = mono_emit_jit_icall (cfg, mono_resolve_iface_call_gsharedvt, icall_args);
7229         else
7230                 call_target = mono_emit_jit_icall (cfg, mono_resolve_vcall_gsharedvt, icall_args);
7231
7232         /*
7233          * Pass the extra argument even if the callee doesn't receive it, most
7234          * calling conventions allow this.
7235          */
7236         return emit_extra_arg_calli (cfg, fsig, sp, arg_reg, call_target);
7237 }
7238
7239 static gboolean
7240 is_exception_class (MonoClass *klass)
7241 {
7242         while (klass) {
7243                 if (klass == mono_defaults.exception_class)
7244                         return TRUE;
7245                 klass = klass->parent;
7246         }
7247         return FALSE;
7248 }
7249
7250 /*
7251  * is_jit_optimizer_disabled:
7252  *
7253  *   Determine whenever M's assembly has a DebuggableAttribute with the
7254  * IsJITOptimizerDisabled flag set.
7255  */
7256 static gboolean
7257 is_jit_optimizer_disabled (MonoMethod *m)
7258 {
7259         MonoError error;
7260         MonoAssembly *ass = m->klass->image->assembly;
7261         MonoCustomAttrInfo* attrs;
7262         MonoClass *klass;
7263         int i;
7264         gboolean val = FALSE;
7265
7266         g_assert (ass);
7267         if (ass->jit_optimizer_disabled_inited)
7268                 return ass->jit_optimizer_disabled;
7269
7270         klass = mono_class_try_get_debuggable_attribute_class ();
7271
7272         if (!klass) {
7273                 /* Linked away */
7274                 ass->jit_optimizer_disabled = FALSE;
7275                 mono_memory_barrier ();
7276                 ass->jit_optimizer_disabled_inited = TRUE;
7277                 return FALSE;
7278         }
7279
7280         attrs = mono_custom_attrs_from_assembly_checked (ass, FALSE, &error);
7281         mono_error_cleanup (&error); /* FIXME don't swallow the error */
7282         if (attrs) {
7283                 for (i = 0; i < attrs->num_attrs; ++i) {
7284                         MonoCustomAttrEntry *attr = &attrs->attrs [i];
7285                         const gchar *p;
7286                         MonoMethodSignature *sig;
7287
7288                         if (!attr->ctor || attr->ctor->klass != klass)
7289                                 continue;
7290                         /* Decode the attribute. See reflection.c */
7291                         p = (const char*)attr->data;
7292                         g_assert (read16 (p) == 0x0001);
7293                         p += 2;
7294
7295                         // FIXME: Support named parameters
7296                         sig = mono_method_signature (attr->ctor);
7297                         if (sig->param_count != 2 || sig->params [0]->type != MONO_TYPE_BOOLEAN || sig->params [1]->type != MONO_TYPE_BOOLEAN)
7298                                 continue;
7299                         /* Two boolean arguments */
7300                         p ++;
7301                         val = *p;
7302                 }
7303                 mono_custom_attrs_free (attrs);
7304         }
7305
7306         ass->jit_optimizer_disabled = val;
7307         mono_memory_barrier ();
7308         ass->jit_optimizer_disabled_inited = TRUE;
7309
7310         return val;
7311 }
7312
7313 static gboolean
7314 is_supported_tail_call (MonoCompile *cfg, MonoMethod *method, MonoMethod *cmethod, MonoMethodSignature *fsig, int call_opcode)
7315 {
7316         gboolean supported_tail_call;
7317         int i;
7318
7319         supported_tail_call = mono_arch_tail_call_supported (cfg, mono_method_signature (method), mono_method_signature (cmethod));
7320
7321         for (i = 0; i < fsig->param_count; ++i) {
7322                 if (fsig->params [i]->byref || fsig->params [i]->type == MONO_TYPE_PTR || fsig->params [i]->type == MONO_TYPE_FNPTR)
7323                         /* These can point to the current method's stack */
7324                         supported_tail_call = FALSE;
7325         }
7326         if (fsig->hasthis && cmethod->klass->valuetype)
7327                 /* this might point to the current method's stack */
7328                 supported_tail_call = FALSE;
7329         if (cmethod->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)
7330                 supported_tail_call = FALSE;
7331         if (cfg->method->save_lmf)
7332                 supported_tail_call = FALSE;
7333         if (cmethod->wrapper_type && cmethod->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
7334                 supported_tail_call = FALSE;
7335         if (call_opcode != CEE_CALL)
7336                 supported_tail_call = FALSE;
7337
7338         /* Debugging support */
7339 #if 0
7340         if (supported_tail_call) {
7341                 if (!mono_debug_count ())
7342                         supported_tail_call = FALSE;
7343         }
7344 #endif
7345
7346         return supported_tail_call;
7347 }
7348
7349 /*
7350  * handle_ctor_call:
7351  *
7352  *   Handle calls made to ctors from NEWOBJ opcodes.
7353  */
7354 static void
7355 handle_ctor_call (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, int context_used,
7356                                   MonoInst **sp, guint8 *ip, int *inline_costs)
7357 {
7358         MonoInst *vtable_arg = NULL, *callvirt_this_arg = NULL, *ins;
7359
7360         if (cmethod->klass->valuetype && mono_class_generic_sharing_enabled (cmethod->klass) &&
7361                                         mono_method_is_generic_sharable (cmethod, TRUE)) {
7362                 if (cmethod->is_inflated && mono_method_get_context (cmethod)->method_inst) {
7363                         mono_class_vtable (cfg->domain, cmethod->klass);
7364                         CHECK_TYPELOAD (cmethod->klass);
7365
7366                         vtable_arg = emit_get_rgctx_method (cfg, context_used,
7367                                                                                                 cmethod, MONO_RGCTX_INFO_METHOD_RGCTX);
7368                 } else {
7369                         if (context_used) {
7370                                 vtable_arg = mini_emit_get_rgctx_klass (cfg, context_used,
7371                                                                                                    cmethod->klass, MONO_RGCTX_INFO_VTABLE);
7372                         } else {
7373                                 MonoVTable *vtable = mono_class_vtable (cfg->domain, cmethod->klass);
7374
7375                                 CHECK_TYPELOAD (cmethod->klass);
7376                                 EMIT_NEW_VTABLECONST (cfg, vtable_arg, vtable);
7377                         }
7378                 }
7379         }
7380
7381         /* Avoid virtual calls to ctors if possible */
7382         if (mono_class_is_marshalbyref (cmethod->klass))
7383                 callvirt_this_arg = sp [0];
7384
7385         if (cmethod && (cfg->opt & MONO_OPT_INTRINS) && (ins = mini_emit_inst_for_ctor (cfg, cmethod, fsig, sp))) {
7386                 g_assert (MONO_TYPE_IS_VOID (fsig->ret));
7387                 CHECK_CFG_EXCEPTION;
7388         } else if ((cfg->opt & MONO_OPT_INLINE) && cmethod && !context_used && !vtable_arg &&
7389                            mono_method_check_inlining (cfg, cmethod) &&
7390                            !mono_class_is_subclass_of (cmethod->klass, mono_defaults.exception_class, FALSE)) {
7391                 int costs;
7392
7393                 if ((costs = inline_method (cfg, cmethod, fsig, sp, ip, cfg->real_offset, FALSE))) {
7394                         cfg->real_offset += 5;
7395
7396                         *inline_costs += costs - 5;
7397                 } else {
7398                         INLINE_FAILURE ("inline failure");
7399                         // FIXME-VT: Clean this up
7400                         if (cfg->gsharedvt && mini_is_gsharedvt_signature (fsig))
7401                                 GSHAREDVT_FAILURE(*ip);
7402                         mono_emit_method_call_full (cfg, cmethod, fsig, FALSE, sp, callvirt_this_arg, NULL, NULL);
7403                 }
7404         } else if (cfg->gsharedvt && mini_is_gsharedvt_signature (fsig)) {
7405                 MonoInst *addr;
7406
7407                 addr = emit_get_rgctx_gsharedvt_call (cfg, context_used, fsig, cmethod, MONO_RGCTX_INFO_METHOD_GSHAREDVT_OUT_TRAMPOLINE);
7408
7409                 if (cfg->llvm_only) {
7410                         // FIXME: Avoid initializing vtable_arg
7411                         emit_llvmonly_calli (cfg, fsig, sp, addr);
7412                 } else {
7413                         mono_emit_calli (cfg, fsig, sp, addr, NULL, vtable_arg);
7414                 }
7415         } else if (context_used &&
7416                            ((!mono_method_is_generic_sharable_full (cmethod, TRUE, FALSE, FALSE) ||
7417                                  !mono_class_generic_sharing_enabled (cmethod->klass)) || cfg->gsharedvt)) {
7418                 MonoInst *cmethod_addr;
7419
7420                 /* Generic calls made out of gsharedvt methods cannot be patched, so use an indirect call */
7421
7422                 if (cfg->llvm_only) {
7423                         MonoInst *addr = emit_get_rgctx_method (cfg, context_used, cmethod,
7424                                                                                                         MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
7425                         emit_llvmonly_calli (cfg, fsig, sp, addr);
7426                 } else {
7427                         cmethod_addr = emit_get_rgctx_method (cfg, context_used,
7428                                                                                                   cmethod, MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
7429
7430                         mono_emit_calli (cfg, fsig, sp, cmethod_addr, NULL, vtable_arg);
7431                 }
7432         } else {
7433                 INLINE_FAILURE ("ctor call");
7434                 ins = mono_emit_method_call_full (cfg, cmethod, fsig, FALSE, sp,
7435                                                                                   callvirt_this_arg, NULL, vtable_arg);
7436         }
7437  exception_exit:
7438         return;
7439 }
7440
7441 static void
7442 emit_setret (MonoCompile *cfg, MonoInst *val)
7443 {
7444         MonoType *ret_type = mini_get_underlying_type (mono_method_signature (cfg->method)->ret);
7445         MonoInst *ins;
7446
7447         if (mini_type_to_stind (cfg, ret_type) == CEE_STOBJ) {
7448                 MonoInst *ret_addr;
7449
7450                 if (!cfg->vret_addr) {
7451                         EMIT_NEW_VARSTORE (cfg, ins, cfg->ret, ret_type, val);
7452                 } else {
7453                         EMIT_NEW_RETLOADA (cfg, ret_addr);
7454
7455                         EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STOREV_MEMBASE, ret_addr->dreg, 0, val->dreg);
7456                         ins->klass = mono_class_from_mono_type (ret_type);
7457                 }
7458         } else {
7459 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
7460                 if (COMPILE_SOFT_FLOAT (cfg) && !ret_type->byref && ret_type->type == MONO_TYPE_R4) {
7461                         MonoInst *iargs [1];
7462                         MonoInst *conv;
7463
7464                         iargs [0] = val;
7465                         conv = mono_emit_jit_icall (cfg, mono_fload_r4_arg, iargs);
7466                         mono_arch_emit_setret (cfg, cfg->method, conv);
7467                 } else {
7468                         mono_arch_emit_setret (cfg, cfg->method, val);
7469                 }
7470 #else
7471                 mono_arch_emit_setret (cfg, cfg->method, val);
7472 #endif
7473         }
7474 }
7475
7476 /*
7477  * mono_method_to_ir:
7478  *
7479  * Translate the .net IL into linear IR.
7480  *
7481  * @start_bblock: if not NULL, the starting basic block, used during inlining.
7482  * @end_bblock: if not NULL, the ending basic block, used during inlining.
7483  * @return_var: if not NULL, the place where the return value is stored, used during inlining.   
7484  * @inline_args: if not NULL, contains the arguments to the inline call
7485  * @inline_offset: if not zero, the real offset from the inline call, or zero otherwise.
7486  * @is_virtual_call: whether this method is being called as a result of a call to callvirt
7487  *
7488  * This method is used to turn ECMA IL into Mono's internal Linear IR
7489  * reprensetation.  It is used both for entire methods, as well as
7490  * inlining existing methods.  In the former case, the @start_bblock,
7491  * @end_bblock, @return_var, @inline_args are all set to NULL, and the
7492  * inline_offset is set to zero.
7493  * 
7494  * Returns: the inline cost, or -1 if there was an error processing this method.
7495  */
7496 int
7497 mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_bblock, MonoBasicBlock *end_bblock, 
7498                    MonoInst *return_var, MonoInst **inline_args, 
7499                    guint inline_offset, gboolean is_virtual_call)
7500 {
7501         MonoError error;
7502         MonoInst *ins, **sp, **stack_start;
7503         MonoBasicBlock *tblock = NULL, *init_localsbb = NULL;
7504         MonoSimpleBasicBlock *bb = NULL, *original_bb = NULL;
7505         MonoMethod *cmethod, *method_definition;
7506         MonoInst **arg_array;
7507         MonoMethodHeader *header;
7508         MonoImage *image;
7509         guint32 token, ins_flag;
7510         MonoClass *klass;
7511         MonoClass *constrained_class = NULL;
7512         unsigned char *ip, *end, *target, *err_pos;
7513         MonoMethodSignature *sig;
7514         MonoGenericContext *generic_context = NULL;
7515         MonoGenericContainer *generic_container = NULL;
7516         MonoType **param_types;
7517         int i, n, start_new_bblock, dreg;
7518         int num_calls = 0, inline_costs = 0;
7519         int breakpoint_id = 0;
7520         guint num_args;
7521         GSList *class_inits = NULL;
7522         gboolean dont_verify, dont_verify_stloc, readonly = FALSE;
7523         int context_used;
7524         gboolean init_locals, seq_points, skip_dead_blocks;
7525         gboolean sym_seq_points = FALSE;
7526         MonoDebugMethodInfo *minfo;
7527         MonoBitSet *seq_point_locs = NULL;
7528         MonoBitSet *seq_point_set_locs = NULL;
7529
7530         cfg->disable_inline = is_jit_optimizer_disabled (method);
7531
7532         /* serialization and xdomain stuff may need access to private fields and methods */
7533         dont_verify = method->klass->image->assembly->corlib_internal? TRUE: FALSE;
7534         dont_verify |= method->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE;
7535         dont_verify |= method->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH;
7536         dont_verify |= method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE; /* bug #77896 */
7537         dont_verify |= method->wrapper_type == MONO_WRAPPER_COMINTEROP;
7538         dont_verify |= method->wrapper_type == MONO_WRAPPER_COMINTEROP_INVOKE;
7539
7540         /* still some type unsafety issues in marshal wrappers... (unknown is PtrToStructure) */
7541         dont_verify_stloc = method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE;
7542         dont_verify_stloc |= method->wrapper_type == MONO_WRAPPER_UNKNOWN;
7543         dont_verify_stloc |= method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED;
7544         dont_verify_stloc |= method->wrapper_type == MONO_WRAPPER_STELEMREF;
7545
7546         image = method->klass->image;
7547         header = mono_method_get_header_checked (method, &cfg->error);
7548         if (!header) {
7549                 mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
7550                 goto exception_exit;
7551         } else {
7552                 cfg->headers_to_free = g_slist_prepend_mempool (cfg->mempool, cfg->headers_to_free, header);
7553         }
7554
7555         generic_container = mono_method_get_generic_container (method);
7556         sig = mono_method_signature (method);
7557         num_args = sig->hasthis + sig->param_count;
7558         ip = (unsigned char*)header->code;
7559         cfg->cil_start = ip;
7560         end = ip + header->code_size;
7561         cfg->stat_cil_code_size += header->code_size;
7562
7563         seq_points = cfg->gen_seq_points && cfg->method == method;
7564
7565         if (method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED) {
7566                 /* We could hit a seq point before attaching to the JIT (#8338) */
7567                 seq_points = FALSE;
7568         }
7569
7570         if (cfg->gen_sdb_seq_points && cfg->method == method) {
7571                 minfo = mono_debug_lookup_method (method);
7572                 if (minfo) {
7573                         MonoSymSeqPoint *sps;
7574                         int i, n_il_offsets;
7575
7576                         mono_debug_get_seq_points (minfo, NULL, NULL, NULL, &sps, &n_il_offsets);
7577                         seq_point_locs = mono_bitset_mem_new (mono_mempool_alloc0 (cfg->mempool, mono_bitset_alloc_size (header->code_size, 0)), header->code_size, 0);
7578                         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);
7579                         sym_seq_points = TRUE;
7580                         for (i = 0; i < n_il_offsets; ++i) {
7581                                 if (sps [i].il_offset < header->code_size)
7582                                         mono_bitset_set_fast (seq_point_locs, sps [i].il_offset);
7583                         }
7584                         g_free (sps);
7585
7586                         MonoDebugMethodAsyncInfo* asyncMethod = mono_debug_lookup_method_async_debug_info (method);
7587                         if (asyncMethod) {
7588                                 for (i = 0; asyncMethod != NULL && i < asyncMethod->num_awaits; i++)
7589                                 {
7590                                         mono_bitset_set_fast (seq_point_locs, asyncMethod->resume_offsets[i]);
7591                                         mono_bitset_set_fast (seq_point_locs, asyncMethod->yield_offsets[i]);
7592                                 }
7593                                 mono_debug_free_method_async_debug_info (asyncMethod);
7594                         }
7595                 } else if (!method->wrapper_type && !method->dynamic && mono_debug_image_has_debug_info (method->klass->image)) {
7596                         /* Methods without line number info like auto-generated property accessors */
7597                         seq_point_locs = mono_bitset_mem_new (mono_mempool_alloc0 (cfg->mempool, mono_bitset_alloc_size (header->code_size, 0)), header->code_size, 0);
7598                         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);
7599                         sym_seq_points = TRUE;
7600                 }
7601         }
7602
7603         /* 
7604          * Methods without init_locals set could cause asserts in various passes
7605          * (#497220). To work around this, we emit dummy initialization opcodes
7606          * (OP_DUMMY_ICONST etc.) which generate no code. These are only supported
7607          * on some platforms.
7608          */
7609         if ((cfg->opt & MONO_OPT_UNSAFE) && cfg->backend->have_dummy_init)
7610                 init_locals = header->init_locals;
7611         else
7612                 init_locals = TRUE;
7613
7614         method_definition = method;
7615         while (method_definition->is_inflated) {
7616                 MonoMethodInflated *imethod = (MonoMethodInflated *) method_definition;
7617                 method_definition = imethod->declaring;
7618         }
7619
7620         /* SkipVerification is not allowed if core-clr is enabled */
7621         if (!dont_verify && mini_assembly_can_skip_verification (cfg->domain, method)) {
7622                 dont_verify = TRUE;
7623                 dont_verify_stloc = TRUE;
7624         }
7625
7626         if (sig->is_inflated)
7627                 generic_context = mono_method_get_context (method);
7628         else if (generic_container)
7629                 generic_context = &generic_container->context;
7630         cfg->generic_context = generic_context;
7631
7632         if (!cfg->gshared)
7633                 g_assert (!sig->has_type_parameters);
7634
7635         if (sig->generic_param_count && method->wrapper_type == MONO_WRAPPER_NONE) {
7636                 g_assert (method->is_inflated);
7637                 g_assert (mono_method_get_context (method)->method_inst);
7638         }
7639         if (method->is_inflated && mono_method_get_context (method)->method_inst)
7640                 g_assert (sig->generic_param_count);
7641
7642         if (cfg->method == method) {
7643                 cfg->real_offset = 0;
7644         } else {
7645                 cfg->real_offset = inline_offset;
7646         }
7647
7648         cfg->cil_offset_to_bb = (MonoBasicBlock **)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoBasicBlock*) * header->code_size);
7649         cfg->cil_offset_to_bb_len = header->code_size;
7650
7651         cfg->current_method = method;
7652
7653         if (cfg->verbose_level > 2)
7654                 printf ("method to IR %s\n", mono_method_full_name (method, TRUE));
7655
7656         param_types = (MonoType **)mono_mempool_alloc (cfg->mempool, sizeof (MonoType*) * num_args);
7657         if (sig->hasthis)
7658                 param_types [0] = method->klass->valuetype?&method->klass->this_arg:&method->klass->byval_arg;
7659         for (n = 0; n < sig->param_count; ++n)
7660                 param_types [n + sig->hasthis] = sig->params [n];
7661         cfg->arg_types = param_types;
7662
7663         cfg->dont_inline = g_list_prepend (cfg->dont_inline, method);
7664         if (cfg->method == method) {
7665
7666                 if (cfg->prof_options & MONO_PROFILE_INS_COVERAGE)
7667                         cfg->coverage_info = mono_profiler_coverage_alloc (cfg->method, header->code_size);
7668
7669                 /* ENTRY BLOCK */
7670                 NEW_BBLOCK (cfg, start_bblock);
7671                 cfg->bb_entry = start_bblock;
7672                 start_bblock->cil_code = NULL;
7673                 start_bblock->cil_length = 0;
7674
7675                 /* EXIT BLOCK */
7676                 NEW_BBLOCK (cfg, end_bblock);
7677                 cfg->bb_exit = end_bblock;
7678                 end_bblock->cil_code = NULL;
7679                 end_bblock->cil_length = 0;
7680                 end_bblock->flags |= BB_INDIRECT_JUMP_TARGET;
7681                 g_assert (cfg->num_bblocks == 2);
7682
7683                 arg_array = cfg->args;
7684
7685                 if (header->num_clauses) {
7686                         cfg->spvars = g_hash_table_new (NULL, NULL);
7687                         cfg->exvars = g_hash_table_new (NULL, NULL);
7688                 }
7689                 /* handle exception clauses */
7690                 for (i = 0; i < header->num_clauses; ++i) {
7691                         MonoBasicBlock *try_bb;
7692                         MonoExceptionClause *clause = &header->clauses [i];
7693                         GET_BBLOCK (cfg, try_bb, ip + clause->try_offset);
7694
7695                         try_bb->real_offset = clause->try_offset;
7696                         try_bb->try_start = TRUE;
7697                         try_bb->region = ((i + 1) << 8) | clause->flags;
7698                         GET_BBLOCK (cfg, tblock, ip + clause->handler_offset);
7699                         tblock->real_offset = clause->handler_offset;
7700                         tblock->flags |= BB_EXCEPTION_HANDLER;
7701
7702                         /*
7703                          * Linking the try block with the EH block hinders inlining as we won't be able to 
7704                          * merge the bblocks from inlining and produce an artificial hole for no good reason.
7705                          */
7706                         if (COMPILE_LLVM (cfg))
7707                                 link_bblock (cfg, try_bb, tblock);
7708
7709                         if (*(ip + clause->handler_offset) == CEE_POP)
7710                                 tblock->flags |= BB_EXCEPTION_DEAD_OBJ;
7711
7712                         if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY ||
7713                             clause->flags == MONO_EXCEPTION_CLAUSE_FILTER ||
7714                             clause->flags == MONO_EXCEPTION_CLAUSE_FAULT) {
7715                                 MONO_INST_NEW (cfg, ins, OP_START_HANDLER);
7716                                 MONO_ADD_INS (tblock, ins);
7717
7718                                 if (seq_points && clause->flags != MONO_EXCEPTION_CLAUSE_FINALLY && clause->flags != MONO_EXCEPTION_CLAUSE_FILTER) {
7719                                         /* finally clauses already have a seq point */
7720                                         /* seq points for filter clauses are emitted below */
7721                                         NEW_SEQ_POINT (cfg, ins, clause->handler_offset, TRUE);
7722                                         MONO_ADD_INS (tblock, ins);
7723                                 }
7724
7725                                 /* todo: is a fault block unsafe to optimize? */
7726                                 if (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT)
7727                                         tblock->flags |= BB_EXCEPTION_UNSAFE;
7728                         }
7729
7730                         /*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);
7731                           while (p < end) {
7732                           printf ("%s", mono_disasm_code_one (NULL, method, p, &p));
7733                           }*/
7734                         /* catch and filter blocks get the exception object on the stack */
7735                         if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE ||
7736                             clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
7737
7738                                 /* mostly like handle_stack_args (), but just sets the input args */
7739                                 /* printf ("handling clause at IL_%04x\n", clause->handler_offset); */
7740                                 tblock->in_scount = 1;
7741                                 tblock->in_stack = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*));
7742                                 tblock->in_stack [0] = mono_create_exvar_for_offset (cfg, clause->handler_offset);
7743
7744                                 cfg->cbb = tblock;
7745
7746 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
7747                                 /* The EH code passes in the exception in a register to both JITted and LLVM compiled code */
7748                                 if (!cfg->compile_llvm) {
7749                                         MONO_INST_NEW (cfg, ins, OP_GET_EX_OBJ);
7750                                         ins->dreg = tblock->in_stack [0]->dreg;
7751                                         MONO_ADD_INS (tblock, ins);
7752                                 }
7753 #else
7754                                 MonoInst *dummy_use;
7755
7756                                 /* 
7757                                  * Add a dummy use for the exvar so its liveness info will be
7758                                  * correct.
7759                                  */
7760                                 EMIT_NEW_DUMMY_USE (cfg, dummy_use, tblock->in_stack [0]);
7761 #endif
7762
7763                                 if (seq_points && clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
7764                                         NEW_SEQ_POINT (cfg, ins, clause->handler_offset, TRUE);
7765                                         MONO_ADD_INS (tblock, ins);
7766                                 }
7767                                 
7768                                 if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
7769                                         GET_BBLOCK (cfg, tblock, ip + clause->data.filter_offset);
7770                                         tblock->flags |= BB_EXCEPTION_HANDLER;
7771                                         tblock->real_offset = clause->data.filter_offset;
7772                                         tblock->in_scount = 1;
7773                                         tblock->in_stack = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*));
7774                                         /* The filter block shares the exvar with the handler block */
7775                                         tblock->in_stack [0] = mono_create_exvar_for_offset (cfg, clause->handler_offset);
7776                                         MONO_INST_NEW (cfg, ins, OP_START_HANDLER);
7777                                         MONO_ADD_INS (tblock, ins);
7778                                 }
7779                         }
7780
7781                         if (clause->flags != MONO_EXCEPTION_CLAUSE_FILTER &&
7782                                         clause->data.catch_class &&
7783                                         cfg->gshared &&
7784                                         mono_class_check_context_used (clause->data.catch_class)) {
7785                                 /*
7786                                  * In shared generic code with catch
7787                                  * clauses containing type variables
7788                                  * the exception handling code has to
7789                                  * be able to get to the rgctx.
7790                                  * Therefore we have to make sure that
7791                                  * the vtable/mrgctx argument (for
7792                                  * static or generic methods) or the
7793                                  * "this" argument (for non-static
7794                                  * methods) are live.
7795                                  */
7796                                 if ((method->flags & METHOD_ATTRIBUTE_STATIC) ||
7797                                                 mini_method_get_context (method)->method_inst ||
7798                                                 method->klass->valuetype) {
7799                                         mono_get_vtable_var (cfg);
7800                                 } else {
7801                                         MonoInst *dummy_use;
7802
7803                                         EMIT_NEW_DUMMY_USE (cfg, dummy_use, arg_array [0]);
7804                                 }
7805                         }
7806                 }
7807         } else {
7808                 arg_array = (MonoInst **) alloca (sizeof (MonoInst *) * num_args);
7809                 cfg->cbb = start_bblock;
7810                 cfg->args = arg_array;
7811                 mono_save_args (cfg, sig, inline_args);
7812         }
7813
7814         /* FIRST CODE BLOCK */
7815         NEW_BBLOCK (cfg, tblock);
7816         tblock->cil_code = ip;
7817         cfg->cbb = tblock;
7818         cfg->ip = ip;
7819
7820         ADD_BBLOCK (cfg, tblock);
7821
7822         if (cfg->method == method) {
7823                 breakpoint_id = mono_debugger_method_has_breakpoint (method);
7824                 if (breakpoint_id) {
7825                         MONO_INST_NEW (cfg, ins, OP_BREAK);
7826                         MONO_ADD_INS (cfg->cbb, ins);
7827                 }
7828         }
7829
7830         /* we use a separate basic block for the initialization code */
7831         NEW_BBLOCK (cfg, init_localsbb);
7832         if (cfg->method == method)
7833                 cfg->bb_init = init_localsbb;
7834         init_localsbb->real_offset = cfg->real_offset;
7835         start_bblock->next_bb = init_localsbb;
7836         init_localsbb->next_bb = cfg->cbb;
7837         link_bblock (cfg, start_bblock, init_localsbb);
7838         link_bblock (cfg, init_localsbb, cfg->cbb);
7839                 
7840         cfg->cbb = init_localsbb;
7841
7842         if (cfg->gsharedvt && cfg->method == method) {
7843                 MonoGSharedVtMethodInfo *info;
7844                 MonoInst *var, *locals_var;
7845                 int dreg;
7846
7847                 info = (MonoGSharedVtMethodInfo *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoGSharedVtMethodInfo));
7848                 info->method = cfg->method;
7849                 info->count_entries = 16;
7850                 info->entries = (MonoRuntimeGenericContextInfoTemplate *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoRuntimeGenericContextInfoTemplate) * info->count_entries);
7851                 cfg->gsharedvt_info = info;
7852
7853                 var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
7854                 /* prevent it from being register allocated */
7855                 //var->flags |= MONO_INST_VOLATILE;
7856                 cfg->gsharedvt_info_var = var;
7857
7858                 ins = emit_get_rgctx_gsharedvt_method (cfg, mini_method_check_context_used (cfg, method), method, info);
7859                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, var->dreg, ins->dreg);
7860
7861                 /* Allocate locals */
7862                 locals_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
7863                 /* prevent it from being register allocated */
7864                 //locals_var->flags |= MONO_INST_VOLATILE;
7865                 cfg->gsharedvt_locals_var = locals_var;
7866
7867                 dreg = alloc_ireg (cfg);
7868                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, dreg, var->dreg, MONO_STRUCT_OFFSET (MonoGSharedVtMethodRuntimeInfo, locals_size));
7869
7870                 MONO_INST_NEW (cfg, ins, OP_LOCALLOC);
7871                 ins->dreg = locals_var->dreg;
7872                 ins->sreg1 = dreg;
7873                 MONO_ADD_INS (cfg->cbb, ins);
7874                 cfg->gsharedvt_locals_var_ins = ins;
7875                 
7876                 cfg->flags |= MONO_CFG_HAS_ALLOCA;
7877                 /*
7878                 if (init_locals)
7879                         ins->flags |= MONO_INST_INIT;
7880                 */
7881         }
7882
7883         if (mono_security_core_clr_enabled ()) {
7884                 /* check if this is native code, e.g. an icall or a p/invoke */
7885                 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
7886                         MonoMethod *wrapped = mono_marshal_method_from_wrapper (method);
7887                         if (wrapped) {
7888                                 gboolean pinvk = (wrapped->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL);
7889                                 gboolean icall = (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL);
7890
7891                                 /* if this ia a native call then it can only be JITted from platform code */
7892                                 if ((icall || pinvk) && method->klass && method->klass->image) {
7893                                         if (!mono_security_core_clr_is_platform_image (method->klass->image)) {
7894                                                 MonoException *ex = icall ? mono_get_exception_security () : 
7895                                                         mono_get_exception_method_access ();
7896                                                 emit_throw_exception (cfg, ex);
7897                                         }
7898                                 }
7899                         }
7900                 }
7901         }
7902
7903         CHECK_CFG_EXCEPTION;
7904
7905         if (header->code_size == 0)
7906                 UNVERIFIED;
7907
7908         if (get_basic_blocks (cfg, header, cfg->real_offset, ip, end, &err_pos)) {
7909                 ip = err_pos;
7910                 UNVERIFIED;
7911         }
7912
7913         if (cfg->method == method)
7914                 mono_debug_init_method (cfg, cfg->cbb, breakpoint_id);
7915
7916         for (n = 0; n < header->num_locals; ++n) {
7917                 if (header->locals [n]->type == MONO_TYPE_VOID && !header->locals [n]->byref)
7918                         UNVERIFIED;
7919         }
7920         class_inits = NULL;
7921
7922         /* We force the vtable variable here for all shared methods
7923            for the possibility that they might show up in a stack
7924            trace where their exact instantiation is needed. */
7925         if (cfg->gshared && method == cfg->method) {
7926                 if ((method->flags & METHOD_ATTRIBUTE_STATIC) ||
7927                                 mini_method_get_context (method)->method_inst ||
7928                                 method->klass->valuetype) {
7929                         mono_get_vtable_var (cfg);
7930                 } else {
7931                         /* FIXME: Is there a better way to do this?
7932                            We need the variable live for the duration
7933                            of the whole method. */
7934                         cfg->args [0]->flags |= MONO_INST_VOLATILE;
7935                 }
7936         }
7937
7938         /* add a check for this != NULL to inlined methods */
7939         if (is_virtual_call) {
7940                 MonoInst *arg_ins;
7941
7942                 NEW_ARGLOAD (cfg, arg_ins, 0);
7943                 MONO_ADD_INS (cfg->cbb, arg_ins);
7944                 MONO_EMIT_NEW_CHECK_THIS (cfg, arg_ins->dreg);
7945         }
7946
7947         skip_dead_blocks = !dont_verify;
7948         if (skip_dead_blocks) {
7949                 original_bb = bb = mono_basic_block_split (method, &cfg->error, header);
7950                 CHECK_CFG_ERROR;
7951                 g_assert (bb);
7952         }
7953
7954         /* we use a spare stack slot in SWITCH and NEWOBJ and others */
7955         stack_start = sp = (MonoInst **)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst*) * (header->max_stack + 1));
7956
7957         ins_flag = 0;
7958         start_new_bblock = 0;
7959         while (ip < end) {
7960                 if (cfg->method == method)
7961                         cfg->real_offset = ip - header->code;
7962                 else
7963                         cfg->real_offset = inline_offset;
7964                 cfg->ip = ip;
7965
7966                 context_used = 0;
7967
7968                 if (start_new_bblock) {
7969                         cfg->cbb->cil_length = ip - cfg->cbb->cil_code;
7970                         if (start_new_bblock == 2) {
7971                                 g_assert (ip == tblock->cil_code);
7972                         } else {
7973                                 GET_BBLOCK (cfg, tblock, ip);
7974                         }
7975                         cfg->cbb->next_bb = tblock;
7976                         cfg->cbb = tblock;
7977                         start_new_bblock = 0;
7978                         for (i = 0; i < cfg->cbb->in_scount; ++i) {
7979                                 if (cfg->verbose_level > 3)
7980                                         printf ("loading %d from temp %d\n", i, (int)cfg->cbb->in_stack [i]->inst_c0);
7981                                 EMIT_NEW_TEMPLOAD (cfg, ins, cfg->cbb->in_stack [i]->inst_c0);
7982                                 *sp++ = ins;
7983                         }
7984                         if (class_inits)
7985                                 g_slist_free (class_inits);
7986                         class_inits = NULL;
7987                 } else {
7988                         if ((tblock = cfg->cil_offset_to_bb [ip - cfg->cil_start]) && (tblock != cfg->cbb)) {
7989                                 link_bblock (cfg, cfg->cbb, tblock);
7990                                 if (sp != stack_start) {
7991                                         handle_stack_args (cfg, stack_start, sp - stack_start);
7992                                         sp = stack_start;
7993                                         CHECK_UNVERIFIABLE (cfg);
7994                                 }
7995                                 cfg->cbb->next_bb = tblock;
7996                                 cfg->cbb = tblock;
7997                                 for (i = 0; i < cfg->cbb->in_scount; ++i) {
7998                                         if (cfg->verbose_level > 3)
7999                                                 printf ("loading %d from temp %d\n", i, (int)cfg->cbb->in_stack [i]->inst_c0);
8000                                         EMIT_NEW_TEMPLOAD (cfg, ins, cfg->cbb->in_stack [i]->inst_c0);
8001                                         *sp++ = ins;
8002                                 }
8003                                 g_slist_free (class_inits);
8004                                 class_inits = NULL;
8005                         }
8006                 }
8007
8008                 if (skip_dead_blocks) {
8009                         int ip_offset = ip - header->code;
8010
8011                         if (ip_offset == bb->end)
8012                                 bb = bb->next;
8013
8014                         if (bb->dead) {
8015                                 int op_size = mono_opcode_size (ip, end);
8016                                 g_assert (op_size > 0); /*The BB formation pass must catch all bad ops*/
8017
8018                                 if (cfg->verbose_level > 3) printf ("SKIPPING DEAD OP at %x\n", ip_offset);
8019
8020                                 if (ip_offset + op_size == bb->end) {
8021                                         MONO_INST_NEW (cfg, ins, OP_NOP);
8022                                         MONO_ADD_INS (cfg->cbb, ins);
8023                                         start_new_bblock = 1;
8024                                 }
8025
8026                                 ip += op_size;
8027                                 continue;
8028                         }
8029                 }
8030                 /*
8031                  * Sequence points are points where the debugger can place a breakpoint.
8032                  * Currently, we generate these automatically at points where the IL
8033                  * stack is empty.
8034                  */
8035                 if (seq_points && ((!sym_seq_points && (sp == stack_start)) || (sym_seq_points && mono_bitset_test_fast (seq_point_locs, ip - header->code)))) {
8036                         /*
8037                          * Make methods interruptable at the beginning, and at the targets of
8038                          * backward branches.
8039                          * Also, do this at the start of every bblock in methods with clauses too,
8040                          * to be able to handle instructions with inprecise control flow like
8041                          * throw/endfinally.
8042                          * Backward branches are handled at the end of method-to-ir ().
8043                          */
8044                         gboolean intr_loc = ip == header->code || (!cfg->cbb->last_ins && cfg->header->num_clauses);
8045                         gboolean sym_seq_point = sym_seq_points && mono_bitset_test_fast (seq_point_locs, ip - header->code);
8046
8047                         /* Avoid sequence points on empty IL like .volatile */
8048                         // FIXME: Enable this
8049                         //if (!(cfg->cbb->last_ins && cfg->cbb->last_ins->opcode == OP_SEQ_POINT)) {
8050                         NEW_SEQ_POINT (cfg, ins, ip - header->code, intr_loc);
8051                         if ((sp != stack_start) && !sym_seq_point)
8052                                 ins->flags |= MONO_INST_NONEMPTY_STACK;
8053                         MONO_ADD_INS (cfg->cbb, ins);
8054
8055                         if (sym_seq_points)
8056                                 mono_bitset_set_fast (seq_point_set_locs, ip - header->code);
8057                 }
8058
8059                 cfg->cbb->real_offset = cfg->real_offset;
8060
8061                 if ((cfg->method == method) && cfg->coverage_info) {
8062                         guint32 cil_offset = ip - header->code;
8063                         cfg->coverage_info->data [cil_offset].cil_code = ip;
8064
8065                         /* TODO: Use an increment here */
8066 #if defined(TARGET_X86)
8067                         MONO_INST_NEW (cfg, ins, OP_STORE_MEM_IMM);
8068                         ins->inst_p0 = &(cfg->coverage_info->data [cil_offset].count);
8069                         ins->inst_imm = 1;
8070                         MONO_ADD_INS (cfg->cbb, ins);
8071 #else
8072                         EMIT_NEW_PCONST (cfg, ins, &(cfg->coverage_info->data [cil_offset].count));
8073                         MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STORE_MEMBASE_IMM, ins->dreg, 0, 1);
8074 #endif
8075                 }
8076
8077                 if (cfg->verbose_level > 3)
8078                         printf ("converting (in B%d: stack: %d) %s", cfg->cbb->block_num, (int)(sp - stack_start), mono_disasm_code_one (NULL, method, ip, NULL));
8079
8080                 switch (*ip) {
8081                 case CEE_NOP:
8082                         if (seq_points && !sym_seq_points && sp != stack_start) {
8083                                 /*
8084                                  * The C# compiler uses these nops to notify the JIT that it should
8085                                  * insert seq points.
8086                                  */
8087                                 NEW_SEQ_POINT (cfg, ins, ip - header->code, FALSE);
8088                                 MONO_ADD_INS (cfg->cbb, ins);
8089                         }
8090                         if (cfg->keep_cil_nops)
8091                                 MONO_INST_NEW (cfg, ins, OP_HARD_NOP);
8092                         else
8093                                 MONO_INST_NEW (cfg, ins, OP_NOP);
8094                         ip++;
8095                         MONO_ADD_INS (cfg->cbb, ins);
8096                         break;
8097                 case CEE_BREAK:
8098                         if (should_insert_brekpoint (cfg->method)) {
8099                                 ins = mono_emit_jit_icall (cfg, mono_debugger_agent_user_break, NULL);
8100                         } else {
8101                                 MONO_INST_NEW (cfg, ins, OP_NOP);
8102                         }
8103                         ip++;
8104                         MONO_ADD_INS (cfg->cbb, ins);
8105                         break;
8106                 case CEE_LDARG_0:
8107                 case CEE_LDARG_1:
8108                 case CEE_LDARG_2:
8109                 case CEE_LDARG_3:
8110                         CHECK_STACK_OVF (1);
8111                         n = (*ip)-CEE_LDARG_0;
8112                         CHECK_ARG (n);
8113                         EMIT_NEW_ARGLOAD (cfg, ins, n);
8114                         ip++;
8115                         *sp++ = ins;
8116                         break;
8117                 case CEE_LDLOC_0:
8118                 case CEE_LDLOC_1:
8119                 case CEE_LDLOC_2:
8120                 case CEE_LDLOC_3:
8121                         CHECK_STACK_OVF (1);
8122                         n = (*ip)-CEE_LDLOC_0;
8123                         CHECK_LOCAL (n);
8124                         EMIT_NEW_LOCLOAD (cfg, ins, n);
8125                         ip++;
8126                         *sp++ = ins;
8127                         break;
8128                 case CEE_STLOC_0:
8129                 case CEE_STLOC_1:
8130                 case CEE_STLOC_2:
8131                 case CEE_STLOC_3: {
8132                         CHECK_STACK (1);
8133                         n = (*ip)-CEE_STLOC_0;
8134                         CHECK_LOCAL (n);
8135                         --sp;
8136                         if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [n], *sp))
8137                                 UNVERIFIED;
8138                         emit_stloc_ir (cfg, sp, header, n);
8139                         ++ip;
8140                         inline_costs += 1;
8141                         break;
8142                         }
8143                 case CEE_LDARG_S:
8144                         CHECK_OPSIZE (2);
8145                         CHECK_STACK_OVF (1);
8146                         n = ip [1];
8147                         CHECK_ARG (n);
8148                         EMIT_NEW_ARGLOAD (cfg, ins, n);
8149                         *sp++ = ins;
8150                         ip += 2;
8151                         break;
8152                 case CEE_LDARGA_S:
8153                         CHECK_OPSIZE (2);
8154                         CHECK_STACK_OVF (1);
8155                         n = ip [1];
8156                         CHECK_ARG (n);
8157                         NEW_ARGLOADA (cfg, ins, n);
8158                         MONO_ADD_INS (cfg->cbb, ins);
8159                         *sp++ = ins;
8160                         ip += 2;
8161                         break;
8162                 case CEE_STARG_S:
8163                         CHECK_OPSIZE (2);
8164                         CHECK_STACK (1);
8165                         --sp;
8166                         n = ip [1];
8167                         CHECK_ARG (n);
8168                         if (!dont_verify_stloc && target_type_is_incompatible (cfg, param_types [ip [1]], *sp))
8169                                 UNVERIFIED;
8170                         EMIT_NEW_ARGSTORE (cfg, ins, n, *sp);
8171                         ip += 2;
8172                         break;
8173                 case CEE_LDLOC_S:
8174                         CHECK_OPSIZE (2);
8175                         CHECK_STACK_OVF (1);
8176                         n = ip [1];
8177                         CHECK_LOCAL (n);
8178                         EMIT_NEW_LOCLOAD (cfg, ins, n);
8179                         *sp++ = ins;
8180                         ip += 2;
8181                         break;
8182                 case CEE_LDLOCA_S: {
8183                         unsigned char *tmp_ip;
8184                         CHECK_OPSIZE (2);
8185                         CHECK_STACK_OVF (1);
8186                         CHECK_LOCAL (ip [1]);
8187
8188                         if ((tmp_ip = emit_optimized_ldloca_ir (cfg, ip, end, 1))) {
8189                                 ip = tmp_ip;
8190                                 inline_costs += 1;
8191                                 break;
8192                         }
8193
8194                         EMIT_NEW_LOCLOADA (cfg, ins, ip [1]);
8195                         *sp++ = ins;
8196                         ip += 2;
8197                         break;
8198                 }
8199                 case CEE_STLOC_S:
8200                         CHECK_OPSIZE (2);
8201                         CHECK_STACK (1);
8202                         --sp;
8203                         CHECK_LOCAL (ip [1]);
8204                         if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [ip [1]], *sp))
8205                                 UNVERIFIED;
8206                         emit_stloc_ir (cfg, sp, header, ip [1]);
8207                         ip += 2;
8208                         inline_costs += 1;
8209                         break;
8210                 case CEE_LDNULL:
8211                         CHECK_STACK_OVF (1);
8212                         EMIT_NEW_PCONST (cfg, ins, NULL);
8213                         ins->type = STACK_OBJ;
8214                         ++ip;
8215                         *sp++ = ins;
8216                         break;
8217                 case CEE_LDC_I4_M1:
8218                         CHECK_STACK_OVF (1);
8219                         EMIT_NEW_ICONST (cfg, ins, -1);
8220                         ++ip;
8221                         *sp++ = ins;
8222                         break;
8223                 case CEE_LDC_I4_0:
8224                 case CEE_LDC_I4_1:
8225                 case CEE_LDC_I4_2:
8226                 case CEE_LDC_I4_3:
8227                 case CEE_LDC_I4_4:
8228                 case CEE_LDC_I4_5:
8229                 case CEE_LDC_I4_6:
8230                 case CEE_LDC_I4_7:
8231                 case CEE_LDC_I4_8:
8232                         CHECK_STACK_OVF (1);
8233                         EMIT_NEW_ICONST (cfg, ins, (*ip) - CEE_LDC_I4_0);
8234                         ++ip;
8235                         *sp++ = ins;
8236                         break;
8237                 case CEE_LDC_I4_S:
8238                         CHECK_OPSIZE (2);
8239                         CHECK_STACK_OVF (1);
8240                         ++ip;
8241                         EMIT_NEW_ICONST (cfg, ins, *((signed char*)ip));
8242                         ++ip;
8243                         *sp++ = ins;
8244                         break;
8245                 case CEE_LDC_I4:
8246                         CHECK_OPSIZE (5);
8247                         CHECK_STACK_OVF (1);
8248                         EMIT_NEW_ICONST (cfg, ins, (gint32)read32 (ip + 1));
8249                         ip += 5;
8250                         *sp++ = ins;
8251                         break;
8252                 case CEE_LDC_I8:
8253                         CHECK_OPSIZE (9);
8254                         CHECK_STACK_OVF (1);
8255                         MONO_INST_NEW (cfg, ins, OP_I8CONST);
8256                         ins->type = STACK_I8;
8257                         ins->dreg = alloc_dreg (cfg, STACK_I8);
8258                         ++ip;
8259                         ins->inst_l = (gint64)read64 (ip);
8260                         MONO_ADD_INS (cfg->cbb, ins);
8261                         ip += 8;
8262                         *sp++ = ins;
8263                         break;
8264                 case CEE_LDC_R4: {
8265                         float *f;
8266                         gboolean use_aotconst = FALSE;
8267
8268 #ifdef TARGET_POWERPC
8269                         /* FIXME: Clean this up */
8270                         if (cfg->compile_aot)
8271                                 use_aotconst = TRUE;
8272 #endif
8273
8274                         /* FIXME: we should really allocate this only late in the compilation process */
8275                         f = (float *)mono_domain_alloc (cfg->domain, sizeof (float));
8276                         CHECK_OPSIZE (5);
8277                         CHECK_STACK_OVF (1);
8278
8279                         if (use_aotconst) {
8280                                 MonoInst *cons;
8281                                 int dreg;
8282
8283                                 EMIT_NEW_AOTCONST (cfg, cons, MONO_PATCH_INFO_R4, f);
8284
8285                                 dreg = alloc_freg (cfg);
8286                                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADR4_MEMBASE, dreg, cons->dreg, 0);
8287                                 ins->type = cfg->r4_stack_type;
8288                         } else {
8289                                 MONO_INST_NEW (cfg, ins, OP_R4CONST);
8290                                 ins->type = cfg->r4_stack_type;
8291                                 ins->dreg = alloc_dreg (cfg, STACK_R8);
8292                                 ins->inst_p0 = f;
8293                                 MONO_ADD_INS (cfg->cbb, ins);
8294                         }
8295                         ++ip;
8296                         readr4 (ip, f);
8297                         ip += 4;
8298                         *sp++ = ins;                    
8299                         break;
8300                 }
8301                 case CEE_LDC_R8: {
8302                         double *d;
8303                         gboolean use_aotconst = FALSE;
8304
8305 #ifdef TARGET_POWERPC
8306                         /* FIXME: Clean this up */
8307                         if (cfg->compile_aot)
8308                                 use_aotconst = TRUE;
8309 #endif
8310
8311                         /* FIXME: we should really allocate this only late in the compilation process */
8312                         d = (double *)mono_domain_alloc (cfg->domain, sizeof (double));
8313                         CHECK_OPSIZE (9);
8314                         CHECK_STACK_OVF (1);
8315
8316                         if (use_aotconst) {
8317                                 MonoInst *cons;
8318                                 int dreg;
8319
8320                                 EMIT_NEW_AOTCONST (cfg, cons, MONO_PATCH_INFO_R8, d);
8321
8322                                 dreg = alloc_freg (cfg);
8323                                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADR8_MEMBASE, dreg, cons->dreg, 0);
8324                                 ins->type = STACK_R8;
8325                         } else {
8326                                 MONO_INST_NEW (cfg, ins, OP_R8CONST);
8327                                 ins->type = STACK_R8;
8328                                 ins->dreg = alloc_dreg (cfg, STACK_R8);
8329                                 ins->inst_p0 = d;
8330                                 MONO_ADD_INS (cfg->cbb, ins);
8331                         }
8332                         ++ip;
8333                         readr8 (ip, d);
8334                         ip += 8;
8335                         *sp++ = ins;
8336                         break;
8337                 }
8338                 case CEE_DUP: {
8339                         MonoInst *temp, *store;
8340                         CHECK_STACK (1);
8341                         CHECK_STACK_OVF (1);
8342                         sp--;
8343                         ins = *sp;
8344
8345                         temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
8346                         EMIT_NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
8347
8348                         EMIT_NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
8349                         *sp++ = ins;
8350
8351                         EMIT_NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
8352                         *sp++ = ins;
8353
8354                         ++ip;
8355                         inline_costs += 2;
8356                         break;
8357                 }
8358                 case CEE_POP:
8359                         CHECK_STACK (1);
8360                         ip++;
8361                         --sp;
8362
8363 #ifdef TARGET_X86
8364                         if (sp [0]->type == STACK_R8)
8365                                 /* we need to pop the value from the x86 FP stack */
8366                                 MONO_EMIT_NEW_UNALU (cfg, OP_X86_FPOP, -1, sp [0]->dreg);
8367 #endif
8368                         break;
8369                 case CEE_JMP: {
8370                         MonoCallInst *call;
8371                         MonoMethodSignature *fsig;
8372                         int i, n;
8373
8374                         INLINE_FAILURE ("jmp");
8375                         GSHAREDVT_FAILURE (*ip);
8376
8377                         CHECK_OPSIZE (5);
8378                         if (stack_start != sp)
8379                                 UNVERIFIED;
8380                         token = read32 (ip + 1);
8381                         /* FIXME: check the signature matches */
8382                         cmethod = mini_get_method (cfg, method, token, NULL, generic_context);
8383                         CHECK_CFG_ERROR;
8384  
8385                         if (cfg->gshared && mono_method_check_context_used (cmethod))
8386                                 GENERIC_SHARING_FAILURE (CEE_JMP);
8387
8388                         emit_instrumentation_call (cfg, mono_profiler_method_leave);
8389
8390                         fsig = mono_method_signature (cmethod);
8391                         n = fsig->param_count + fsig->hasthis;
8392                         if (cfg->llvm_only) {
8393                                 MonoInst **args;
8394
8395                                 args = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * n);
8396                                 for (i = 0; i < n; ++i)
8397                                         EMIT_NEW_ARGLOAD (cfg, args [i], i);
8398                                 ins = mono_emit_method_call_full (cfg, cmethod, fsig, TRUE, args, NULL, NULL, NULL);
8399                                 /*
8400                                  * The code in mono-basic-block.c treats the rest of the code as dead, but we
8401                                  * have to emit a normal return since llvm expects it.
8402                                  */
8403                                 if (cfg->ret)
8404                                         emit_setret (cfg, ins);
8405                                 MONO_INST_NEW (cfg, ins, OP_BR);
8406                                 ins->inst_target_bb = end_bblock;
8407                                 MONO_ADD_INS (cfg->cbb, ins);
8408                                 link_bblock (cfg, cfg->cbb, end_bblock);
8409                                 ip += 5;
8410                                 break;
8411                         } else if (cfg->backend->have_op_tail_call) {
8412                                 /* Handle tail calls similarly to calls */
8413                                 DISABLE_AOT (cfg);
8414
8415                                 MONO_INST_NEW_CALL (cfg, call, OP_TAILCALL);
8416                                 call->method = cmethod;
8417                                 call->tail_call = TRUE;
8418                                 call->signature = mono_method_signature (cmethod);
8419                                 call->args = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * n);
8420                                 call->inst.inst_p0 = cmethod;
8421                                 for (i = 0; i < n; ++i)
8422                                         EMIT_NEW_ARGLOAD (cfg, call->args [i], i);
8423
8424                                 if (mini_type_is_vtype (mini_get_underlying_type (call->signature->ret)))
8425                                         call->vret_var = cfg->vret_addr;
8426
8427                                 mono_arch_emit_call (cfg, call);
8428                                 cfg->param_area = MAX(cfg->param_area, call->stack_usage);
8429                                 MONO_ADD_INS (cfg->cbb, (MonoInst*)call);
8430                         } else {
8431                                 for (i = 0; i < num_args; ++i)
8432                                         /* Prevent arguments from being optimized away */
8433                                         arg_array [i]->flags |= MONO_INST_VOLATILE;
8434
8435                                 MONO_INST_NEW_CALL (cfg, call, OP_JMP);
8436                                 ins = (MonoInst*)call;
8437                                 ins->inst_p0 = cmethod;
8438                                 MONO_ADD_INS (cfg->cbb, ins);
8439                         }
8440
8441                         ip += 5;
8442                         start_new_bblock = 1;
8443                         break;
8444                 }
8445                 case CEE_CALLI: {
8446                         MonoInst *addr;
8447                         MonoMethodSignature *fsig;
8448
8449                         CHECK_OPSIZE (5);
8450                         token = read32 (ip + 1);
8451
8452                         ins = NULL;
8453
8454                         //GSHAREDVT_FAILURE (*ip);
8455                         cmethod = NULL;
8456                         CHECK_STACK (1);
8457                         --sp;
8458                         addr = *sp;
8459                         fsig = mini_get_signature (method, token, generic_context, &cfg->error);
8460                         CHECK_CFG_ERROR;
8461
8462                         if (method->dynamic && fsig->pinvoke) {
8463                                 MonoInst *args [3];
8464
8465                                 /*
8466                                  * This is a call through a function pointer using a pinvoke
8467                                  * signature. Have to create a wrapper and call that instead.
8468                                  * FIXME: This is very slow, need to create a wrapper at JIT time
8469                                  * instead based on the signature.
8470                                  */
8471                                 EMIT_NEW_IMAGECONST (cfg, args [0], method->klass->image);
8472                                 EMIT_NEW_PCONST (cfg, args [1], fsig);
8473                                 args [2] = addr;
8474                                 addr = mono_emit_jit_icall (cfg, mono_get_native_calli_wrapper, args);
8475                         }
8476
8477                         n = fsig->param_count + fsig->hasthis;
8478
8479                         CHECK_STACK (n);
8480
8481                         //g_assert (!virtual_ || fsig->hasthis);
8482
8483                         sp -= n;
8484
8485                         inline_costs += 10 * num_calls++;
8486
8487                         /*
8488                          * Making generic calls out of gsharedvt methods.
8489                          * This needs to be used for all generic calls, not just ones with a gsharedvt signature, to avoid
8490                          * patching gshared method addresses into a gsharedvt method.
8491                          */
8492                         if (cfg->gsharedvt && mini_is_gsharedvt_signature (fsig)) {
8493                                 /*
8494                                  * We pass the address to the gsharedvt trampoline in the rgctx reg
8495                                  */
8496                                 MonoInst *callee = addr;
8497
8498                                 if (method->wrapper_type != MONO_WRAPPER_DELEGATE_INVOKE)
8499                                         /* Not tested */
8500                                         GSHAREDVT_FAILURE (*ip);
8501
8502                                 if (cfg->llvm_only)
8503                                         // FIXME:
8504                                         GSHAREDVT_FAILURE (*ip);
8505
8506                                 addr = emit_get_rgctx_sig (cfg, context_used,
8507                                                                                           fsig, MONO_RGCTX_INFO_SIG_GSHAREDVT_OUT_TRAMPOLINE_CALLI);
8508                                 ins = (MonoInst*)mono_emit_calli (cfg, fsig, sp, addr, NULL, callee);
8509                                 goto calli_end;
8510                         }
8511
8512                         /* Prevent inlining of methods with indirect calls */
8513                         INLINE_FAILURE ("indirect call");
8514
8515                         if (addr->opcode == OP_PCONST || addr->opcode == OP_AOTCONST || addr->opcode == OP_GOT_ENTRY) {
8516                                 MonoJumpInfoType info_type;
8517                                 gpointer info_data;
8518
8519                                 /*
8520                                  * Instead of emitting an indirect call, emit a direct call
8521                                  * with the contents of the aotconst as the patch info.
8522                                  */
8523                                 if (addr->opcode == OP_PCONST || addr->opcode == OP_AOTCONST) {
8524                                         info_type = (MonoJumpInfoType)addr->inst_c1;
8525                                         info_data = addr->inst_p0;
8526                                 } else {
8527                                         info_type = (MonoJumpInfoType)addr->inst_right->inst_c1;
8528                                         info_data = addr->inst_right->inst_left;
8529                                 }
8530
8531                                 if (info_type == MONO_PATCH_INFO_ICALL_ADDR) {
8532                                         ins = (MonoInst*)mono_emit_abs_call (cfg, MONO_PATCH_INFO_ICALL_ADDR_CALL, info_data, fsig, sp);
8533                                         NULLIFY_INS (addr);
8534                                         goto calli_end;
8535                                 } else if (info_type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
8536                                         ins = (MonoInst*)mono_emit_abs_call (cfg, info_type, info_data, fsig, sp);
8537                                         NULLIFY_INS (addr);
8538                                         goto calli_end;
8539                                 }
8540                         }
8541                         ins = (MonoInst*)mono_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
8542
8543                         calli_end:
8544
8545                         /* End of call, INS should contain the result of the call, if any */
8546
8547                         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
8548                                 g_assert (ins);
8549                                 *sp++ = mono_emit_widen_call_res (cfg, ins, fsig);
8550                         }
8551
8552                         CHECK_CFG_EXCEPTION;
8553
8554                         ip += 5;
8555                         ins_flag = 0;
8556                         constrained_class = NULL;
8557                         break;
8558                 }
8559                 case CEE_CALL:
8560                 case CEE_CALLVIRT: {
8561                         MonoInst *addr = NULL;
8562                         MonoMethodSignature *fsig = NULL;
8563                         int array_rank = 0;
8564                         int virtual_ = *ip == CEE_CALLVIRT;
8565                         gboolean pass_imt_from_rgctx = FALSE;
8566                         MonoInst *imt_arg = NULL;
8567                         MonoInst *keep_this_alive = NULL;
8568                         gboolean pass_vtable = FALSE;
8569                         gboolean pass_mrgctx = FALSE;
8570                         MonoInst *vtable_arg = NULL;
8571                         gboolean check_this = FALSE;
8572                         gboolean supported_tail_call = FALSE;
8573                         gboolean tail_call = FALSE;
8574                         gboolean need_seq_point = FALSE;
8575                         guint32 call_opcode = *ip;
8576                         gboolean emit_widen = TRUE;
8577                         gboolean push_res = TRUE;
8578                         gboolean skip_ret = FALSE;
8579                         gboolean delegate_invoke = FALSE;
8580                         gboolean direct_icall = FALSE;
8581                         gboolean constrained_partial_call = FALSE;
8582                         MonoMethod *cil_method;
8583
8584                         CHECK_OPSIZE (5);
8585                         token = read32 (ip + 1);
8586
8587                         ins = NULL;
8588
8589                         cmethod = mini_get_method (cfg, method, token, NULL, generic_context);
8590                         CHECK_CFG_ERROR;
8591
8592                         cil_method = cmethod;
8593                                 
8594                         if (constrained_class) {
8595                                 if ((constrained_class->byval_arg.type == MONO_TYPE_VAR || constrained_class->byval_arg.type == MONO_TYPE_MVAR) && cfg->gshared) {
8596                                         if (!mini_is_gsharedvt_klass (constrained_class)) {
8597                                                 g_assert (!cmethod->klass->valuetype);
8598                                                 if (!mini_type_is_reference (&constrained_class->byval_arg))
8599                                                         constrained_partial_call = TRUE;
8600                                         }
8601                                 }
8602
8603                                 if (method->wrapper_type != MONO_WRAPPER_NONE) {
8604                                         if (cfg->verbose_level > 2)
8605                                                 printf ("DM Constrained call to %s\n", mono_type_get_full_name (constrained_class));
8606                                         if (!((constrained_class->byval_arg.type == MONO_TYPE_VAR ||
8607                                                    constrained_class->byval_arg.type == MONO_TYPE_MVAR) &&
8608                                                   cfg->gshared)) {
8609                                                 cmethod = mono_get_method_constrained_with_method (image, cil_method, constrained_class, generic_context, &cfg->error);
8610                                                 CHECK_CFG_ERROR;
8611                                         }
8612                                 } else {
8613                                         if (cfg->verbose_level > 2)
8614                                                 printf ("Constrained call to %s\n", mono_type_get_full_name (constrained_class));
8615
8616                                         if ((constrained_class->byval_arg.type == MONO_TYPE_VAR || constrained_class->byval_arg.type == MONO_TYPE_MVAR) && cfg->gshared) {
8617                                                 /* 
8618                                                  * This is needed since get_method_constrained can't find 
8619                                                  * the method in klass representing a type var.
8620                                                  * The type var is guaranteed to be a reference type in this
8621                                                  * case.
8622                                                  */
8623                                                 if (!mini_is_gsharedvt_klass (constrained_class))
8624                                                         g_assert (!cmethod->klass->valuetype);
8625                                         } else {
8626                                                 cmethod = mono_get_method_constrained_checked (image, token, constrained_class, generic_context, &cil_method, &cfg->error);
8627                                                 CHECK_CFG_ERROR;
8628                                         }
8629                                 }
8630
8631                                 if (constrained_class->enumtype && !strcmp (cmethod->name, "GetHashCode")) {
8632                                         /* Use the corresponding method from the base type to avoid boxing */
8633                                         MonoType *base_type = mono_class_enum_basetype (constrained_class);
8634                                         g_assert (base_type);
8635                                         constrained_class = mono_class_from_mono_type (base_type);
8636                                         cmethod = mono_class_get_method_from_name (constrained_class, cmethod->name, 0);
8637                                         g_assert (cmethod);
8638                                 }
8639                         }
8640                                         
8641                         if (!dont_verify && !cfg->skip_visibility) {
8642                                 MonoMethod *target_method = cil_method;
8643                                 if (method->is_inflated) {
8644                                         target_method = mini_get_method_allow_open (method, token, NULL, &(mono_method_get_generic_container (method_definition)->context), &cfg->error);
8645                                         CHECK_CFG_ERROR;
8646                                 }
8647                                 if (!mono_method_can_access_method (method_definition, target_method) &&
8648                                         !mono_method_can_access_method (method, cil_method))
8649                                         emit_method_access_failure (cfg, method, cil_method);
8650                         }
8651
8652                         if (mono_security_core_clr_enabled ())
8653                                 ensure_method_is_allowed_to_call_method (cfg, method, cil_method);
8654
8655                         if (!virtual_ && (cmethod->flags & METHOD_ATTRIBUTE_ABSTRACT))
8656                                 /* MS.NET seems to silently convert this to a callvirt */
8657                                 virtual_ = 1;
8658
8659                         {
8660                                 /*
8661                                  * MS.NET accepts non virtual calls to virtual final methods of transparent proxy classes and
8662                                  * converts to a callvirt.
8663                                  *
8664                                  * tests/bug-515884.il is an example of this behavior
8665                                  */
8666                                 const int test_flags = METHOD_ATTRIBUTE_VIRTUAL | METHOD_ATTRIBUTE_FINAL | METHOD_ATTRIBUTE_STATIC;
8667                                 const int expected_flags = METHOD_ATTRIBUTE_VIRTUAL | METHOD_ATTRIBUTE_FINAL;
8668                                 if (!virtual_ && mono_class_is_marshalbyref (cmethod->klass) && (cmethod->flags & test_flags) == expected_flags && cfg->method->wrapper_type == MONO_WRAPPER_NONE)
8669                                         virtual_ = 1;
8670                         }
8671
8672                         if (!cmethod->klass->inited)
8673                                 if (!mono_class_init (cmethod->klass))
8674                                         TYPE_LOAD_ERROR (cmethod->klass);
8675
8676                         fsig = mono_method_signature (cmethod);
8677                         if (!fsig)
8678                                 LOAD_ERROR;
8679                         if (cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL &&
8680                                 mini_class_is_system_array (cmethod->klass)) {
8681                                 array_rank = cmethod->klass->rank;
8682                         } else if ((cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && icall_is_direct_callable (cfg, cmethod)) {
8683                                 direct_icall = TRUE;
8684                         } else if (fsig->pinvoke) {
8685                                 MonoMethod *wrapper = mono_marshal_get_native_wrapper (cmethod, TRUE, cfg->compile_aot);
8686                                 fsig = mono_method_signature (wrapper);
8687                         } else if (constrained_class) {
8688                         } else {
8689                                 fsig = mono_method_get_signature_checked (cmethod, image, token, generic_context, &cfg->error);
8690                                 CHECK_CFG_ERROR;
8691                         }
8692
8693                         if (cfg->llvm_only && !cfg->method->wrapper_type && (!cmethod || cmethod->is_inflated))
8694                                 cfg->signatures = g_slist_prepend_mempool (cfg->mempool, cfg->signatures, fsig);
8695
8696                         /* See code below */
8697                         if (cmethod->klass == mono_defaults.monitor_class && !strcmp (cmethod->name, "Enter") && mono_method_signature (cmethod)->param_count == 1) {
8698                                 MonoBasicBlock *tbb;
8699
8700                                 GET_BBLOCK (cfg, tbb, ip + 5);
8701                                 if (tbb->try_start && MONO_REGION_FLAGS(tbb->region) == MONO_EXCEPTION_CLAUSE_FINALLY) {
8702                                         /*
8703                                          * We want to extend the try block to cover the call, but we can't do it if the
8704                                          * call is made directly since its followed by an exception check.
8705                                          */
8706                                         direct_icall = FALSE;
8707                                 }
8708                         }
8709
8710                         mono_save_token_info (cfg, image, token, cil_method);
8711
8712                         if (!(seq_point_locs && mono_bitset_test_fast (seq_point_locs, ip + 5 - header->code)))
8713                                 need_seq_point = TRUE;
8714
8715                         /* Don't support calls made using type arguments for now */
8716                         /*
8717                           if (cfg->gsharedvt) {
8718                           if (mini_is_gsharedvt_signature (fsig))
8719                           GSHAREDVT_FAILURE (*ip);
8720                           }
8721                         */
8722
8723                         if (cmethod->string_ctor && method->wrapper_type != MONO_WRAPPER_RUNTIME_INVOKE)
8724                                 g_assert_not_reached ();
8725
8726                         n = fsig->param_count + fsig->hasthis;
8727
8728                         if (!cfg->gshared && mono_class_is_gtd (cmethod->klass))
8729                                 UNVERIFIED;
8730
8731                         if (!cfg->gshared)
8732                                 g_assert (!mono_method_check_context_used (cmethod));
8733
8734                         CHECK_STACK (n);
8735
8736                         //g_assert (!virtual_ || fsig->hasthis);
8737
8738                         sp -= n;
8739
8740                         /*
8741                          * We have the `constrained.' prefix opcode.
8742                          */
8743                         if (constrained_class) {
8744                                 if (mini_is_gsharedvt_klass (constrained_class)) {
8745                                         if ((cmethod->klass != mono_defaults.object_class) && constrained_class->valuetype && cmethod->klass->valuetype) {
8746                                                 /* The 'Own method' case below */
8747                                         } else if (cmethod->klass->image != mono_defaults.corlib && !mono_class_is_interface (cmethod->klass) && !cmethod->klass->valuetype) {
8748                                                 /* 'The type parameter is instantiated as a reference type' case below. */
8749                                         } else {
8750                                                 ins = handle_constrained_gsharedvt_call (cfg, cmethod, fsig, sp, constrained_class, &emit_widen);
8751                                                 CHECK_CFG_EXCEPTION;
8752                                                 g_assert (ins);
8753                                                 goto call_end;
8754                                         }
8755                                 }
8756
8757                                 if (constrained_partial_call) {
8758                                         gboolean need_box = TRUE;
8759
8760                                         /*
8761                                          * The receiver is a valuetype, but the exact type is not known at compile time. This means the
8762                                          * called method is not known at compile time either. The called method could end up being
8763                                          * one of the methods on the parent classes (object/valuetype/enum), in which case we need
8764                                          * to box the receiver.
8765                                          * A simple solution would be to box always and make a normal virtual call, but that would
8766                                          * be bad performance wise.
8767                                          */
8768                                         if (mono_class_is_interface (cmethod->klass) && mono_class_is_ginst (cmethod->klass)) {
8769                                                 /*
8770                                                  * The parent classes implement no generic interfaces, so the called method will be a vtype method, so no boxing neccessary.
8771                                                  */
8772                                                 need_box = FALSE;
8773                                         }
8774
8775                                         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)) {
8776                                                 /* The called method is not virtual, i.e. Object:GetType (), the receiver is a vtype, has to box */
8777                                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &constrained_class->byval_arg, sp [0]->dreg, 0);
8778                                                 ins->klass = constrained_class;
8779                                                 sp [0] = handle_box (cfg, ins, constrained_class, mono_class_check_context_used (constrained_class));
8780                                                 CHECK_CFG_EXCEPTION;
8781                                         } else if (need_box) {
8782                                                 MonoInst *box_type;
8783                                                 MonoBasicBlock *is_ref_bb, *end_bb;
8784                                                 MonoInst *nonbox_call;
8785
8786                                                 /*
8787                                                  * Determine at runtime whenever the called method is defined on object/valuetype/enum, and emit a boxing call
8788                                                  * if needed.
8789                                                  * FIXME: It is possible to inline the called method in a lot of cases, i.e. for T_INT,
8790                                                  * the no-box case goes to a method in Int32, while the box case goes to a method in Enum.
8791                                                  */
8792                                                 addr = emit_get_rgctx_virt_method (cfg, mono_class_check_context_used (constrained_class), constrained_class, cmethod, MONO_RGCTX_INFO_VIRT_METHOD_CODE);
8793
8794                                                 NEW_BBLOCK (cfg, is_ref_bb);
8795                                                 NEW_BBLOCK (cfg, end_bb);
8796
8797                                                 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);
8798                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, box_type->dreg, MONO_GSHAREDVT_BOX_TYPE_REF);
8799                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, is_ref_bb);
8800
8801                                                 /* Non-ref case */
8802                                                 nonbox_call = (MonoInst*)mono_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
8803
8804                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
8805
8806                                                 /* Ref case */
8807                                                 MONO_START_BB (cfg, is_ref_bb);
8808                                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &constrained_class->byval_arg, sp [0]->dreg, 0);
8809                                                 ins->klass = constrained_class;
8810                                                 sp [0] = handle_box (cfg, ins, constrained_class, mono_class_check_context_used (constrained_class));
8811                                                 ins = (MonoInst*)mono_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
8812
8813                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
8814
8815                                                 MONO_START_BB (cfg, end_bb);
8816                                                 cfg->cbb = end_bb;
8817
8818                                                 nonbox_call->dreg = ins->dreg;
8819                                                 goto call_end;
8820                                         } else {
8821                                                 g_assert (mono_class_is_interface (cmethod->klass));
8822                                                 addr = emit_get_rgctx_virt_method (cfg, mono_class_check_context_used (constrained_class), constrained_class, cmethod, MONO_RGCTX_INFO_VIRT_METHOD_CODE);
8823                                                 ins = (MonoInst*)mono_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
8824                                                 goto call_end;
8825                                         }
8826                                 } else if (constrained_class->valuetype && (cmethod->klass == mono_defaults.object_class || cmethod->klass == mono_defaults.enum_class->parent || cmethod->klass == mono_defaults.enum_class)) {
8827                                         /*
8828                                          * The type parameter is instantiated as a valuetype,
8829                                          * but that type doesn't override the method we're
8830                                          * calling, so we need to box `this'.
8831                                          */
8832                                         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &constrained_class->byval_arg, sp [0]->dreg, 0);
8833                                         ins->klass = constrained_class;
8834                                         sp [0] = handle_box (cfg, ins, constrained_class, mono_class_check_context_used (constrained_class));
8835                                         CHECK_CFG_EXCEPTION;
8836                                 } else if (!constrained_class->valuetype) {
8837                                         int dreg = alloc_ireg_ref (cfg);
8838
8839                                         /*
8840                                          * The type parameter is instantiated as a reference
8841                                          * type.  We have a managed pointer on the stack, so
8842                                          * we need to dereference it here.
8843                                          */
8844                                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, dreg, sp [0]->dreg, 0);
8845                                         ins->type = STACK_OBJ;
8846                                         sp [0] = ins;
8847                                 } else {
8848                                         if (cmethod->klass->valuetype) {
8849                                                 /* Own method */
8850                                         } else {
8851                                                 /* Interface method */
8852                                                 int ioffset, slot;
8853
8854                                                 mono_class_setup_vtable (constrained_class);
8855                                                 CHECK_TYPELOAD (constrained_class);
8856                                                 ioffset = mono_class_interface_offset (constrained_class, cmethod->klass);
8857                                                 if (ioffset == -1)
8858                                                         TYPE_LOAD_ERROR (constrained_class);
8859                                                 slot = mono_method_get_vtable_slot (cmethod);
8860                                                 if (slot == -1)
8861                                                         TYPE_LOAD_ERROR (cmethod->klass);
8862                                                 cmethod = constrained_class->vtable [ioffset + slot];
8863
8864                                                 if (cmethod->klass == mono_defaults.enum_class) {
8865                                                         /* Enum implements some interfaces, so treat this as the first case */
8866                                                         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &constrained_class->byval_arg, sp [0]->dreg, 0);
8867                                                         ins->klass = constrained_class;
8868                                                         sp [0] = handle_box (cfg, ins, constrained_class, mono_class_check_context_used (constrained_class));
8869                                                         CHECK_CFG_EXCEPTION;
8870                                                 }
8871                                         }
8872                                         virtual_ = 0;
8873                                 }
8874                                 constrained_class = NULL;
8875                         }
8876
8877                         if (check_call_signature (cfg, fsig, sp))
8878                                 UNVERIFIED;
8879
8880                         if ((cmethod->klass->parent == mono_defaults.multicastdelegate_class) && !strcmp (cmethod->name, "Invoke"))
8881                                 delegate_invoke = TRUE;
8882
8883                         if ((cfg->opt & MONO_OPT_INTRINS) && (ins = mini_emit_inst_for_sharable_method (cfg, cmethod, fsig, sp))) {
8884                                 if (!MONO_TYPE_IS_VOID (fsig->ret)) {
8885                                         type_to_eval_stack_type ((cfg), fsig->ret, ins);
8886                                         emit_widen = FALSE;
8887                                 }
8888
8889                                 goto call_end;
8890                         }
8891
8892                         /* 
8893                          * If the callee is a shared method, then its static cctor
8894                          * might not get called after the call was patched.
8895                          */
8896                         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)) {
8897                                 emit_class_init (cfg, cmethod->klass);
8898                                 CHECK_TYPELOAD (cmethod->klass);
8899                         }
8900
8901                         check_method_sharing (cfg, cmethod, &pass_vtable, &pass_mrgctx);
8902
8903                         if (cfg->gshared) {
8904                                 MonoGenericContext *cmethod_context = mono_method_get_context (cmethod);
8905
8906                                 context_used = mini_method_check_context_used (cfg, cmethod);
8907
8908                                 if (context_used && mono_class_is_interface (cmethod->klass)) {
8909                                         /* Generic method interface
8910                                            calls are resolved via a
8911                                            helper function and don't
8912                                            need an imt. */
8913                                         if (!cmethod_context || !cmethod_context->method_inst)
8914                                                 pass_imt_from_rgctx = TRUE;
8915                                 }
8916
8917                                 /*
8918                                  * If a shared method calls another
8919                                  * shared method then the caller must
8920                                  * have a generic sharing context
8921                                  * because the magic trampoline
8922                                  * requires it.  FIXME: We shouldn't
8923                                  * have to force the vtable/mrgctx
8924                                  * variable here.  Instead there
8925                                  * should be a flag in the cfg to
8926                                  * request a generic sharing context.
8927                                  */
8928                                 if (context_used &&
8929                                                 ((cfg->method->flags & METHOD_ATTRIBUTE_STATIC) || cfg->method->klass->valuetype))
8930                                         mono_get_vtable_var (cfg);
8931                         }
8932
8933                         if (pass_vtable) {
8934                                 if (context_used) {
8935                                         vtable_arg = mini_emit_get_rgctx_klass (cfg, context_used, cmethod->klass, MONO_RGCTX_INFO_VTABLE);
8936                                 } else {
8937                                         MonoVTable *vtable = mono_class_vtable (cfg->domain, cmethod->klass);
8938
8939                                         CHECK_TYPELOAD (cmethod->klass);
8940                                         EMIT_NEW_VTABLECONST (cfg, vtable_arg, vtable);
8941                                 }
8942                         }
8943
8944                         if (pass_mrgctx) {
8945                                 g_assert (!vtable_arg);
8946
8947                                 if (!cfg->compile_aot) {
8948                                         /* 
8949                                          * emit_get_rgctx_method () calls mono_class_vtable () so check 
8950                                          * for type load errors before.
8951                                          */
8952                                         mono_class_setup_vtable (cmethod->klass);
8953                                         CHECK_TYPELOAD (cmethod->klass);
8954                                 }
8955
8956                                 vtable_arg = emit_get_rgctx_method (cfg, context_used, cmethod, MONO_RGCTX_INFO_METHOD_RGCTX);
8957
8958                                 /* !marshalbyref is needed to properly handle generic methods + remoting */
8959                                 if ((!(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) ||
8960                                          MONO_METHOD_IS_FINAL (cmethod)) &&
8961                                         !mono_class_is_marshalbyref (cmethod->klass)) {
8962                                         if (virtual_)
8963                                                 check_this = TRUE;
8964                                         virtual_ = 0;
8965                                 }
8966                         }
8967
8968                         if (pass_imt_from_rgctx) {
8969                                 g_assert (!pass_vtable);
8970
8971                                 imt_arg = emit_get_rgctx_method (cfg, context_used,
8972                                         cmethod, MONO_RGCTX_INFO_METHOD);
8973                         }
8974
8975                         if (check_this)
8976                                 MONO_EMIT_NEW_CHECK_THIS (cfg, sp [0]->dreg);
8977
8978                         /* Calling virtual generic methods */
8979                         if (virtual_ && (cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) &&
8980                             !(MONO_METHOD_IS_FINAL (cmethod) && 
8981                               cmethod->wrapper_type != MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK) &&
8982                             fsig->generic_param_count && 
8983                                 !(cfg->gsharedvt && mini_is_gsharedvt_signature (fsig)) &&
8984                                 !cfg->llvm_only) {
8985                                 MonoInst *this_temp, *this_arg_temp, *store;
8986                                 MonoInst *iargs [4];
8987
8988                                 g_assert (fsig->is_inflated);
8989
8990                                 /* Prevent inlining of methods that contain indirect calls */
8991                                 INLINE_FAILURE ("virtual generic call");
8992
8993                                 if (cfg->gsharedvt && mini_is_gsharedvt_signature (fsig))
8994                                         GSHAREDVT_FAILURE (*ip);
8995
8996                                 if (cfg->backend->have_generalized_imt_trampoline && cfg->backend->gshared_supported && cmethod->wrapper_type == MONO_WRAPPER_NONE) {
8997                                         g_assert (!imt_arg);
8998                                         if (!context_used)
8999                                                 g_assert (cmethod->is_inflated);
9000                                         imt_arg = emit_get_rgctx_method (cfg, context_used,
9001                                                                                                          cmethod, MONO_RGCTX_INFO_METHOD);
9002                                         ins = mono_emit_method_call_full (cfg, cmethod, fsig, FALSE, sp, sp [0], imt_arg, NULL);
9003                                 } else {
9004                                         this_temp = mono_compile_create_var (cfg, type_from_stack_type (sp [0]), OP_LOCAL);
9005                                         NEW_TEMPSTORE (cfg, store, this_temp->inst_c0, sp [0]);
9006                                         MONO_ADD_INS (cfg->cbb, store);
9007
9008                                         /* FIXME: This should be a managed pointer */
9009                                         this_arg_temp = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
9010
9011                                         EMIT_NEW_TEMPLOAD (cfg, iargs [0], this_temp->inst_c0);
9012                                         iargs [1] = emit_get_rgctx_method (cfg, context_used,
9013                                                                                                            cmethod, MONO_RGCTX_INFO_METHOD);
9014                                         EMIT_NEW_TEMPLOADA (cfg, iargs [2], this_arg_temp->inst_c0);
9015                                         addr = mono_emit_jit_icall (cfg,
9016                                                                                                 mono_helper_compile_generic_method, iargs);
9017
9018                                         EMIT_NEW_TEMPLOAD (cfg, sp [0], this_arg_temp->inst_c0);
9019
9020                                         ins = (MonoInst*)mono_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
9021                                 }
9022
9023                                 goto call_end;
9024                         }
9025
9026                         /*
9027                          * Implement a workaround for the inherent races involved in locking:
9028                          * Monitor.Enter ()
9029                          * try {
9030                          * } finally {
9031                          *    Monitor.Exit ()
9032                          * }
9033                          * If a thread abort happens between the call to Monitor.Enter () and the start of the
9034                          * try block, the Exit () won't be executed, see:
9035                          * http://www.bluebytesoftware.com/blog/2007/01/30/MonitorEnterThreadAbortsAndOrphanedLocks.aspx
9036                          * To work around this, we extend such try blocks to include the last x bytes
9037                          * of the Monitor.Enter () call.
9038                          */
9039                         if (cmethod->klass == mono_defaults.monitor_class && !strcmp (cmethod->name, "Enter") && mono_method_signature (cmethod)->param_count == 1) {
9040                                 MonoBasicBlock *tbb;
9041
9042                                 GET_BBLOCK (cfg, tbb, ip + 5);
9043                                 /* 
9044                                  * Only extend try blocks with a finally, to avoid catching exceptions thrown
9045                                  * from Monitor.Enter like ArgumentNullException.
9046                                  */
9047                                 if (tbb->try_start && MONO_REGION_FLAGS(tbb->region) == MONO_EXCEPTION_CLAUSE_FINALLY) {
9048                                         /* Mark this bblock as needing to be extended */
9049                                         tbb->extend_try_block = TRUE;
9050                                 }
9051                         }
9052
9053                         /* Conversion to a JIT intrinsic */
9054                         if ((cfg->opt & MONO_OPT_INTRINS) && (ins = mini_emit_inst_for_method (cfg, cmethod, fsig, sp))) {
9055                                 if (!MONO_TYPE_IS_VOID (fsig->ret)) {
9056                                         type_to_eval_stack_type ((cfg), fsig->ret, ins);
9057                                         emit_widen = FALSE;
9058                                 }
9059                                 goto call_end;
9060                         }
9061                         CHECK_CFG_ERROR;
9062                         
9063                         /* Inlining */
9064                         if ((cfg->opt & MONO_OPT_INLINE) &&
9065                                 (!virtual_ || !(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) || MONO_METHOD_IS_FINAL (cmethod)) &&
9066                             mono_method_check_inlining (cfg, cmethod)) {
9067                                 int costs;
9068                                 gboolean always = FALSE;
9069
9070                                 if ((cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
9071                                         (cmethod->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
9072                                         /* Prevent inlining of methods that call wrappers */
9073                                         INLINE_FAILURE ("wrapper call");
9074                                         cmethod = mono_marshal_get_native_wrapper (cmethod, TRUE, FALSE);
9075                                         always = TRUE;
9076                                 }
9077
9078                                 costs = inline_method (cfg, cmethod, fsig, sp, ip, cfg->real_offset, always);
9079                                 if (costs) {
9080                                         cfg->real_offset += 5;
9081
9082                                         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
9083                                                 /* *sp is already set by inline_method */
9084                                                 sp++;
9085                                                 push_res = FALSE;
9086                                         }
9087
9088                                         inline_costs += costs;
9089
9090                                         goto call_end;
9091                                 }
9092                         }
9093
9094                         /* Tail recursion elimination */
9095                         if ((cfg->opt & MONO_OPT_TAILC) && call_opcode == CEE_CALL && cmethod == method && ip [5] == CEE_RET && !vtable_arg) {
9096                                 gboolean has_vtargs = FALSE;
9097                                 int i;
9098
9099                                 /* Prevent inlining of methods with tail calls (the call stack would be altered) */
9100                                 INLINE_FAILURE ("tail call");
9101
9102                                 /* keep it simple */
9103                                 for (i =  fsig->param_count - 1; i >= 0; i--) {
9104                                         if (MONO_TYPE_ISSTRUCT (mono_method_signature (cmethod)->params [i])) 
9105                                                 has_vtargs = TRUE;
9106                                 }
9107
9108                                 if (!has_vtargs) {
9109                                         if (need_seq_point) {
9110                                                 emit_seq_point (cfg, method, ip, FALSE, TRUE);
9111                                                 need_seq_point = FALSE;
9112                                         }
9113                                         for (i = 0; i < n; ++i)
9114                                                 EMIT_NEW_ARGSTORE (cfg, ins, i, sp [i]);
9115                                         MONO_INST_NEW (cfg, ins, OP_BR);
9116                                         MONO_ADD_INS (cfg->cbb, ins);
9117                                         tblock = start_bblock->out_bb [0];
9118                                         link_bblock (cfg, cfg->cbb, tblock);
9119                                         ins->inst_target_bb = tblock;
9120                                         start_new_bblock = 1;
9121
9122                                         /* skip the CEE_RET, too */
9123                                         if (ip_in_bb (cfg, cfg->cbb, ip + 5))
9124                                                 skip_ret = TRUE;
9125                                         push_res = FALSE;
9126                                         goto call_end;
9127                                 }
9128                         }
9129
9130                         inline_costs += 10 * num_calls++;
9131
9132                         /*
9133                          * Synchronized wrappers.
9134                          * Its hard to determine where to replace a method with its synchronized
9135                          * wrapper without causing an infinite recursion. The current solution is
9136                          * to add the synchronized wrapper in the trampolines, and to
9137                          * change the called method to a dummy wrapper, and resolve that wrapper
9138                          * to the real method in mono_jit_compile_method ().
9139                          */
9140                         if (cfg->method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED) {
9141                                 MonoMethod *orig = mono_marshal_method_from_wrapper (cfg->method);
9142                                 if (cmethod == orig || (cmethod->is_inflated && mono_method_get_declaring_generic_method (cmethod) == orig))
9143                                         cmethod = mono_marshal_get_synchronized_inner_wrapper (cmethod);
9144                         }
9145
9146                         /*
9147                          * Making generic calls out of gsharedvt methods.
9148                          * This needs to be used for all generic calls, not just ones with a gsharedvt signature, to avoid
9149                          * patching gshared method addresses into a gsharedvt method.
9150                          */
9151                         if (cfg->gsharedvt && (mini_is_gsharedvt_signature (fsig) || cmethod->is_inflated || mono_class_is_ginst (cmethod->klass)) &&
9152                                 !(cmethod->klass->rank && cmethod->klass->byval_arg.type != MONO_TYPE_SZARRAY) &&
9153                                 (!(cfg->llvm_only && virtual_ && (cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL)))) {
9154                                 MonoRgctxInfoType info_type;
9155
9156                                 if (virtual_) {
9157                                         //if (mono_class_is_interface (cmethod->klass))
9158                                                 //GSHAREDVT_FAILURE (*ip);
9159                                         // disable for possible remoting calls
9160                                         if (fsig->hasthis && (mono_class_is_marshalbyref (method->klass) || method->klass == mono_defaults.object_class))
9161                                                 GSHAREDVT_FAILURE (*ip);
9162                                         if (fsig->generic_param_count) {
9163                                                 /* virtual generic call */
9164                                                 g_assert (!imt_arg);
9165                                                 /* Same as the virtual generic case above */
9166                                                 imt_arg = emit_get_rgctx_method (cfg, context_used,
9167                                                                                                                  cmethod, MONO_RGCTX_INFO_METHOD);
9168                                                 /* This is not needed, as the trampoline code will pass one, and it might be passed in the same reg as the imt arg */
9169                                                 vtable_arg = NULL;
9170                                         } else if (mono_class_is_interface (cmethod->klass) && !imt_arg) {
9171                                                 /* This can happen when we call a fully instantiated iface method */
9172                                                 imt_arg = emit_get_rgctx_method (cfg, context_used,
9173                                                                                                                  cmethod, MONO_RGCTX_INFO_METHOD);
9174                                                 vtable_arg = NULL;
9175                                         }
9176                                 }
9177
9178                                 if ((cmethod->klass->parent == mono_defaults.multicastdelegate_class) && (!strcmp (cmethod->name, "Invoke")))
9179                                         keep_this_alive = sp [0];
9180
9181                                 if (virtual_ && (cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL))
9182                                         info_type = MONO_RGCTX_INFO_METHOD_GSHAREDVT_OUT_TRAMPOLINE_VIRT;
9183                                 else
9184                                         info_type = MONO_RGCTX_INFO_METHOD_GSHAREDVT_OUT_TRAMPOLINE;
9185                                 addr = emit_get_rgctx_gsharedvt_call (cfg, context_used, fsig, cmethod, info_type);
9186
9187                                 if (cfg->llvm_only) {
9188                                         // FIXME: Avoid initializing vtable_arg
9189                                         ins = emit_llvmonly_calli (cfg, fsig, sp, addr);
9190                                 } else {
9191                                         ins = (MonoInst*)mono_emit_calli (cfg, fsig, sp, addr, imt_arg, vtable_arg);
9192                                 }
9193                                 goto call_end;
9194                         }
9195
9196                         /* Generic sharing */
9197
9198                         /*
9199                          * Use this if the callee is gsharedvt sharable too, since
9200                          * at runtime we might find an instantiation so the call cannot
9201                          * be patched (the 'no_patch' code path in mini-trampolines.c).
9202                          */
9203                         if (context_used && !imt_arg && !array_rank && !delegate_invoke &&
9204                                 (!mono_method_is_generic_sharable_full (cmethod, TRUE, FALSE, FALSE) ||
9205                                  !mono_class_generic_sharing_enabled (cmethod->klass)) &&
9206                                 (!virtual_ || MONO_METHOD_IS_FINAL (cmethod) ||
9207                                  !(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL))) {
9208                                 INLINE_FAILURE ("gshared");
9209
9210                                 g_assert (cfg->gshared && cmethod);
9211                                 g_assert (!addr);
9212
9213                                 /*
9214                                  * We are compiling a call to a
9215                                  * generic method from shared code,
9216                                  * which means that we have to look up
9217                                  * the method in the rgctx and do an
9218                                  * indirect call.
9219                                  */
9220                                 if (fsig->hasthis)
9221                                         MONO_EMIT_NEW_CHECK_THIS (cfg, sp [0]->dreg);
9222
9223                                 if (cfg->llvm_only) {
9224                                         if (cfg->gsharedvt && mini_is_gsharedvt_variable_signature (fsig))
9225                                                 addr = emit_get_rgctx_method (cfg, context_used, cmethod, MONO_RGCTX_INFO_GSHAREDVT_OUT_WRAPPER);
9226                                         else
9227                                                 addr = emit_get_rgctx_method (cfg, context_used, cmethod, MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
9228                                         // FIXME: Avoid initializing imt_arg/vtable_arg
9229                                         ins = emit_llvmonly_calli (cfg, fsig, sp, addr);
9230                                 } else {
9231                                         addr = emit_get_rgctx_method (cfg, context_used, cmethod, MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
9232                                         ins = (MonoInst*)mono_emit_calli (cfg, fsig, sp, addr, imt_arg, vtable_arg);
9233                                 }
9234                                 goto call_end;
9235                         }
9236
9237                         /* Direct calls to icalls */
9238                         if (direct_icall) {
9239                                 MonoMethod *wrapper;
9240                                 int costs;
9241
9242                                 /* Inline the wrapper */
9243                                 wrapper = mono_marshal_get_native_wrapper (cmethod, TRUE, cfg->compile_aot);
9244
9245                                 costs = inline_method (cfg, wrapper, fsig, sp, ip, cfg->real_offset, TRUE);
9246                                 g_assert (costs > 0);
9247                                 cfg->real_offset += 5;
9248
9249                                 if (!MONO_TYPE_IS_VOID (fsig->ret)) {
9250                                         /* *sp is already set by inline_method */
9251                                         sp++;
9252                                         push_res = FALSE;
9253                                 }
9254
9255                                 inline_costs += costs;
9256
9257                                 goto call_end;
9258                         }
9259                                         
9260                         /* Array methods */
9261                         if (array_rank) {
9262                                 MonoInst *addr;
9263
9264                                 if (strcmp (cmethod->name, "Set") == 0) { /* array Set */ 
9265                                         MonoInst *val = sp [fsig->param_count];
9266
9267                                         if (val->type == STACK_OBJ) {
9268                                                 MonoInst *iargs [2];
9269
9270                                                 iargs [0] = sp [0];
9271                                                 iargs [1] = val;
9272                                                 
9273                                                 mono_emit_jit_icall (cfg, mono_helper_stelem_ref_check, iargs);
9274                                         }
9275                                         
9276                                         addr = mini_emit_ldelema_ins (cfg, cmethod, sp, ip, TRUE);
9277                                         EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, fsig->params [fsig->param_count - 1], addr->dreg, 0, val->dreg);
9278                                         if (cfg->gen_write_barriers && val->type == STACK_OBJ && !MONO_INS_IS_PCONST_NULL (val))
9279                                                 emit_write_barrier (cfg, addr, val);
9280                                         if (cfg->gen_write_barriers && mini_is_gsharedvt_klass (cmethod->klass))
9281                                                 GSHAREDVT_FAILURE (*ip);
9282                                 } else if (strcmp (cmethod->name, "Get") == 0) { /* array Get */
9283                                         addr = mini_emit_ldelema_ins (cfg, cmethod, sp, ip, FALSE);
9284
9285                                         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, fsig->ret, addr->dreg, 0);
9286                                 } else if (strcmp (cmethod->name, "Address") == 0) { /* array Address */
9287                                         if (!cmethod->klass->element_class->valuetype && !readonly)
9288                                                 mini_emit_check_array_type (cfg, sp [0], cmethod->klass);
9289                                         CHECK_TYPELOAD (cmethod->klass);
9290                                         
9291                                         readonly = FALSE;
9292                                         addr = mini_emit_ldelema_ins (cfg, cmethod, sp, ip, FALSE);
9293                                         ins = addr;
9294                                 } else {
9295                                         g_assert_not_reached ();
9296                                 }
9297
9298                                 emit_widen = FALSE;
9299                                 goto call_end;
9300                         }
9301
9302                         ins = mini_redirect_call (cfg, cmethod, fsig, sp, virtual_ ? sp [0] : NULL);
9303                         if (ins)
9304                                 goto call_end;
9305
9306                         /* Tail prefix / tail call optimization */
9307
9308                         /* FIXME: Enabling TAILC breaks some inlining/stack trace/etc tests */
9309                         /* FIXME: runtime generic context pointer for jumps? */
9310                         /* FIXME: handle this for generic sharing eventually */
9311                         if ((ins_flag & MONO_INST_TAILCALL) &&
9312                                 !vtable_arg && !cfg->gshared && is_supported_tail_call (cfg, method, cmethod, fsig, call_opcode))
9313                                 supported_tail_call = TRUE;
9314
9315                         if (supported_tail_call) {
9316                                 MonoCallInst *call;
9317
9318                                 /* Prevent inlining of methods with tail calls (the call stack would be altered) */
9319                                 INLINE_FAILURE ("tail call");
9320
9321                                 //printf ("HIT: %s -> %s\n", mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
9322
9323                                 if (cfg->backend->have_op_tail_call) {
9324                                         /* Handle tail calls similarly to normal calls */
9325                                         tail_call = TRUE;
9326                                 } else {
9327                                         emit_instrumentation_call (cfg, mono_profiler_method_leave);
9328
9329                                         MONO_INST_NEW_CALL (cfg, call, OP_JMP);
9330                                         call->tail_call = TRUE;
9331                                         call->method = cmethod;
9332                                         call->signature = mono_method_signature (cmethod);
9333
9334                                         /*
9335                                          * We implement tail calls by storing the actual arguments into the 
9336                                          * argument variables, then emitting a CEE_JMP.
9337                                          */
9338                                         for (i = 0; i < n; ++i) {
9339                                                 /* Prevent argument from being register allocated */
9340                                                 arg_array [i]->flags |= MONO_INST_VOLATILE;
9341                                                 EMIT_NEW_ARGSTORE (cfg, ins, i, sp [i]);
9342                                         }
9343                                         ins = (MonoInst*)call;
9344                                         ins->inst_p0 = cmethod;
9345                                         ins->inst_p1 = arg_array [0];
9346                                         MONO_ADD_INS (cfg->cbb, ins);
9347                                         link_bblock (cfg, cfg->cbb, end_bblock);
9348                                         start_new_bblock = 1;
9349
9350                                         // FIXME: Eliminate unreachable epilogs
9351
9352                                         /*
9353                                          * OP_TAILCALL has no return value, so skip the CEE_RET if it is
9354                                          * only reachable from this call.
9355                                          */
9356                                         GET_BBLOCK (cfg, tblock, ip + 5);
9357                                         if (tblock == cfg->cbb || tblock->in_count == 0)
9358                                                 skip_ret = TRUE;
9359                                         push_res = FALSE;
9360
9361                                         goto call_end;
9362                                 }
9363                         }
9364
9365                         /*
9366                          * Virtual calls in llvm-only mode.
9367                          */
9368                         if (cfg->llvm_only && virtual_ && cmethod && (cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
9369                                 ins = emit_llvmonly_virtual_call (cfg, cmethod, fsig, context_used, sp);
9370                                 goto call_end;
9371                         }
9372
9373                         /* Common call */
9374                         if (!(cmethod->iflags & METHOD_IMPL_ATTRIBUTE_AGGRESSIVE_INLINING))
9375                                 INLINE_FAILURE ("call");
9376                         ins = mono_emit_method_call_full (cfg, cmethod, fsig, tail_call, sp, virtual_ ? sp [0] : NULL,
9377                                                                                           imt_arg, vtable_arg);
9378
9379                         if (tail_call && !cfg->llvm_only) {
9380                                 link_bblock (cfg, cfg->cbb, end_bblock);
9381                                 start_new_bblock = 1;
9382
9383                                 // FIXME: Eliminate unreachable epilogs
9384
9385                                 /*
9386                                  * OP_TAILCALL has no return value, so skip the CEE_RET if it is
9387                                  * only reachable from this call.
9388                                  */
9389                                 GET_BBLOCK (cfg, tblock, ip + 5);
9390                                 if (tblock == cfg->cbb || tblock->in_count == 0)
9391                                         skip_ret = TRUE;
9392                                 push_res = FALSE;
9393                         }
9394
9395                         call_end:
9396
9397                         /* End of call, INS should contain the result of the call, if any */
9398
9399                         if (push_res && !MONO_TYPE_IS_VOID (fsig->ret)) {
9400                                 g_assert (ins);
9401                                 if (emit_widen)
9402                                         *sp++ = mono_emit_widen_call_res (cfg, ins, fsig);
9403                                 else
9404                                         *sp++ = ins;
9405                         }
9406
9407                         if (keep_this_alive) {
9408                                 MonoInst *dummy_use;
9409
9410                                 /* See mono_emit_method_call_full () */
9411                                 EMIT_NEW_DUMMY_USE (cfg, dummy_use, keep_this_alive);
9412                         }
9413
9414                         if (cfg->llvm_only && cmethod && method_needs_stack_walk (cfg, cmethod)) {
9415                                 /*
9416                                  * Clang can convert these calls to tail calls which screw up the stack
9417                                  * walk. This happens even when the -fno-optimize-sibling-calls
9418                                  * option is passed to clang.
9419                                  * Work around this by emitting a dummy call.
9420                                  */
9421                                 mono_emit_jit_icall (cfg, mono_dummy_jit_icall, NULL);
9422                         }
9423
9424                         CHECK_CFG_EXCEPTION;
9425
9426                         ip += 5;
9427                         if (skip_ret) {
9428                                 g_assert (*ip == CEE_RET);
9429                                 ip += 1;
9430                         }
9431                         ins_flag = 0;
9432                         constrained_class = NULL;
9433                         if (need_seq_point)
9434                                 emit_seq_point (cfg, method, ip, FALSE, TRUE);
9435                         break;
9436                 }
9437                 case CEE_RET:
9438                         if (cfg->method != method) {
9439                                 /* return from inlined method */
9440                                 /* 
9441                                  * If in_count == 0, that means the ret is unreachable due to
9442                                  * being preceeded by a throw. In that case, inline_method () will
9443                                  * handle setting the return value 
9444                                  * (test case: test_0_inline_throw ()).
9445                                  */
9446                                 if (return_var && cfg->cbb->in_count) {
9447                                         MonoType *ret_type = mono_method_signature (method)->ret;
9448
9449                                         MonoInst *store;
9450                                         CHECK_STACK (1);
9451                                         --sp;
9452
9453                                         if ((method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD || method->wrapper_type == MONO_WRAPPER_NONE) && target_type_is_incompatible (cfg, ret_type, *sp))
9454                                                 UNVERIFIED;
9455
9456                                         //g_assert (returnvar != -1);
9457                                         EMIT_NEW_TEMPSTORE (cfg, store, return_var->inst_c0, *sp);
9458                                         cfg->ret_var_set = TRUE;
9459                                 } 
9460                         } else {
9461                                 emit_instrumentation_call (cfg, mono_profiler_method_leave);
9462
9463                                 if (cfg->lmf_var && cfg->cbb->in_count && !cfg->llvm_only)
9464                                         emit_pop_lmf (cfg);
9465
9466                                 if (cfg->ret) {
9467                                         MonoType *ret_type = mini_get_underlying_type (mono_method_signature (method)->ret);
9468
9469                                         if (seq_points && !sym_seq_points) {
9470                                                 /* 
9471                                                  * Place a seq point here too even through the IL stack is not
9472                                                  * empty, so a step over on
9473                                                  * call <FOO>
9474                                                  * ret
9475                                                  * will work correctly.
9476                                                  */
9477                                                 NEW_SEQ_POINT (cfg, ins, ip - header->code, TRUE);
9478                                                 MONO_ADD_INS (cfg->cbb, ins);
9479                                         }
9480
9481                                         g_assert (!return_var);
9482                                         CHECK_STACK (1);
9483                                         --sp;
9484
9485                                         if ((method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD || method->wrapper_type == MONO_WRAPPER_NONE) && target_type_is_incompatible (cfg, ret_type, *sp))
9486                                                 UNVERIFIED;
9487
9488                                         emit_setret (cfg, *sp);
9489                                 }
9490                         }
9491                         if (sp != stack_start)
9492                                 UNVERIFIED;
9493                         MONO_INST_NEW (cfg, ins, OP_BR);
9494                         ip++;
9495                         ins->inst_target_bb = end_bblock;
9496                         MONO_ADD_INS (cfg->cbb, ins);
9497                         link_bblock (cfg, cfg->cbb, end_bblock);
9498                         start_new_bblock = 1;
9499                         break;
9500                 case CEE_BR_S:
9501                         CHECK_OPSIZE (2);
9502                         MONO_INST_NEW (cfg, ins, OP_BR);
9503                         ip++;
9504                         target = ip + 1 + (signed char)(*ip);
9505                         ++ip;
9506                         GET_BBLOCK (cfg, tblock, target);
9507                         link_bblock (cfg, cfg->cbb, tblock);
9508                         ins->inst_target_bb = tblock;
9509                         if (sp != stack_start) {
9510                                 handle_stack_args (cfg, stack_start, sp - stack_start);
9511                                 sp = stack_start;
9512                                 CHECK_UNVERIFIABLE (cfg);
9513                         }
9514                         MONO_ADD_INS (cfg->cbb, ins);
9515                         start_new_bblock = 1;
9516                         inline_costs += BRANCH_COST;
9517                         break;
9518                 case CEE_BEQ_S:
9519                 case CEE_BGE_S:
9520                 case CEE_BGT_S:
9521                 case CEE_BLE_S:
9522                 case CEE_BLT_S:
9523                 case CEE_BNE_UN_S:
9524                 case CEE_BGE_UN_S:
9525                 case CEE_BGT_UN_S:
9526                 case CEE_BLE_UN_S:
9527                 case CEE_BLT_UN_S:
9528                         CHECK_OPSIZE (2);
9529                         CHECK_STACK (2);
9530                         MONO_INST_NEW (cfg, ins, *ip + BIG_BRANCH_OFFSET);
9531                         ip++;
9532                         target = ip + 1 + *(signed char*)ip;
9533                         ip++;
9534
9535                         ADD_BINCOND (NULL);
9536
9537                         sp = stack_start;
9538                         inline_costs += BRANCH_COST;
9539                         break;
9540                 case CEE_BR:
9541                         CHECK_OPSIZE (5);
9542                         MONO_INST_NEW (cfg, ins, OP_BR);
9543                         ip++;
9544
9545                         target = ip + 4 + (gint32)read32(ip);
9546                         ip += 4;
9547                         GET_BBLOCK (cfg, tblock, target);
9548                         link_bblock (cfg, cfg->cbb, tblock);
9549                         ins->inst_target_bb = tblock;
9550                         if (sp != stack_start) {
9551                                 handle_stack_args (cfg, stack_start, sp - stack_start);
9552                                 sp = stack_start;
9553                                 CHECK_UNVERIFIABLE (cfg);
9554                         }
9555
9556                         MONO_ADD_INS (cfg->cbb, ins);
9557
9558                         start_new_bblock = 1;
9559                         inline_costs += BRANCH_COST;
9560                         break;
9561                 case CEE_BRFALSE_S:
9562                 case CEE_BRTRUE_S:
9563                 case CEE_BRFALSE:
9564                 case CEE_BRTRUE: {
9565                         MonoInst *cmp;
9566                         gboolean is_short = ((*ip) == CEE_BRFALSE_S) || ((*ip) == CEE_BRTRUE_S);
9567                         gboolean is_true = ((*ip) == CEE_BRTRUE_S) || ((*ip) == CEE_BRTRUE);
9568                         guint32 opsize = is_short ? 1 : 4;
9569
9570                         CHECK_OPSIZE (opsize);
9571                         CHECK_STACK (1);
9572                         if (sp [-1]->type == STACK_VTYPE || sp [-1]->type == STACK_R8)
9573                                 UNVERIFIED;
9574                         ip ++;
9575                         target = ip + opsize + (is_short ? *(signed char*)ip : (gint32)read32(ip));
9576                         ip += opsize;
9577
9578                         sp--;
9579
9580                         GET_BBLOCK (cfg, tblock, target);
9581                         link_bblock (cfg, cfg->cbb, tblock);
9582                         GET_BBLOCK (cfg, tblock, ip);
9583                         link_bblock (cfg, cfg->cbb, tblock);
9584
9585                         if (sp != stack_start) {
9586                                 handle_stack_args (cfg, stack_start, sp - stack_start);
9587                                 CHECK_UNVERIFIABLE (cfg);
9588                         }
9589
9590                         MONO_INST_NEW(cfg, cmp, OP_ICOMPARE_IMM);
9591                         cmp->sreg1 = sp [0]->dreg;
9592                         type_from_op (cfg, cmp, sp [0], NULL);
9593                         CHECK_TYPE (cmp);
9594
9595 #if SIZEOF_REGISTER == 4
9596                         if (cmp->opcode == OP_LCOMPARE_IMM) {
9597                                 /* Convert it to OP_LCOMPARE */
9598                                 MONO_INST_NEW (cfg, ins, OP_I8CONST);
9599                                 ins->type = STACK_I8;
9600                                 ins->dreg = alloc_dreg (cfg, STACK_I8);
9601                                 ins->inst_l = 0;
9602                                 MONO_ADD_INS (cfg->cbb, ins);
9603                                 cmp->opcode = OP_LCOMPARE;
9604                                 cmp->sreg2 = ins->dreg;
9605                         }
9606 #endif
9607                         MONO_ADD_INS (cfg->cbb, cmp);
9608
9609                         MONO_INST_NEW (cfg, ins, is_true ? CEE_BNE_UN : CEE_BEQ);
9610                         type_from_op (cfg, ins, sp [0], NULL);
9611                         MONO_ADD_INS (cfg->cbb, ins);
9612                         ins->inst_many_bb = (MonoBasicBlock **)mono_mempool_alloc (cfg->mempool, sizeof(gpointer)*2);
9613                         GET_BBLOCK (cfg, tblock, target);
9614                         ins->inst_true_bb = tblock;
9615                         GET_BBLOCK (cfg, tblock, ip);
9616                         ins->inst_false_bb = tblock;
9617                         start_new_bblock = 2;
9618
9619                         sp = stack_start;
9620                         inline_costs += BRANCH_COST;
9621                         break;
9622                 }
9623                 case CEE_BEQ:
9624                 case CEE_BGE:
9625                 case CEE_BGT:
9626                 case CEE_BLE:
9627                 case CEE_BLT:
9628                 case CEE_BNE_UN:
9629                 case CEE_BGE_UN:
9630                 case CEE_BGT_UN:
9631                 case CEE_BLE_UN:
9632                 case CEE_BLT_UN:
9633                         CHECK_OPSIZE (5);
9634                         CHECK_STACK (2);
9635                         MONO_INST_NEW (cfg, ins, *ip);
9636                         ip++;
9637                         target = ip + 4 + (gint32)read32(ip);
9638                         ip += 4;
9639
9640                         ADD_BINCOND (NULL);
9641
9642                         sp = stack_start;
9643                         inline_costs += BRANCH_COST;
9644                         break;
9645                 case CEE_SWITCH: {
9646                         MonoInst *src1;
9647                         MonoBasicBlock **targets;
9648                         MonoBasicBlock *default_bblock;
9649                         MonoJumpInfoBBTable *table;
9650                         int offset_reg = alloc_preg (cfg);
9651                         int target_reg = alloc_preg (cfg);
9652                         int table_reg = alloc_preg (cfg);
9653                         int sum_reg = alloc_preg (cfg);
9654                         gboolean use_op_switch;
9655
9656                         CHECK_OPSIZE (5);
9657                         CHECK_STACK (1);
9658                         n = read32 (ip + 1);
9659                         --sp;
9660                         src1 = sp [0];
9661                         if ((src1->type != STACK_I4) && (src1->type != STACK_PTR)) 
9662                                 UNVERIFIED;
9663
9664                         ip += 5;
9665                         CHECK_OPSIZE (n * sizeof (guint32));
9666                         target = ip + n * sizeof (guint32);
9667
9668                         GET_BBLOCK (cfg, default_bblock, target);
9669                         default_bblock->flags |= BB_INDIRECT_JUMP_TARGET;
9670
9671                         targets = (MonoBasicBlock **)mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * n);
9672                         for (i = 0; i < n; ++i) {
9673                                 GET_BBLOCK (cfg, tblock, target + (gint32)read32(ip));
9674                                 targets [i] = tblock;
9675                                 targets [i]->flags |= BB_INDIRECT_JUMP_TARGET;
9676                                 ip += 4;
9677                         }
9678
9679                         if (sp != stack_start) {
9680                                 /* 
9681                                  * Link the current bb with the targets as well, so handle_stack_args
9682                                  * will set their in_stack correctly.
9683                                  */
9684                                 link_bblock (cfg, cfg->cbb, default_bblock);
9685                                 for (i = 0; i < n; ++i)
9686                                         link_bblock (cfg, cfg->cbb, targets [i]);
9687
9688                                 handle_stack_args (cfg, stack_start, sp - stack_start);
9689                                 sp = stack_start;
9690                                 CHECK_UNVERIFIABLE (cfg);
9691
9692                                 /* Undo the links */
9693                                 mono_unlink_bblock (cfg, cfg->cbb, default_bblock);
9694                                 for (i = 0; i < n; ++i)
9695                                         mono_unlink_bblock (cfg, cfg->cbb, targets [i]);
9696                         }
9697
9698                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ICOMPARE_IMM, -1, src1->dreg, n);
9699                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBGE_UN, default_bblock);
9700
9701                         for (i = 0; i < n; ++i)
9702                                 link_bblock (cfg, cfg->cbb, targets [i]);
9703
9704                         table = (MonoJumpInfoBBTable *)mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfoBBTable));
9705                         table->table = targets;
9706                         table->table_size = n;
9707
9708                         use_op_switch = FALSE;
9709 #ifdef TARGET_ARM
9710                         /* ARM implements SWITCH statements differently */
9711                         /* FIXME: Make it use the generic implementation */
9712                         if (!cfg->compile_aot)
9713                                 use_op_switch = TRUE;
9714 #endif
9715
9716                         if (COMPILE_LLVM (cfg))
9717                                 use_op_switch = TRUE;
9718
9719                         cfg->cbb->has_jump_table = 1;
9720
9721                         if (use_op_switch) {
9722                                 MONO_INST_NEW (cfg, ins, OP_SWITCH);
9723                                 ins->sreg1 = src1->dreg;
9724                                 ins->inst_p0 = table;
9725                                 ins->inst_many_bb = targets;
9726                                 ins->klass = (MonoClass *)GUINT_TO_POINTER (n);
9727                                 MONO_ADD_INS (cfg->cbb, ins);
9728                         } else {
9729                                 if (sizeof (gpointer) == 8)
9730                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHL_IMM, offset_reg, src1->dreg, 3);
9731                                 else
9732                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHL_IMM, offset_reg, src1->dreg, 2);
9733
9734 #if SIZEOF_REGISTER == 8
9735                                 /* The upper word might not be zero, and we add it to a 64 bit address later */
9736                                 MONO_EMIT_NEW_UNALU (cfg, OP_ZEXT_I4, offset_reg, offset_reg);
9737 #endif
9738
9739                                 if (cfg->compile_aot) {
9740                                         MONO_EMIT_NEW_AOTCONST (cfg, table_reg, table, MONO_PATCH_INFO_SWITCH);
9741                                 } else {
9742                                         MONO_INST_NEW (cfg, ins, OP_JUMP_TABLE);
9743                                         ins->inst_c1 = MONO_PATCH_INFO_SWITCH;
9744                                         ins->inst_p0 = table;
9745                                         ins->dreg = table_reg;
9746                                         MONO_ADD_INS (cfg->cbb, ins);
9747                                 }
9748
9749                                 /* FIXME: Use load_memindex */
9750                                 MONO_EMIT_NEW_BIALU (cfg, OP_PADD, sum_reg, table_reg, offset_reg);
9751                                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, target_reg, sum_reg, 0);
9752                                 MONO_EMIT_NEW_UNALU (cfg, OP_BR_REG, -1, target_reg);
9753                         }
9754                         start_new_bblock = 1;
9755                         inline_costs += (BRANCH_COST * 2);
9756                         break;
9757                 }
9758                 case CEE_LDIND_I1:
9759                 case CEE_LDIND_U1:
9760                 case CEE_LDIND_I2:
9761                 case CEE_LDIND_U2:
9762                 case CEE_LDIND_I4:
9763                 case CEE_LDIND_U4:
9764                 case CEE_LDIND_I8:
9765                 case CEE_LDIND_I:
9766                 case CEE_LDIND_R4:
9767                 case CEE_LDIND_R8:
9768                 case CEE_LDIND_REF:
9769                         CHECK_STACK (1);
9770                         --sp;
9771
9772                         switch (*ip) {
9773                         case CEE_LDIND_R4:
9774                         case CEE_LDIND_R8:
9775                                 dreg = alloc_freg (cfg);
9776                                 break;
9777                         case CEE_LDIND_I8:
9778                                 dreg = alloc_lreg (cfg);
9779                                 break;
9780                         case CEE_LDIND_REF:
9781                                 dreg = alloc_ireg_ref (cfg);
9782                                 break;
9783                         default:
9784                                 dreg = alloc_preg (cfg);
9785                         }
9786
9787                         NEW_LOAD_MEMBASE (cfg, ins, ldind_to_load_membase (*ip), dreg, sp [0]->dreg, 0);
9788                         ins->type = ldind_type [*ip - CEE_LDIND_I1];
9789                         if (*ip == CEE_LDIND_R4)
9790                                 ins->type = cfg->r4_stack_type;
9791                         ins->flags |= ins_flag;
9792                         MONO_ADD_INS (cfg->cbb, ins);
9793                         *sp++ = ins;
9794                         if (ins_flag & MONO_INST_VOLATILE) {
9795                                 /* Volatile loads have acquire semantics, see 12.6.7 in Ecma 335 */
9796                                 emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_ACQ);
9797                         }
9798                         ins_flag = 0;
9799                         ++ip;
9800                         break;
9801                 case CEE_STIND_REF:
9802                 case CEE_STIND_I1:
9803                 case CEE_STIND_I2:
9804                 case CEE_STIND_I4:
9805                 case CEE_STIND_I8:
9806                 case CEE_STIND_R4:
9807                 case CEE_STIND_R8:
9808                 case CEE_STIND_I:
9809                         CHECK_STACK (2);
9810                         sp -= 2;
9811
9812                         if (ins_flag & MONO_INST_VOLATILE) {
9813                                 /* Volatile stores have release semantics, see 12.6.7 in Ecma 335 */
9814                                 emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_REL);
9815                         }
9816
9817                         NEW_STORE_MEMBASE (cfg, ins, stind_to_store_membase (*ip), sp [0]->dreg, 0, sp [1]->dreg);
9818                         ins->flags |= ins_flag;
9819                         ins_flag = 0;
9820
9821                         MONO_ADD_INS (cfg->cbb, ins);
9822
9823                         if (cfg->gen_write_barriers && *ip == CEE_STIND_REF && method->wrapper_type != MONO_WRAPPER_WRITE_BARRIER && !MONO_INS_IS_PCONST_NULL (sp [1]))
9824                                 emit_write_barrier (cfg, sp [0], sp [1]);
9825
9826                         inline_costs += 1;
9827                         ++ip;
9828                         break;
9829
9830                 case CEE_MUL:
9831                         CHECK_STACK (2);
9832
9833                         MONO_INST_NEW (cfg, ins, (*ip));
9834                         sp -= 2;
9835                         ins->sreg1 = sp [0]->dreg;
9836                         ins->sreg2 = sp [1]->dreg;
9837                         type_from_op (cfg, ins, sp [0], sp [1]);
9838                         CHECK_TYPE (ins);
9839                         ins->dreg = alloc_dreg ((cfg), (MonoStackType)(ins)->type);
9840
9841                         /* Use the immediate opcodes if possible */
9842                         if ((sp [1]->opcode == OP_ICONST) && mono_arch_is_inst_imm (sp [1]->inst_c0)) {
9843                                 int imm_opcode = mono_op_to_op_imm_noemul (ins->opcode);
9844                                 if (imm_opcode != -1) {
9845                                         ins->opcode = imm_opcode;
9846                                         ins->inst_p1 = (gpointer)(gssize)(sp [1]->inst_c0);
9847                                         ins->sreg2 = -1;
9848
9849                                         NULLIFY_INS (sp [1]);
9850                                 }
9851                         }
9852
9853                         MONO_ADD_INS ((cfg)->cbb, (ins));
9854
9855                         *sp++ = mono_decompose_opcode (cfg, ins);
9856                         ip++;
9857                         break;
9858                 case CEE_ADD:
9859                 case CEE_SUB:
9860                 case CEE_DIV:
9861                 case CEE_DIV_UN:
9862                 case CEE_REM:
9863                 case CEE_REM_UN:
9864                 case CEE_AND:
9865                 case CEE_OR:
9866                 case CEE_XOR:
9867                 case CEE_SHL:
9868                 case CEE_SHR:
9869                 case CEE_SHR_UN:
9870                         CHECK_STACK (2);
9871
9872                         MONO_INST_NEW (cfg, ins, (*ip));
9873                         sp -= 2;
9874                         ins->sreg1 = sp [0]->dreg;
9875                         ins->sreg2 = sp [1]->dreg;
9876                         type_from_op (cfg, ins, sp [0], sp [1]);
9877                         CHECK_TYPE (ins);
9878                         add_widen_op (cfg, ins, &sp [0], &sp [1]);
9879                         ins->dreg = alloc_dreg ((cfg), (MonoStackType)(ins)->type);
9880
9881                         /* FIXME: Pass opcode to is_inst_imm */
9882
9883                         /* Use the immediate opcodes if possible */
9884                         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)) {
9885                                 int imm_opcode = mono_op_to_op_imm_noemul (ins->opcode);
9886                                 if (imm_opcode != -1) {
9887                                         ins->opcode = imm_opcode;
9888                                         if (sp [1]->opcode == OP_I8CONST) {
9889 #if SIZEOF_REGISTER == 8
9890                                                 ins->inst_imm = sp [1]->inst_l;
9891 #else
9892                                                 ins->inst_ls_word = sp [1]->inst_ls_word;
9893                                                 ins->inst_ms_word = sp [1]->inst_ms_word;
9894 #endif
9895                                         }
9896                                         else
9897                                                 ins->inst_imm = (gssize)(sp [1]->inst_c0);
9898                                         ins->sreg2 = -1;
9899
9900                                         /* Might be followed by an instruction added by add_widen_op */
9901                                         if (sp [1]->next == NULL)
9902                                                 NULLIFY_INS (sp [1]);
9903                                 }
9904                         }
9905                         MONO_ADD_INS ((cfg)->cbb, (ins));
9906
9907                         *sp++ = mono_decompose_opcode (cfg, ins);
9908                         ip++;
9909                         break;
9910                 case CEE_NEG:
9911                 case CEE_NOT:
9912                 case CEE_CONV_I1:
9913                 case CEE_CONV_I2:
9914                 case CEE_CONV_I4:
9915                 case CEE_CONV_R4:
9916                 case CEE_CONV_R8:
9917                 case CEE_CONV_U4:
9918                 case CEE_CONV_I8:
9919                 case CEE_CONV_U8:
9920                 case CEE_CONV_OVF_I8:
9921                 case CEE_CONV_OVF_U8:
9922                 case CEE_CONV_R_UN:
9923                         CHECK_STACK (1);
9924
9925                         /* Special case this earlier so we have long constants in the IR */
9926                         if ((((*ip) == CEE_CONV_I8) || ((*ip) == CEE_CONV_U8)) && (sp [-1]->opcode == OP_ICONST)) {
9927                                 int data = sp [-1]->inst_c0;
9928                                 sp [-1]->opcode = OP_I8CONST;
9929                                 sp [-1]->type = STACK_I8;
9930 #if SIZEOF_REGISTER == 8
9931                                 if ((*ip) == CEE_CONV_U8)
9932                                         sp [-1]->inst_c0 = (guint32)data;
9933                                 else
9934                                         sp [-1]->inst_c0 = data;
9935 #else
9936                                 sp [-1]->inst_ls_word = data;
9937                                 if ((*ip) == CEE_CONV_U8)
9938                                         sp [-1]->inst_ms_word = 0;
9939                                 else
9940                                         sp [-1]->inst_ms_word = (data < 0) ? -1 : 0;
9941 #endif
9942                                 sp [-1]->dreg = alloc_dreg (cfg, STACK_I8);
9943                         }
9944                         else {
9945                                 ADD_UNOP (*ip);
9946                         }
9947                         ip++;
9948                         break;
9949                 case CEE_CONV_OVF_I4:
9950                 case CEE_CONV_OVF_I1:
9951                 case CEE_CONV_OVF_I2:
9952                 case CEE_CONV_OVF_I:
9953                 case CEE_CONV_OVF_U:
9954                         CHECK_STACK (1);
9955
9956                         if (sp [-1]->type == STACK_R8 || sp [-1]->type == STACK_R4) {
9957                                 ADD_UNOP (CEE_CONV_OVF_I8);
9958                                 ADD_UNOP (*ip);
9959                         } else {
9960                                 ADD_UNOP (*ip);
9961                         }
9962                         ip++;
9963                         break;
9964                 case CEE_CONV_OVF_U1:
9965                 case CEE_CONV_OVF_U2:
9966                 case CEE_CONV_OVF_U4:
9967                         CHECK_STACK (1);
9968
9969                         if (sp [-1]->type == STACK_R8 || sp [-1]->type == STACK_R4) {
9970                                 ADD_UNOP (CEE_CONV_OVF_U8);
9971                                 ADD_UNOP (*ip);
9972                         } else {
9973                                 ADD_UNOP (*ip);
9974                         }
9975                         ip++;
9976                         break;
9977                 case CEE_CONV_OVF_I1_UN:
9978                 case CEE_CONV_OVF_I2_UN:
9979                 case CEE_CONV_OVF_I4_UN:
9980                 case CEE_CONV_OVF_I8_UN:
9981                 case CEE_CONV_OVF_U1_UN:
9982                 case CEE_CONV_OVF_U2_UN:
9983                 case CEE_CONV_OVF_U4_UN:
9984                 case CEE_CONV_OVF_U8_UN:
9985                 case CEE_CONV_OVF_I_UN:
9986                 case CEE_CONV_OVF_U_UN:
9987                 case CEE_CONV_U2:
9988                 case CEE_CONV_U1:
9989                 case CEE_CONV_I:
9990                 case CEE_CONV_U:
9991                         CHECK_STACK (1);
9992                         ADD_UNOP (*ip);
9993                         CHECK_CFG_EXCEPTION;
9994                         ip++;
9995                         break;
9996                 case CEE_ADD_OVF:
9997                 case CEE_ADD_OVF_UN:
9998                 case CEE_MUL_OVF:
9999                 case CEE_MUL_OVF_UN:
10000                 case CEE_SUB_OVF:
10001                 case CEE_SUB_OVF_UN:
10002                         CHECK_STACK (2);
10003                         ADD_BINOP (*ip);
10004                         ip++;
10005                         break;
10006                 case CEE_CPOBJ:
10007                         GSHAREDVT_FAILURE (*ip);
10008                         CHECK_OPSIZE (5);
10009                         CHECK_STACK (2);
10010                         token = read32 (ip + 1);
10011                         klass = mini_get_class (method, token, generic_context);
10012                         CHECK_TYPELOAD (klass);
10013                         sp -= 2;
10014                         if (generic_class_is_reference_type (cfg, klass)) {
10015                                 MonoInst *store, *load;
10016                                 int dreg = alloc_ireg_ref (cfg);
10017
10018                                 NEW_LOAD_MEMBASE (cfg, load, OP_LOAD_MEMBASE, dreg, sp [1]->dreg, 0);
10019                                 load->flags |= ins_flag;
10020                                 MONO_ADD_INS (cfg->cbb, load);
10021
10022                                 NEW_STORE_MEMBASE (cfg, store, OP_STORE_MEMBASE_REG, sp [0]->dreg, 0, dreg);
10023                                 store->flags |= ins_flag;
10024                                 MONO_ADD_INS (cfg->cbb, store);
10025
10026                                 if (cfg->gen_write_barriers && cfg->method->wrapper_type != MONO_WRAPPER_WRITE_BARRIER)
10027                                         emit_write_barrier (cfg, sp [0], sp [1]);
10028                         } else {
10029                                 mini_emit_stobj (cfg, sp [0], sp [1], klass, FALSE);
10030                         }
10031                         ins_flag = 0;
10032                         ip += 5;
10033                         break;
10034                 case CEE_LDOBJ: {
10035                         int loc_index = -1;
10036                         int stloc_len = 0;
10037
10038                         CHECK_OPSIZE (5);
10039                         CHECK_STACK (1);
10040                         --sp;
10041                         token = read32 (ip + 1);
10042                         klass = mini_get_class (method, token, generic_context);
10043                         CHECK_TYPELOAD (klass);
10044
10045                         /* Optimize the common ldobj+stloc combination */
10046                         switch (ip [5]) {
10047                         case CEE_STLOC_S:
10048                                 loc_index = ip [6];
10049                                 stloc_len = 2;
10050                                 break;
10051                         case CEE_STLOC_0:
10052                         case CEE_STLOC_1:
10053                         case CEE_STLOC_2:
10054                         case CEE_STLOC_3:
10055                                 loc_index = ip [5] - CEE_STLOC_0;
10056                                 stloc_len = 1;
10057                                 break;
10058                         default:
10059                                 break;
10060                         }
10061
10062                         if ((loc_index != -1) && ip_in_bb (cfg, cfg->cbb, ip + 5)) {
10063                                 CHECK_LOCAL (loc_index);
10064
10065                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, sp [0]->dreg, 0);
10066                                 ins->dreg = cfg->locals [loc_index]->dreg;
10067                                 ins->flags |= ins_flag;
10068                                 ip += 5;
10069                                 ip += stloc_len;
10070                                 if (ins_flag & MONO_INST_VOLATILE) {
10071                                         /* Volatile loads have acquire semantics, see 12.6.7 in Ecma 335 */
10072                                         emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_ACQ);
10073                                 }
10074                                 ins_flag = 0;
10075                                 break;
10076                         }
10077
10078                         /* Optimize the ldobj+stobj combination */
10079                         /* The reference case ends up being a load+store anyway */
10080                         /* Skip this if the operation is volatile. */
10081                         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)) {
10082                                 CHECK_STACK (1);
10083
10084                                 sp --;
10085
10086                                 mini_emit_stobj (cfg, sp [0], sp [1], klass, FALSE);
10087
10088                                 ip += 5 + 5;
10089                                 ins_flag = 0;
10090                                 break;
10091                         }
10092
10093                         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, sp [0]->dreg, 0);
10094                         ins->flags |= ins_flag;
10095                         *sp++ = ins;
10096
10097                         if (ins_flag & MONO_INST_VOLATILE) {
10098                                 /* Volatile loads have acquire semantics, see 12.6.7 in Ecma 335 */
10099                                 emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_ACQ);
10100                         }
10101
10102                         ip += 5;
10103                         ins_flag = 0;
10104                         inline_costs += 1;
10105                         break;
10106                 }
10107                 case CEE_LDSTR:
10108                         CHECK_STACK_OVF (1);
10109                         CHECK_OPSIZE (5);
10110                         n = read32 (ip + 1);
10111
10112                         if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
10113                                 EMIT_NEW_PCONST (cfg, ins, mono_method_get_wrapper_data (method, n));
10114                                 ins->type = STACK_OBJ;
10115                                 *sp = ins;
10116                         }
10117                         else if (method->wrapper_type != MONO_WRAPPER_NONE) {
10118                                 MonoInst *iargs [1];
10119                                 char *str = (char *)mono_method_get_wrapper_data (method, n);
10120
10121                                 if (cfg->compile_aot)
10122                                         EMIT_NEW_LDSTRLITCONST (cfg, iargs [0], str);
10123                                 else
10124                                         EMIT_NEW_PCONST (cfg, iargs [0], str);
10125                                 *sp = mono_emit_jit_icall (cfg, mono_string_new_wrapper, iargs);
10126                         } else {
10127                                 if (cfg->opt & MONO_OPT_SHARED) {
10128                                         MonoInst *iargs [3];
10129
10130                                         if (cfg->compile_aot) {
10131                                                 cfg->ldstr_list = g_list_prepend (cfg->ldstr_list, GINT_TO_POINTER (n));
10132                                         }
10133                                         EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
10134                                         EMIT_NEW_IMAGECONST (cfg, iargs [1], image);
10135                                         EMIT_NEW_ICONST (cfg, iargs [2], mono_metadata_token_index (n));
10136                                         *sp = mono_emit_jit_icall (cfg, ves_icall_mono_ldstr, iargs);
10137                                         mono_ldstr_checked (cfg->domain, image, mono_metadata_token_index (n), &cfg->error);
10138                                         CHECK_CFG_ERROR;
10139                                 } else {
10140                                         if (cfg->cbb->out_of_line) {
10141                                                 MonoInst *iargs [2];
10142
10143                                                 if (image == mono_defaults.corlib) {
10144                                                         /* 
10145                                                          * Avoid relocations in AOT and save some space by using a 
10146                                                          * version of helper_ldstr specialized to mscorlib.
10147                                                          */
10148                                                         EMIT_NEW_ICONST (cfg, iargs [0], mono_metadata_token_index (n));
10149                                                         *sp = mono_emit_jit_icall (cfg, mono_helper_ldstr_mscorlib, iargs);
10150                                                 } else {
10151                                                         /* Avoid creating the string object */
10152                                                         EMIT_NEW_IMAGECONST (cfg, iargs [0], image);
10153                                                         EMIT_NEW_ICONST (cfg, iargs [1], mono_metadata_token_index (n));
10154                                                         *sp = mono_emit_jit_icall (cfg, mono_helper_ldstr, iargs);
10155                                                 }
10156                                         } 
10157                                         else
10158                                         if (cfg->compile_aot) {
10159                                                 NEW_LDSTRCONST (cfg, ins, image, n);
10160                                                 *sp = ins;
10161                                                 MONO_ADD_INS (cfg->cbb, ins);
10162                                         } 
10163                                         else {
10164                                                 NEW_PCONST (cfg, ins, NULL);
10165                                                 ins->type = STACK_OBJ;
10166                                                 ins->inst_p0 = mono_ldstr_checked (cfg->domain, image, mono_metadata_token_index (n), &cfg->error);
10167                                                 CHECK_CFG_ERROR;
10168                                                 
10169                                                 if (!ins->inst_p0)
10170                                                         OUT_OF_MEMORY_FAILURE;
10171
10172                                                 *sp = ins;
10173                                                 MONO_ADD_INS (cfg->cbb, ins);
10174                                         }
10175                                 }
10176                         }
10177
10178                         sp++;
10179                         ip += 5;
10180                         break;
10181                 case CEE_NEWOBJ: {
10182                         MonoInst *iargs [2];
10183                         MonoMethodSignature *fsig;
10184                         MonoInst this_ins;
10185                         MonoInst *alloc;
10186                         MonoInst *vtable_arg = NULL;
10187
10188                         CHECK_OPSIZE (5);
10189                         token = read32 (ip + 1);
10190                         cmethod = mini_get_method (cfg, method, token, NULL, generic_context);
10191                         CHECK_CFG_ERROR;
10192
10193                         fsig = mono_method_get_signature_checked (cmethod, image, token, generic_context, &cfg->error);
10194                         CHECK_CFG_ERROR;
10195
10196                         mono_save_token_info (cfg, image, token, cmethod);
10197
10198                         if (!mono_class_init (cmethod->klass))
10199                                 TYPE_LOAD_ERROR (cmethod->klass);
10200
10201                         context_used = mini_method_check_context_used (cfg, cmethod);
10202
10203                         if (mono_security_core_clr_enabled ())
10204                                 ensure_method_is_allowed_to_call_method (cfg, method, cmethod);
10205
10206                         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)) {
10207                                 emit_class_init (cfg, cmethod->klass);
10208                                 CHECK_TYPELOAD (cmethod->klass);
10209                         }
10210
10211                         /*
10212                         if (cfg->gsharedvt) {
10213                                 if (mini_is_gsharedvt_variable_signature (sig))
10214                                         GSHAREDVT_FAILURE (*ip);
10215                         }
10216                         */
10217
10218                         n = fsig->param_count;
10219                         CHECK_STACK (n);
10220
10221                         /* 
10222                          * Generate smaller code for the common newobj <exception> instruction in
10223                          * argument checking code.
10224                          */
10225                         if (cfg->cbb->out_of_line && cmethod->klass->image == mono_defaults.corlib &&
10226                                 is_exception_class (cmethod->klass) && n <= 2 &&
10227                                 ((n < 1) || (!fsig->params [0]->byref && fsig->params [0]->type == MONO_TYPE_STRING)) && 
10228                                 ((n < 2) || (!fsig->params [1]->byref && fsig->params [1]->type == MONO_TYPE_STRING))) {
10229                                 MonoInst *iargs [3];
10230
10231                                 sp -= n;
10232
10233                                 EMIT_NEW_ICONST (cfg, iargs [0], cmethod->klass->type_token);
10234                                 switch (n) {
10235                                 case 0:
10236                                         *sp ++ = mono_emit_jit_icall (cfg, mono_create_corlib_exception_0, iargs);
10237                                         break;
10238                                 case 1:
10239                                         iargs [1] = sp [0];
10240                                         *sp ++ = mono_emit_jit_icall (cfg, mono_create_corlib_exception_1, iargs);
10241                                         break;
10242                                 case 2:
10243                                         iargs [1] = sp [0];
10244                                         iargs [2] = sp [1];
10245                                         *sp ++ = mono_emit_jit_icall (cfg, mono_create_corlib_exception_2, iargs);
10246                                         break;
10247                                 default:
10248                                         g_assert_not_reached ();
10249                                 }
10250
10251                                 ip += 5;
10252                                 inline_costs += 5;
10253                                 break;
10254                         }
10255
10256                         /* move the args to allow room for 'this' in the first position */
10257                         while (n--) {
10258                                 --sp;
10259                                 sp [1] = sp [0];
10260                         }
10261
10262                         /* check_call_signature () requires sp[0] to be set */
10263                         this_ins.type = STACK_OBJ;
10264                         sp [0] = &this_ins;
10265                         if (check_call_signature (cfg, fsig, sp))
10266                                 UNVERIFIED;
10267
10268                         iargs [0] = NULL;
10269
10270                         if (mini_class_is_system_array (cmethod->klass)) {
10271                                 *sp = emit_get_rgctx_method (cfg, context_used,
10272                                                                                          cmethod, MONO_RGCTX_INFO_METHOD);
10273
10274                                 /* Avoid varargs in the common case */
10275                                 if (fsig->param_count == 1)
10276                                         alloc = mono_emit_jit_icall (cfg, mono_array_new_1, sp);
10277                                 else if (fsig->param_count == 2)
10278                                         alloc = mono_emit_jit_icall (cfg, mono_array_new_2, sp);
10279                                 else if (fsig->param_count == 3)
10280                                         alloc = mono_emit_jit_icall (cfg, mono_array_new_3, sp);
10281                                 else if (fsig->param_count == 4)
10282                                         alloc = mono_emit_jit_icall (cfg, mono_array_new_4, sp);
10283                                 else
10284                                         alloc = handle_array_new (cfg, fsig->param_count, sp, ip);
10285                         } else if (cmethod->string_ctor) {
10286                                 g_assert (!context_used);
10287                                 g_assert (!vtable_arg);
10288                                 /* we simply pass a null pointer */
10289                                 EMIT_NEW_PCONST (cfg, *sp, NULL); 
10290                                 /* now call the string ctor */
10291                                 alloc = mono_emit_method_call_full (cfg, cmethod, fsig, FALSE, sp, NULL, NULL, NULL);
10292                         } else {
10293                                 if (cmethod->klass->valuetype) {
10294                                         iargs [0] = mono_compile_create_var (cfg, &cmethod->klass->byval_arg, OP_LOCAL);
10295                                         emit_init_rvar (cfg, iargs [0]->dreg, &cmethod->klass->byval_arg);
10296                                         EMIT_NEW_TEMPLOADA (cfg, *sp, iargs [0]->inst_c0);
10297
10298                                         alloc = NULL;
10299
10300                                         /* 
10301                                          * The code generated by mini_emit_virtual_call () expects
10302                                          * iargs [0] to be a boxed instance, but luckily the vcall
10303                                          * will be transformed into a normal call there.
10304                                          */
10305                                 } else if (context_used) {
10306                                         alloc = handle_alloc (cfg, cmethod->klass, FALSE, context_used);
10307                                         *sp = alloc;
10308                                 } else {
10309                                         MonoVTable *vtable = NULL;
10310
10311                                         if (!cfg->compile_aot)
10312                                                 vtable = mono_class_vtable (cfg->domain, cmethod->klass);
10313                                         CHECK_TYPELOAD (cmethod->klass);
10314
10315                                         /*
10316                                          * TypeInitializationExceptions thrown from the mono_runtime_class_init
10317                                          * call in mono_jit_runtime_invoke () can abort the finalizer thread.
10318                                          * As a workaround, we call class cctors before allocating objects.
10319                                          */
10320                                         if (mini_field_access_needs_cctor_run (cfg, method, cmethod->klass, vtable) && !(g_slist_find (class_inits, cmethod->klass))) {
10321                                                 emit_class_init (cfg, cmethod->klass);
10322                                                 if (cfg->verbose_level > 2)
10323                                                         printf ("class %s.%s needs init call for ctor\n", cmethod->klass->name_space, cmethod->klass->name);
10324                                                 class_inits = g_slist_prepend (class_inits, cmethod->klass);
10325                                         }
10326
10327                                         alloc = handle_alloc (cfg, cmethod->klass, FALSE, 0);
10328                                         *sp = alloc;
10329                                 }
10330                                 CHECK_CFG_EXCEPTION; /*for handle_alloc*/
10331
10332                                 if (alloc)
10333                                         MONO_EMIT_NEW_UNALU (cfg, OP_NOT_NULL, -1, alloc->dreg);
10334
10335                                 /* Now call the actual ctor */
10336                                 handle_ctor_call (cfg, cmethod, fsig, context_used, sp, ip, &inline_costs);
10337                                 CHECK_CFG_EXCEPTION;
10338                         }
10339
10340                         if (alloc == NULL) {
10341                                 /* Valuetype */
10342                                 EMIT_NEW_TEMPLOAD (cfg, ins, iargs [0]->inst_c0);
10343                                 type_to_eval_stack_type (cfg, &ins->klass->byval_arg, ins);
10344                                 *sp++= ins;
10345                         } else {
10346                                 *sp++ = alloc;
10347                         }
10348                         
10349                         ip += 5;
10350                         inline_costs += 5;
10351                         if (!(seq_point_locs && mono_bitset_test_fast (seq_point_locs, ip - header->code)))
10352                                 emit_seq_point (cfg, method, ip, FALSE, TRUE);
10353                         break;
10354                 }
10355                 case CEE_CASTCLASS:
10356                 case CEE_ISINST: {
10357                         CHECK_STACK (1);
10358                         --sp;
10359                         CHECK_OPSIZE (5);
10360                         token = read32 (ip + 1);
10361                         klass = mini_get_class (method, token, generic_context);
10362                         CHECK_TYPELOAD (klass);
10363                         if (sp [0]->type != STACK_OBJ)
10364                                 UNVERIFIED;
10365
10366                         MONO_INST_NEW (cfg, ins, *ip == CEE_ISINST ? OP_ISINST : OP_CASTCLASS);
10367                         ins->dreg = alloc_preg (cfg);
10368                         ins->sreg1 = (*sp)->dreg;
10369                         ins->klass = klass;
10370                         ins->type = STACK_OBJ;
10371                         MONO_ADD_INS (cfg->cbb, ins);
10372
10373                         CHECK_CFG_EXCEPTION;
10374                         *sp++ = ins;
10375                         ip += 5;
10376
10377                         cfg->flags |= MONO_CFG_HAS_TYPE_CHECK;
10378                         break;
10379                 }
10380                 case CEE_UNBOX_ANY: {
10381                         MonoInst *res, *addr;
10382
10383                         CHECK_STACK (1);
10384                         --sp;
10385                         CHECK_OPSIZE (5);
10386                         token = read32 (ip + 1);
10387                         klass = mini_get_class (method, token, generic_context);
10388                         CHECK_TYPELOAD (klass);
10389
10390                         mono_save_token_info (cfg, image, token, klass);
10391
10392                         context_used = mini_class_check_context_used (cfg, klass);
10393
10394                         if (mini_is_gsharedvt_klass (klass)) {
10395                                 res = handle_unbox_gsharedvt (cfg, klass, *sp);
10396                                 inline_costs += 2;
10397                         } else if (generic_class_is_reference_type (cfg, klass)) {
10398                                 if (MONO_INS_IS_PCONST_NULL (*sp)) {
10399                                         EMIT_NEW_PCONST (cfg, res, NULL);
10400                                         res->type = STACK_OBJ;
10401                                 } else {
10402                                         MONO_INST_NEW (cfg, res, OP_CASTCLASS);
10403                                         res->dreg = alloc_preg (cfg);
10404                                         res->sreg1 = (*sp)->dreg;
10405                                         res->klass = klass;
10406                                         res->type = STACK_OBJ;
10407                                         MONO_ADD_INS (cfg->cbb, res);
10408                                         cfg->flags |= MONO_CFG_HAS_TYPE_CHECK;
10409                                 }
10410                         } else if (mono_class_is_nullable (klass)) {
10411                                 res = handle_unbox_nullable (cfg, *sp, klass, context_used);
10412                         } else {
10413                                 addr = handle_unbox (cfg, klass, sp, context_used);
10414                                 /* LDOBJ */
10415                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr->dreg, 0);
10416                                 res = ins;
10417                                 inline_costs += 2;
10418                         }
10419
10420                         *sp ++ = res;
10421                         ip += 5;
10422                         break;
10423                 }
10424                 case CEE_BOX: {
10425                         MonoInst *val;
10426                         MonoClass *enum_class;
10427                         MonoMethod *has_flag;
10428
10429                         CHECK_STACK (1);
10430                         --sp;
10431                         val = *sp;
10432                         CHECK_OPSIZE (5);
10433                         token = read32 (ip + 1);
10434                         klass = mini_get_class (method, token, generic_context);
10435                         CHECK_TYPELOAD (klass);
10436
10437                         mono_save_token_info (cfg, image, token, klass);
10438
10439                         context_used = mini_class_check_context_used (cfg, klass);
10440
10441                         if (generic_class_is_reference_type (cfg, klass)) {
10442                                 *sp++ = val;
10443                                 ip += 5;
10444                                 break;
10445                         }
10446
10447                         if (klass == mono_defaults.void_class)
10448                                 UNVERIFIED;
10449                         if (target_type_is_incompatible (cfg, &klass->byval_arg, *sp))
10450                                 UNVERIFIED;
10451                         /* frequent check in generic code: box (struct), brtrue */
10452
10453                         /*
10454                          * Look for:
10455                          *
10456                          *   <push int/long ptr>
10457                          *   <push int/long>
10458                          *   box MyFlags
10459                          *   constrained. MyFlags
10460                          *   callvirt instace bool class [mscorlib] System.Enum::HasFlag (class [mscorlib] System.Enum)
10461                          *
10462                          * If we find this sequence and the operand types on box and constrained
10463                          * are equal, we can emit a specialized instruction sequence instead of
10464                          * the very slow HasFlag () call.
10465                          */
10466                         if ((cfg->opt & MONO_OPT_INTRINS) &&
10467                             /* Cheap checks first. */
10468                             ip + 5 + 6 + 5 < end &&
10469                             ip [5] == CEE_PREFIX1 &&
10470                             ip [6] == CEE_CONSTRAINED_ &&
10471                             ip [11] == CEE_CALLVIRT &&
10472                             ip_in_bb (cfg, cfg->cbb, ip + 5 + 6 + 5) &&
10473                             mono_class_is_enum (klass) &&
10474                             (enum_class = mini_get_class (method, read32 (ip + 7), generic_context)) &&
10475                             (has_flag = mini_get_method (cfg, method, read32 (ip + 12), NULL, generic_context)) &&
10476                             has_flag->klass == mono_defaults.enum_class &&
10477                             !strcmp (has_flag->name, "HasFlag") &&
10478                             has_flag->signature->hasthis &&
10479                             has_flag->signature->param_count == 1) {
10480                                 CHECK_TYPELOAD (enum_class);
10481
10482                                 if (enum_class == klass) {
10483                                         MonoInst *enum_this, *enum_flag;
10484
10485                                         ip += 5 + 6 + 5;
10486                                         --sp;
10487
10488                                         enum_this = sp [0];
10489                                         enum_flag = sp [1];
10490
10491                                         *sp++ = handle_enum_has_flag (cfg, klass, enum_this, enum_flag);
10492                                         break;
10493                                 }
10494                         }
10495
10496                         // FIXME: LLVM can't handle the inconsistent bb linking
10497                         if (!mono_class_is_nullable (klass) &&
10498                                 !mini_is_gsharedvt_klass (klass) &&
10499                                 ip + 5 < end && ip_in_bb (cfg, cfg->cbb, ip + 5) &&
10500                                 (ip [5] == CEE_BRTRUE || 
10501                                  ip [5] == CEE_BRTRUE_S ||
10502                                  ip [5] == CEE_BRFALSE ||
10503                                  ip [5] == CEE_BRFALSE_S)) {
10504                                 gboolean is_true = ip [5] == CEE_BRTRUE || ip [5] == CEE_BRTRUE_S;
10505                                 int dreg;
10506                                 MonoBasicBlock *true_bb, *false_bb;
10507
10508                                 ip += 5;
10509
10510                                 if (cfg->verbose_level > 3) {
10511                                         printf ("converting (in B%d: stack: %d) %s", cfg->cbb->block_num, (int)(sp - stack_start), mono_disasm_code_one (NULL, method, ip, NULL));
10512                                         printf ("<box+brtrue opt>\n");
10513                                 }
10514
10515                                 switch (*ip) {
10516                                 case CEE_BRTRUE_S:
10517                                 case CEE_BRFALSE_S:
10518                                         CHECK_OPSIZE (2);
10519                                         ip++;
10520                                         target = ip + 1 + (signed char)(*ip);
10521                                         ip++;
10522                                         break;
10523                                 case CEE_BRTRUE:
10524                                 case CEE_BRFALSE:
10525                                         CHECK_OPSIZE (5);
10526                                         ip++;
10527                                         target = ip + 4 + (gint)(read32 (ip));
10528                                         ip += 4;
10529                                         break;
10530                                 default:
10531                                         g_assert_not_reached ();
10532                                 }
10533
10534                                 /* 
10535                                  * We need to link both bblocks, since it is needed for handling stack
10536                                  * arguments correctly (See test_0_box_brtrue_opt_regress_81102).
10537                                  * Branching to only one of them would lead to inconsistencies, so
10538                                  * generate an ICONST+BRTRUE, the branch opts will get rid of them.
10539                                  */
10540                                 GET_BBLOCK (cfg, true_bb, target);
10541                                 GET_BBLOCK (cfg, false_bb, ip);
10542
10543                                 mono_link_bblock (cfg, cfg->cbb, true_bb);
10544                                 mono_link_bblock (cfg, cfg->cbb, false_bb);
10545
10546                                 if (sp != stack_start) {
10547                                         handle_stack_args (cfg, stack_start, sp - stack_start);
10548                                         sp = stack_start;
10549                                         CHECK_UNVERIFIABLE (cfg);
10550                                 }
10551
10552                                 if (COMPILE_LLVM (cfg)) {
10553                                         dreg = alloc_ireg (cfg);
10554                                         MONO_EMIT_NEW_ICONST (cfg, dreg, 0);
10555                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, dreg, is_true ? 0 : 1);
10556
10557                                         MONO_EMIT_NEW_BRANCH_BLOCK2 (cfg, OP_IBEQ, true_bb, false_bb);
10558                                 } else {
10559                                         /* The JIT can't eliminate the iconst+compare */
10560                                         MONO_INST_NEW (cfg, ins, OP_BR);
10561                                         ins->inst_target_bb = is_true ? true_bb : false_bb;
10562                                         MONO_ADD_INS (cfg->cbb, ins);
10563                                 }
10564
10565                                 start_new_bblock = 1;
10566                                 break;
10567                         }
10568
10569                         *sp++ = handle_box (cfg, val, klass, context_used);
10570
10571                         CHECK_CFG_EXCEPTION;
10572                         ip += 5;
10573                         inline_costs += 1;
10574                         break;
10575                 }
10576                 case CEE_UNBOX: {
10577                         CHECK_STACK (1);
10578                         --sp;
10579                         CHECK_OPSIZE (5);
10580                         token = read32 (ip + 1);
10581                         klass = mini_get_class (method, token, generic_context);
10582                         CHECK_TYPELOAD (klass);
10583
10584                         mono_save_token_info (cfg, image, token, klass);
10585
10586                         context_used = mini_class_check_context_used (cfg, klass);
10587
10588                         if (mono_class_is_nullable (klass)) {
10589                                 MonoInst *val;
10590
10591                                 val = handle_unbox_nullable (cfg, *sp, klass, context_used);
10592                                 EMIT_NEW_VARLOADA (cfg, ins, get_vreg_to_inst (cfg, val->dreg), &val->klass->byval_arg);
10593
10594                                 *sp++= ins;
10595                         } else {
10596                                 ins = handle_unbox (cfg, klass, sp, context_used);
10597                                 *sp++ = ins;
10598                         }
10599                         ip += 5;
10600                         inline_costs += 2;
10601                         break;
10602                 }
10603                 case CEE_LDFLD:
10604                 case CEE_LDFLDA:
10605                 case CEE_STFLD:
10606                 case CEE_LDSFLD:
10607                 case CEE_LDSFLDA:
10608                 case CEE_STSFLD: {
10609                         MonoClassField *field;
10610 #ifndef DISABLE_REMOTING
10611                         int costs;
10612 #endif
10613                         guint foffset;
10614                         gboolean is_instance;
10615                         int op;
10616                         gpointer addr = NULL;
10617                         gboolean is_special_static;
10618                         MonoType *ftype;
10619                         MonoInst *store_val = NULL;
10620                         MonoInst *thread_ins;
10621
10622                         op = *ip;
10623                         is_instance = (op == CEE_LDFLD || op == CEE_LDFLDA || op == CEE_STFLD);
10624                         if (is_instance) {
10625                                 if (op == CEE_STFLD) {
10626                                         CHECK_STACK (2);
10627                                         sp -= 2;
10628                                         store_val = sp [1];
10629                                 } else {
10630                                         CHECK_STACK (1);
10631                                         --sp;
10632                                 }
10633                                 if (sp [0]->type == STACK_I4 || sp [0]->type == STACK_I8 || sp [0]->type == STACK_R8)
10634                                         UNVERIFIED;
10635                                 if (*ip != CEE_LDFLD && sp [0]->type == STACK_VTYPE)
10636                                         UNVERIFIED;
10637                         } else {
10638                                 if (op == CEE_STSFLD) {
10639                                         CHECK_STACK (1);
10640                                         sp--;
10641                                         store_val = sp [0];
10642                                 }
10643                         }
10644
10645                         CHECK_OPSIZE (5);
10646                         token = read32 (ip + 1);
10647                         if (method->wrapper_type != MONO_WRAPPER_NONE) {
10648                                 field = (MonoClassField *)mono_method_get_wrapper_data (method, token);
10649                                 klass = field->parent;
10650                         }
10651                         else {
10652                                 field = mono_field_from_token_checked (image, token, &klass, generic_context, &cfg->error);
10653                                 CHECK_CFG_ERROR;
10654                         }
10655                         if (!dont_verify && !cfg->skip_visibility && !mono_method_can_access_field (method, field))
10656                                 FIELD_ACCESS_FAILURE (method, field);
10657                         mono_class_init (klass);
10658
10659                         /* if the class is Critical then transparent code cannot access it's fields */
10660                         if (!is_instance && mono_security_core_clr_enabled ())
10661                                 ensure_method_is_allowed_to_access_field (cfg, method, field);
10662
10663                         /* XXX this is technically required but, so far (SL2), no [SecurityCritical] types (not many exists) have
10664                            any visible *instance* field  (in fact there's a single case for a static field in Marshal) XXX
10665                         if (mono_security_core_clr_enabled ())
10666                                 ensure_method_is_allowed_to_access_field (cfg, method, field);
10667                         */
10668
10669                         ftype = mono_field_get_type (field);
10670
10671                         /*
10672                          * LDFLD etc. is usable on static fields as well, so convert those cases to
10673                          * the static case.
10674                          */
10675                         if (is_instance && ftype->attrs & FIELD_ATTRIBUTE_STATIC) {
10676                                 switch (op) {
10677                                 case CEE_LDFLD:
10678                                         op = CEE_LDSFLD;
10679                                         break;
10680                                 case CEE_STFLD:
10681                                         op = CEE_STSFLD;
10682                                         break;
10683                                 case CEE_LDFLDA:
10684                                         op = CEE_LDSFLDA;
10685                                         break;
10686                                 default:
10687                                         g_assert_not_reached ();
10688                                 }
10689                                 is_instance = FALSE;
10690                         }
10691
10692                         context_used = mini_class_check_context_used (cfg, klass);
10693
10694                         /* INSTANCE CASE */
10695
10696                         foffset = klass->valuetype? field->offset - sizeof (MonoObject): field->offset;
10697                         if (op == CEE_STFLD) {
10698                                 if (target_type_is_incompatible (cfg, field->type, sp [1]))
10699                                         UNVERIFIED;
10700 #ifndef DISABLE_REMOTING
10701                                 if ((mono_class_is_marshalbyref (klass) && !MONO_CHECK_THIS (sp [0])) || mono_class_is_contextbound (klass) || klass == mono_defaults.marshalbyrefobject_class) {
10702                                         MonoMethod *stfld_wrapper = mono_marshal_get_stfld_wrapper (field->type); 
10703                                         MonoInst *iargs [5];
10704
10705                                         GSHAREDVT_FAILURE (op);
10706
10707                                         iargs [0] = sp [0];
10708                                         EMIT_NEW_CLASSCONST (cfg, iargs [1], klass);
10709                                         EMIT_NEW_FIELDCONST (cfg, iargs [2], field);
10710                                         EMIT_NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) : 
10711                                                     field->offset);
10712                                         iargs [4] = sp [1];
10713
10714                                         if (cfg->opt & MONO_OPT_INLINE || cfg->compile_aot) {
10715                                                 costs = inline_method (cfg, stfld_wrapper, mono_method_signature (stfld_wrapper), 
10716                                                                                            iargs, ip, cfg->real_offset, TRUE);
10717                                                 CHECK_CFG_EXCEPTION;
10718                                                 g_assert (costs > 0);
10719                                                       
10720                                                 cfg->real_offset += 5;
10721
10722                                                 inline_costs += costs;
10723                                         } else {
10724                                                 mono_emit_method_call (cfg, stfld_wrapper, iargs, NULL);
10725                                         }
10726                                 } else
10727 #endif
10728                                 {
10729                                         MonoInst *store, *wbarrier_ptr_ins = NULL;
10730
10731                                         MONO_EMIT_NULL_CHECK (cfg, sp [0]->dreg);
10732
10733                                         if (ins_flag & MONO_INST_VOLATILE) {
10734                                                 /* Volatile stores have release semantics, see 12.6.7 in Ecma 335 */
10735                                                 emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_REL);
10736                                         }
10737
10738                                         if (mini_is_gsharedvt_klass (klass)) {
10739                                                 MonoInst *offset_ins;
10740
10741                                                 context_used = mini_class_check_context_used (cfg, klass);
10742
10743                                                 offset_ins = emit_get_gsharedvt_info (cfg, field, MONO_RGCTX_INFO_FIELD_OFFSET);
10744                                                 /* The value is offset by 1 */
10745                                                 EMIT_NEW_BIALU_IMM (cfg, ins, OP_PSUB_IMM, offset_ins->dreg, offset_ins->dreg, 1);
10746                                                 dreg = alloc_ireg_mp (cfg);
10747                                                 EMIT_NEW_BIALU (cfg, ins, OP_PADD, dreg, sp [0]->dreg, offset_ins->dreg);
10748                                                 wbarrier_ptr_ins = ins;
10749                                                 /* The decomposition will call mini_emit_stobj () which will emit a wbarrier if needed */
10750                                                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, store, field->type, dreg, 0, sp [1]->dreg);
10751                                         } else {
10752                                                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, store, field->type, sp [0]->dreg, foffset, sp [1]->dreg);
10753                                         }
10754                                         if (sp [0]->opcode != OP_LDADDR)
10755                                                 store->flags |= MONO_INST_FAULT;
10756
10757                                         if (cfg->gen_write_barriers && mini_type_to_stind (cfg, field->type) == CEE_STIND_REF && !MONO_INS_IS_PCONST_NULL (sp [1])) {
10758                                                 if (mini_is_gsharedvt_klass (klass)) {
10759                                                         g_assert (wbarrier_ptr_ins);
10760                                                         emit_write_barrier (cfg, wbarrier_ptr_ins, sp [1]);
10761                                                 } else {
10762                                                         /* insert call to write barrier */
10763                                                         MonoInst *ptr;
10764                                                         int dreg;
10765
10766                                                         dreg = alloc_ireg_mp (cfg);
10767                                                         EMIT_NEW_BIALU_IMM (cfg, ptr, OP_PADD_IMM, dreg, sp [0]->dreg, foffset);
10768                                                         emit_write_barrier (cfg, ptr, sp [1]);
10769                                                 }
10770                                         }
10771
10772                                         store->flags |= ins_flag;
10773                                 }
10774                                 ins_flag = 0;
10775                                 ip += 5;
10776                                 break;
10777                         }
10778
10779 #ifndef DISABLE_REMOTING
10780                         if (is_instance && ((mono_class_is_marshalbyref (klass) && !MONO_CHECK_THIS (sp [0])) || mono_class_is_contextbound (klass) || klass == mono_defaults.marshalbyrefobject_class)) {
10781                                 MonoMethod *wrapper = (op == CEE_LDFLDA) ? mono_marshal_get_ldflda_wrapper (field->type) : mono_marshal_get_ldfld_wrapper (field->type); 
10782                                 MonoInst *iargs [4];
10783
10784                                 GSHAREDVT_FAILURE (op);
10785
10786                                 iargs [0] = sp [0];
10787                                 EMIT_NEW_CLASSCONST (cfg, iargs [1], klass);
10788                                 EMIT_NEW_FIELDCONST (cfg, iargs [2], field);
10789                                 EMIT_NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) : field->offset);
10790                                 if (cfg->opt & MONO_OPT_INLINE || cfg->compile_aot) {
10791                                         costs = inline_method (cfg, wrapper, mono_method_signature (wrapper), 
10792                                                                                    iargs, ip, cfg->real_offset, TRUE);
10793                                         CHECK_CFG_EXCEPTION;
10794                                         g_assert (costs > 0);
10795                                                       
10796                                         cfg->real_offset += 5;
10797
10798                                         *sp++ = iargs [0];
10799
10800                                         inline_costs += costs;
10801                                 } else {
10802                                         ins = mono_emit_method_call (cfg, wrapper, iargs, NULL);
10803                                         *sp++ = ins;
10804                                 }
10805                         } else 
10806 #endif
10807                         if (is_instance) {
10808                                 if (sp [0]->type == STACK_VTYPE) {
10809                                         MonoInst *var;
10810
10811                                         /* Have to compute the address of the variable */
10812
10813                                         var = get_vreg_to_inst (cfg, sp [0]->dreg);
10814                                         if (!var)
10815                                                 var = mono_compile_create_var_for_vreg (cfg, &klass->byval_arg, OP_LOCAL, sp [0]->dreg);
10816                                         else
10817                                                 g_assert (var->klass == klass);
10818                                         
10819                                         EMIT_NEW_VARLOADA (cfg, ins, var, &var->klass->byval_arg);
10820                                         sp [0] = ins;
10821                                 }
10822
10823                                 if (op == CEE_LDFLDA) {
10824                                         if (sp [0]->type == STACK_OBJ) {
10825                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, sp [0]->dreg, 0);
10826                                                 MONO_EMIT_NEW_COND_EXC (cfg, EQ, "NullReferenceException");
10827                                         }
10828
10829                                         dreg = alloc_ireg_mp (cfg);
10830
10831                                         if (mini_is_gsharedvt_klass (klass)) {
10832                                                 MonoInst *offset_ins;
10833
10834                                                 offset_ins = emit_get_gsharedvt_info (cfg, field, MONO_RGCTX_INFO_FIELD_OFFSET);
10835                                                 /* The value is offset by 1 */
10836                                                 EMIT_NEW_BIALU_IMM (cfg, ins, OP_PSUB_IMM, offset_ins->dreg, offset_ins->dreg, 1);
10837                                                 EMIT_NEW_BIALU (cfg, ins, OP_PADD, dreg, sp [0]->dreg, offset_ins->dreg);
10838                                         } else {
10839                                                 EMIT_NEW_BIALU_IMM (cfg, ins, OP_PADD_IMM, dreg, sp [0]->dreg, foffset);
10840                                         }
10841                                         ins->klass = mono_class_from_mono_type (field->type);
10842                                         ins->type = STACK_MP;
10843                                         *sp++ = ins;
10844                                 } else {
10845                                         MonoInst *load;
10846
10847                                         MONO_EMIT_NULL_CHECK (cfg, sp [0]->dreg);
10848
10849                                         if (sp [0]->opcode == OP_LDADDR && klass->simd_type && cfg->opt & MONO_OPT_SIMD) {
10850                                                 ins = mono_emit_simd_field_load (cfg, field, sp [0]);
10851                                                 if (ins) {
10852                                                         *sp++ = ins;
10853                                                         ins_flag = 0;
10854                                                         ip += 5;
10855                                                         break;
10856                                                 }
10857                                         }
10858
10859                                         if (mini_is_gsharedvt_klass (klass)) {
10860                                                 MonoInst *offset_ins;
10861
10862                                                 offset_ins = emit_get_gsharedvt_info (cfg, field, MONO_RGCTX_INFO_FIELD_OFFSET);
10863                                                 /* The value is offset by 1 */
10864                                                 EMIT_NEW_BIALU_IMM (cfg, ins, OP_PSUB_IMM, offset_ins->dreg, offset_ins->dreg, 1);
10865                                                 dreg = alloc_ireg_mp (cfg);
10866                                                 EMIT_NEW_BIALU (cfg, ins, OP_PADD, dreg, sp [0]->dreg, offset_ins->dreg);
10867                                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, load, field->type, dreg, 0);
10868                                         } else {
10869                                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, load, field->type, sp [0]->dreg, foffset);
10870                                         }
10871                                         load->flags |= ins_flag;
10872                                         if (sp [0]->opcode != OP_LDADDR)
10873                                                 load->flags |= MONO_INST_FAULT;
10874                                         *sp++ = load;
10875                                 }
10876                         }
10877
10878                         if (is_instance) {
10879                                 ins_flag = 0;
10880                                 ip += 5;
10881                                 break;
10882                         }
10883
10884                         /* STATIC CASE */
10885                         context_used = mini_class_check_context_used (cfg, klass);
10886
10887                         if (ftype->attrs & FIELD_ATTRIBUTE_LITERAL) {
10888                                 mono_error_set_field_load (&cfg->error, field->parent, field->name, "Using static instructions with literal field");
10889                                 CHECK_CFG_ERROR;
10890                         }
10891
10892                         /* The special_static_fields field is init'd in mono_class_vtable, so it needs
10893                          * to be called here.
10894                          */
10895                         if (!context_used && !(cfg->opt & MONO_OPT_SHARED)) {
10896                                 mono_class_vtable (cfg->domain, klass);
10897                                 CHECK_TYPELOAD (klass);
10898                         }
10899                         mono_domain_lock (cfg->domain);
10900                         if (cfg->domain->special_static_fields)
10901                                 addr = g_hash_table_lookup (cfg->domain->special_static_fields, field);
10902                         mono_domain_unlock (cfg->domain);
10903
10904                         is_special_static = mono_class_field_is_special_static (field);
10905
10906                         if (is_special_static && ((gsize)addr & 0x80000000) == 0)
10907                                 thread_ins = mono_create_tls_get (cfg, TLS_KEY_THREAD);
10908                         else
10909                                 thread_ins = NULL;
10910
10911                         /* Generate IR to compute the field address */
10912                         if (is_special_static && ((gsize)addr & 0x80000000) == 0 && thread_ins && !(cfg->opt & MONO_OPT_SHARED) && !context_used) {
10913                                 /*
10914                                  * Fast access to TLS data
10915                                  * Inline version of get_thread_static_data () in
10916                                  * threads.c.
10917                                  */
10918                                 guint32 offset;
10919                                 int idx, static_data_reg, array_reg, dreg;
10920
10921                                 if (context_used && cfg->gsharedvt && mini_is_gsharedvt_klass (klass))
10922                                         GSHAREDVT_FAILURE (op);
10923
10924                                 static_data_reg = alloc_ireg (cfg);
10925                                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, static_data_reg, thread_ins->dreg, MONO_STRUCT_OFFSET (MonoInternalThread, static_data));
10926
10927                                 if (cfg->compile_aot) {
10928                                         int offset_reg, offset2_reg, idx_reg;
10929
10930                                         /* For TLS variables, this will return the TLS offset */
10931                                         EMIT_NEW_SFLDACONST (cfg, ins, field);
10932                                         offset_reg = ins->dreg;
10933                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_IAND_IMM, offset_reg, offset_reg, 0x7fffffff);
10934                                         idx_reg = alloc_ireg (cfg);
10935                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_IAND_IMM, idx_reg, offset_reg, 0x3f);
10936                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ISHL_IMM, idx_reg, idx_reg, sizeof (gpointer) == 8 ? 3 : 2);
10937                                         MONO_EMIT_NEW_BIALU (cfg, OP_PADD, static_data_reg, static_data_reg, idx_reg);
10938                                         array_reg = alloc_ireg (cfg);
10939                                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, array_reg, static_data_reg, 0);
10940                                         offset2_reg = alloc_ireg (cfg);
10941                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ISHR_UN_IMM, offset2_reg, offset_reg, 6);
10942                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_IAND_IMM, offset2_reg, offset2_reg, 0x1ffffff);
10943                                         dreg = alloc_ireg (cfg);
10944                                         EMIT_NEW_BIALU (cfg, ins, OP_PADD, dreg, array_reg, offset2_reg);
10945                                 } else {
10946                                         offset = (gsize)addr & 0x7fffffff;
10947                                         idx = offset & 0x3f;
10948
10949                                         array_reg = alloc_ireg (cfg);
10950                                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, array_reg, static_data_reg, idx * sizeof (gpointer));
10951                                         dreg = alloc_ireg (cfg);
10952                                         EMIT_NEW_BIALU_IMM (cfg, ins, OP_ADD_IMM, dreg, array_reg, ((offset >> 6) & 0x1ffffff));
10953                                 }
10954                         } else if ((cfg->opt & MONO_OPT_SHARED) ||
10955                                         (cfg->compile_aot && is_special_static) ||
10956                                         (context_used && is_special_static)) {
10957                                 MonoInst *iargs [2];
10958
10959                                 g_assert (field->parent);
10960                                 EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
10961                                 if (context_used) {
10962                                         iargs [1] = emit_get_rgctx_field (cfg, context_used,
10963                                                 field, MONO_RGCTX_INFO_CLASS_FIELD);
10964                                 } else {
10965                                         EMIT_NEW_FIELDCONST (cfg, iargs [1], field);
10966                                 }
10967                                 ins = mono_emit_jit_icall (cfg, mono_class_static_field_address, iargs);
10968                         } else if (context_used) {
10969                                 MonoInst *static_data;
10970
10971                                 /*
10972                                 g_print ("sharing static field access in %s.%s.%s - depth %d offset %d\n",
10973                                         method->klass->name_space, method->klass->name, method->name,
10974                                         depth, field->offset);
10975                                 */
10976
10977                                 if (mono_class_needs_cctor_run (klass, method))
10978                                         emit_class_init (cfg, klass);
10979
10980                                 /*
10981                                  * The pointer we're computing here is
10982                                  *
10983                                  *   super_info.static_data + field->offset
10984                                  */
10985                                 static_data = mini_emit_get_rgctx_klass (cfg, context_used,
10986                                         klass, MONO_RGCTX_INFO_STATIC_DATA);
10987
10988                                 if (mini_is_gsharedvt_klass (klass)) {
10989                                         MonoInst *offset_ins;
10990
10991                                         offset_ins = emit_get_rgctx_field (cfg, context_used, field, MONO_RGCTX_INFO_FIELD_OFFSET);
10992                                         /* The value is offset by 1 */
10993                                         EMIT_NEW_BIALU_IMM (cfg, ins, OP_PSUB_IMM, offset_ins->dreg, offset_ins->dreg, 1);
10994                                         dreg = alloc_ireg_mp (cfg);
10995                                         EMIT_NEW_BIALU (cfg, ins, OP_PADD, dreg, static_data->dreg, offset_ins->dreg);
10996                                 } else if (field->offset == 0) {
10997                                         ins = static_data;
10998                                 } else {
10999                                         int addr_reg = mono_alloc_preg (cfg);
11000                                         EMIT_NEW_BIALU_IMM (cfg, ins, OP_PADD_IMM, addr_reg, static_data->dreg, field->offset);
11001                                 }
11002                                 } else if ((cfg->opt & MONO_OPT_SHARED) || (cfg->compile_aot && addr)) {
11003                                 MonoInst *iargs [2];
11004
11005                                 g_assert (field->parent);
11006                                 EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
11007                                 EMIT_NEW_FIELDCONST (cfg, iargs [1], field);
11008                                 ins = mono_emit_jit_icall (cfg, mono_class_static_field_address, iargs);
11009                         } else {
11010                                 MonoVTable *vtable = NULL;
11011
11012                                 if (!cfg->compile_aot)
11013                                         vtable = mono_class_vtable (cfg->domain, klass);
11014                                 CHECK_TYPELOAD (klass);
11015
11016                                 if (!addr) {
11017                                         if (mini_field_access_needs_cctor_run (cfg, method, klass, vtable)) {
11018                                                 if (!(g_slist_find (class_inits, klass))) {
11019                                                         emit_class_init (cfg, klass);
11020                                                         if (cfg->verbose_level > 2)
11021                                                                 printf ("class %s.%s needs init call for %s\n", klass->name_space, klass->name, mono_field_get_name (field));
11022                                                         class_inits = g_slist_prepend (class_inits, klass);
11023                                                 }
11024                                         } else {
11025                                                 if (cfg->run_cctors) {
11026                                                         /* This makes so that inline cannot trigger */
11027                                                         /* .cctors: too many apps depend on them */
11028                                                         /* running with a specific order... */
11029                                                         g_assert (vtable);
11030                                                         if (! vtable->initialized)
11031                                                                 INLINE_FAILURE ("class init");
11032                                                         if (!mono_runtime_class_init_full (vtable, &cfg->error)) {
11033                                                                 mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
11034                                                                 goto exception_exit;
11035                                                         }
11036                                                 }
11037                                         }
11038                                         if (cfg->compile_aot)
11039                                                 EMIT_NEW_SFLDACONST (cfg, ins, field);
11040                                         else {
11041                                                 g_assert (vtable);
11042                                                 addr = (char*)mono_vtable_get_static_field_data (vtable) + field->offset;
11043                                                 g_assert (addr);
11044                                                 EMIT_NEW_PCONST (cfg, ins, addr);
11045                                         }
11046                                 } else {
11047                                         MonoInst *iargs [1];
11048                                         EMIT_NEW_ICONST (cfg, iargs [0], GPOINTER_TO_UINT (addr));
11049                                         ins = mono_emit_jit_icall (cfg, mono_get_special_static_data, iargs);
11050                                 }
11051                         }
11052
11053                         /* Generate IR to do the actual load/store operation */
11054
11055                         if ((op == CEE_STFLD || op == CEE_STSFLD) && (ins_flag & MONO_INST_VOLATILE)) {
11056                                 /* Volatile stores have release semantics, see 12.6.7 in Ecma 335 */
11057                                 emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_REL);
11058                         }
11059
11060                         if (op == CEE_LDSFLDA) {
11061                                 ins->klass = mono_class_from_mono_type (ftype);
11062                                 ins->type = STACK_PTR;
11063                                 *sp++ = ins;
11064                         } else if (op == CEE_STSFLD) {
11065                                 MonoInst *store;
11066
11067                                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, store, ftype, ins->dreg, 0, store_val->dreg);
11068                                 store->flags |= ins_flag;
11069                         } else {
11070                                 gboolean is_const = FALSE;
11071                                 MonoVTable *vtable = NULL;
11072                                 gpointer addr = NULL;
11073
11074                                 if (!context_used) {
11075                                         vtable = mono_class_vtable (cfg->domain, klass);
11076                                         CHECK_TYPELOAD (klass);
11077                                 }
11078                                 if ((ftype->attrs & FIELD_ATTRIBUTE_INIT_ONLY) && (((addr = mono_aot_readonly_field_override (field)) != NULL) ||
11079                                                 (!context_used && !((cfg->opt & MONO_OPT_SHARED) || cfg->compile_aot) && vtable->initialized))) {
11080                                         int ro_type = ftype->type;
11081                                         if (!addr)
11082                                                 addr = (char*)mono_vtable_get_static_field_data (vtable) + field->offset;
11083                                         if (ro_type == MONO_TYPE_VALUETYPE && ftype->data.klass->enumtype) {
11084                                                 ro_type = mono_class_enum_basetype (ftype->data.klass)->type;
11085                                         }
11086
11087                                         GSHAREDVT_FAILURE (op);
11088
11089                                         /* printf ("RO-FIELD %s.%s:%s\n", klass->name_space, klass->name, mono_field_get_name (field));*/
11090                                         is_const = TRUE;
11091                                         switch (ro_type) {
11092                                         case MONO_TYPE_BOOLEAN:
11093                                         case MONO_TYPE_U1:
11094                                                 EMIT_NEW_ICONST (cfg, *sp, *((guint8 *)addr));
11095                                                 sp++;
11096                                                 break;
11097                                         case MONO_TYPE_I1:
11098                                                 EMIT_NEW_ICONST (cfg, *sp, *((gint8 *)addr));
11099                                                 sp++;
11100                                                 break;                                          
11101                                         case MONO_TYPE_CHAR:
11102                                         case MONO_TYPE_U2:
11103                                                 EMIT_NEW_ICONST (cfg, *sp, *((guint16 *)addr));
11104                                                 sp++;
11105                                                 break;
11106                                         case MONO_TYPE_I2:
11107                                                 EMIT_NEW_ICONST (cfg, *sp, *((gint16 *)addr));
11108                                                 sp++;
11109                                                 break;
11110                                                 break;
11111                                         case MONO_TYPE_I4:
11112                                                 EMIT_NEW_ICONST (cfg, *sp, *((gint32 *)addr));
11113                                                 sp++;
11114                                                 break;                                          
11115                                         case MONO_TYPE_U4:
11116                                                 EMIT_NEW_ICONST (cfg, *sp, *((guint32 *)addr));
11117                                                 sp++;
11118                                                 break;
11119                                         case MONO_TYPE_I:
11120                                         case MONO_TYPE_U:
11121                                         case MONO_TYPE_PTR:
11122                                         case MONO_TYPE_FNPTR:
11123                                                 EMIT_NEW_PCONST (cfg, *sp, *((gpointer *)addr));
11124                                                 type_to_eval_stack_type ((cfg), field->type, *sp);
11125                                                 sp++;
11126                                                 break;
11127                                         case MONO_TYPE_STRING:
11128                                         case MONO_TYPE_OBJECT:
11129                                         case MONO_TYPE_CLASS:
11130                                         case MONO_TYPE_SZARRAY:
11131                                         case MONO_TYPE_ARRAY:
11132                                                 if (!mono_gc_is_moving ()) {
11133                                                         EMIT_NEW_PCONST (cfg, *sp, *((gpointer *)addr));
11134                                                         type_to_eval_stack_type ((cfg), field->type, *sp);
11135                                                         sp++;
11136                                                 } else {
11137                                                         is_const = FALSE;
11138                                                 }
11139                                                 break;
11140                                         case MONO_TYPE_I8:
11141                                         case MONO_TYPE_U8:
11142                                                 EMIT_NEW_I8CONST (cfg, *sp, *((gint64 *)addr));
11143                                                 sp++;
11144                                                 break;
11145                                         case MONO_TYPE_R4:
11146                                         case MONO_TYPE_R8:
11147                                         case MONO_TYPE_VALUETYPE:
11148                                         default:
11149                                                 is_const = FALSE;
11150                                                 break;
11151                                         }
11152                                 }
11153
11154                                 if (!is_const) {
11155                                         MonoInst *load;
11156
11157                                         CHECK_STACK_OVF (1);
11158
11159                                         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, load, field->type, ins->dreg, 0);
11160                                         load->flags |= ins_flag;
11161                                         ins_flag = 0;
11162                                         *sp++ = load;
11163                                 }
11164                         }
11165
11166                         if ((op == CEE_LDFLD || op == CEE_LDSFLD) && (ins_flag & MONO_INST_VOLATILE)) {
11167                                 /* Volatile loads have acquire semantics, see 12.6.7 in Ecma 335 */
11168                                 emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_ACQ);
11169                         }
11170
11171                         ins_flag = 0;
11172                         ip += 5;
11173                         break;
11174                 }
11175                 case CEE_STOBJ:
11176                         CHECK_STACK (2);
11177                         sp -= 2;
11178                         CHECK_OPSIZE (5);
11179                         token = read32 (ip + 1);
11180                         klass = mini_get_class (method, token, generic_context);
11181                         CHECK_TYPELOAD (klass);
11182                         if (ins_flag & MONO_INST_VOLATILE) {
11183                                 /* Volatile stores have release semantics, see 12.6.7 in Ecma 335 */
11184                                 emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_REL);
11185                         }
11186                         /* FIXME: should check item at sp [1] is compatible with the type of the store. */
11187                         EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, sp [0]->dreg, 0, sp [1]->dreg);
11188                         ins->flags |= ins_flag;
11189                         if (cfg->gen_write_barriers && cfg->method->wrapper_type != MONO_WRAPPER_WRITE_BARRIER &&
11190                                 generic_class_is_reference_type (cfg, klass) && !MONO_INS_IS_PCONST_NULL (sp [1])) {
11191                                 /* insert call to write barrier */
11192                                 emit_write_barrier (cfg, sp [0], sp [1]);
11193                         }
11194                         ins_flag = 0;
11195                         ip += 5;
11196                         inline_costs += 1;
11197                         break;
11198
11199                         /*
11200                          * Array opcodes
11201                          */
11202                 case CEE_NEWARR: {
11203                         MonoInst *len_ins;
11204                         const char *data_ptr;
11205                         int data_size = 0;
11206                         guint32 field_token;
11207
11208                         CHECK_STACK (1);
11209                         --sp;
11210
11211                         CHECK_OPSIZE (5);
11212                         token = read32 (ip + 1);
11213
11214                         klass = mini_get_class (method, token, generic_context);
11215                         CHECK_TYPELOAD (klass);
11216                         if (klass->byval_arg.type == MONO_TYPE_VOID)
11217                                 UNVERIFIED;
11218
11219                         context_used = mini_class_check_context_used (cfg, klass);
11220
11221                         if (sp [0]->type == STACK_I8 || (SIZEOF_VOID_P == 8 && sp [0]->type == STACK_PTR)) {
11222                                 MONO_INST_NEW (cfg, ins, OP_LCONV_TO_OVF_U4);
11223                                 ins->sreg1 = sp [0]->dreg;
11224                                 ins->type = STACK_I4;
11225                                 ins->dreg = alloc_ireg (cfg);
11226                                 MONO_ADD_INS (cfg->cbb, ins);
11227                                 *sp = mono_decompose_opcode (cfg, ins);
11228                         }
11229
11230                         if (context_used) {
11231                                 MonoInst *args [3];
11232                                 MonoClass *array_class = mono_array_class_get (klass, 1);
11233                                 MonoMethod *managed_alloc = mono_gc_get_managed_array_allocator (array_class);
11234
11235                                 /* FIXME: Use OP_NEWARR and decompose later to help abcrem */
11236
11237                                 /* vtable */
11238                                 args [0] = mini_emit_get_rgctx_klass (cfg, context_used,
11239                                         array_class, MONO_RGCTX_INFO_VTABLE);
11240                                 /* array len */
11241                                 args [1] = sp [0];
11242
11243                                 if (managed_alloc)
11244                                         ins = mono_emit_method_call (cfg, managed_alloc, args, NULL);
11245                                 else
11246                                         ins = mono_emit_jit_icall (cfg, ves_icall_array_new_specific, args);
11247                         } else {
11248                                 if (cfg->opt & MONO_OPT_SHARED) {
11249                                         /* Decompose now to avoid problems with references to the domainvar */
11250                                         MonoInst *iargs [3];
11251
11252                                         EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
11253                                         EMIT_NEW_CLASSCONST (cfg, iargs [1], klass);
11254                                         iargs [2] = sp [0];
11255
11256                                         ins = mono_emit_jit_icall (cfg, ves_icall_array_new, iargs);
11257                                 } else {
11258                                         /* Decompose later since it is needed by abcrem */
11259                                         MonoClass *array_type = mono_array_class_get (klass, 1);
11260                                         mono_class_vtable (cfg->domain, array_type);
11261                                         CHECK_TYPELOAD (array_type);
11262
11263                                         MONO_INST_NEW (cfg, ins, OP_NEWARR);
11264                                         ins->dreg = alloc_ireg_ref (cfg);
11265                                         ins->sreg1 = sp [0]->dreg;
11266                                         ins->inst_newa_class = klass;
11267                                         ins->type = STACK_OBJ;
11268                                         ins->klass = array_type;
11269                                         MONO_ADD_INS (cfg->cbb, ins);
11270                                         cfg->flags |= MONO_CFG_HAS_ARRAY_ACCESS;
11271                                         cfg->cbb->has_array_access = TRUE;
11272
11273                                         /* Needed so mono_emit_load_get_addr () gets called */
11274                                         mono_get_got_var (cfg);
11275                                 }
11276                         }
11277
11278                         len_ins = sp [0];
11279                         ip += 5;
11280                         *sp++ = ins;
11281                         inline_costs += 1;
11282
11283                         /* 
11284                          * we inline/optimize the initialization sequence if possible.
11285                          * we should also allocate the array as not cleared, since we spend as much time clearing to 0 as initializing
11286                          * for small sizes open code the memcpy
11287                          * ensure the rva field is big enough
11288                          */
11289                         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))) {
11290                                 MonoMethod *memcpy_method = get_memcpy_method ();
11291                                 MonoInst *iargs [3];
11292                                 int add_reg = alloc_ireg_mp (cfg);
11293
11294                                 EMIT_NEW_BIALU_IMM (cfg, iargs [0], OP_PADD_IMM, add_reg, ins->dreg, MONO_STRUCT_OFFSET (MonoArray, vector));
11295                                 if (cfg->compile_aot) {
11296                                         EMIT_NEW_AOTCONST_TOKEN (cfg, iargs [1], MONO_PATCH_INFO_RVA, method->klass->image, GPOINTER_TO_UINT(field_token), STACK_PTR, NULL);
11297                                 } else {
11298                                         EMIT_NEW_PCONST (cfg, iargs [1], (char*)data_ptr);
11299                                 }
11300                                 EMIT_NEW_ICONST (cfg, iargs [2], data_size);
11301                                 mono_emit_method_call (cfg, memcpy_method, iargs, NULL);
11302                                 ip += 11;
11303                         }
11304
11305                         break;
11306                 }
11307                 case CEE_LDLEN:
11308                         CHECK_STACK (1);
11309                         --sp;
11310                         if (sp [0]->type != STACK_OBJ)
11311                                 UNVERIFIED;
11312
11313                         MONO_INST_NEW (cfg, ins, OP_LDLEN);
11314                         ins->dreg = alloc_preg (cfg);
11315                         ins->sreg1 = sp [0]->dreg;
11316                         ins->type = STACK_I4;
11317                         /* This flag will be inherited by the decomposition */
11318                         ins->flags |= MONO_INST_FAULT;
11319                         MONO_ADD_INS (cfg->cbb, ins);
11320                         cfg->flags |= MONO_CFG_HAS_ARRAY_ACCESS;
11321                         cfg->cbb->has_array_access = TRUE;
11322                         ip ++;
11323                         *sp++ = ins;
11324                         break;
11325                 case CEE_LDELEMA:
11326                         CHECK_STACK (2);
11327                         sp -= 2;
11328                         CHECK_OPSIZE (5);
11329                         if (sp [0]->type != STACK_OBJ)
11330                                 UNVERIFIED;
11331
11332                         cfg->flags |= MONO_CFG_HAS_LDELEMA;
11333
11334                         klass = mini_get_class (method, read32 (ip + 1), generic_context);
11335                         CHECK_TYPELOAD (klass);
11336                         /* we need to make sure that this array is exactly the type it needs
11337                          * to be for correctness. the wrappers are lax with their usage
11338                          * so we need to ignore them here
11339                          */
11340                         if (!klass->valuetype && method->wrapper_type == MONO_WRAPPER_NONE && !readonly) {
11341                                 MonoClass *array_class = mono_array_class_get (klass, 1);
11342                                 mini_emit_check_array_type (cfg, sp [0], array_class);
11343                                 CHECK_TYPELOAD (array_class);
11344                         }
11345
11346                         readonly = FALSE;
11347                         ins = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1], TRUE);
11348                         *sp++ = ins;
11349                         ip += 5;
11350                         break;
11351                 case CEE_LDELEM:
11352                 case CEE_LDELEM_I1:
11353                 case CEE_LDELEM_U1:
11354                 case CEE_LDELEM_I2:
11355                 case CEE_LDELEM_U2:
11356                 case CEE_LDELEM_I4:
11357                 case CEE_LDELEM_U4:
11358                 case CEE_LDELEM_I8:
11359                 case CEE_LDELEM_I:
11360                 case CEE_LDELEM_R4:
11361                 case CEE_LDELEM_R8:
11362                 case CEE_LDELEM_REF: {
11363                         MonoInst *addr;
11364
11365                         CHECK_STACK (2);
11366                         sp -= 2;
11367
11368                         if (*ip == CEE_LDELEM) {
11369                                 CHECK_OPSIZE (5);
11370                                 token = read32 (ip + 1);
11371                                 klass = mini_get_class (method, token, generic_context);
11372                                 CHECK_TYPELOAD (klass);
11373                                 mono_class_init (klass);
11374                         }
11375                         else
11376                                 klass = array_access_to_klass (*ip);
11377
11378                         if (sp [0]->type != STACK_OBJ)
11379                                 UNVERIFIED;
11380
11381                         cfg->flags |= MONO_CFG_HAS_LDELEMA;
11382
11383                         if (mini_is_gsharedvt_variable_klass (klass)) {
11384                                 // FIXME-VT: OP_ICONST optimization
11385                                 addr = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1], TRUE);
11386                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr->dreg, 0);
11387                                 ins->opcode = OP_LOADV_MEMBASE;
11388                         } else if (sp [1]->opcode == OP_ICONST) {
11389                                 int array_reg = sp [0]->dreg;
11390                                 int index_reg = sp [1]->dreg;
11391                                 int offset = (mono_class_array_element_size (klass) * sp [1]->inst_c0) + MONO_STRUCT_OFFSET (MonoArray, vector);
11392
11393                                 if (SIZEOF_REGISTER == 8 && COMPILE_LLVM (cfg))
11394                                         MONO_EMIT_NEW_UNALU (cfg, OP_ZEXT_I4, index_reg, index_reg);
11395
11396                                 MONO_EMIT_BOUNDS_CHECK (cfg, array_reg, MonoArray, max_length, index_reg);
11397                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, array_reg, offset);
11398                         } else {
11399                                 addr = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1], TRUE);
11400                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr->dreg, 0);
11401                         }
11402                         *sp++ = ins;
11403                         if (*ip == CEE_LDELEM)
11404                                 ip += 5;
11405                         else
11406                                 ++ip;
11407                         break;
11408                 }
11409                 case CEE_STELEM_I:
11410                 case CEE_STELEM_I1:
11411                 case CEE_STELEM_I2:
11412                 case CEE_STELEM_I4:
11413                 case CEE_STELEM_I8:
11414                 case CEE_STELEM_R4:
11415                 case CEE_STELEM_R8:
11416                 case CEE_STELEM_REF:
11417                 case CEE_STELEM: {
11418                         CHECK_STACK (3);
11419                         sp -= 3;
11420
11421                         cfg->flags |= MONO_CFG_HAS_LDELEMA;
11422
11423                         if (*ip == CEE_STELEM) {
11424                                 CHECK_OPSIZE (5);
11425                                 token = read32 (ip + 1);
11426                                 klass = mini_get_class (method, token, generic_context);
11427                                 CHECK_TYPELOAD (klass);
11428                                 mono_class_init (klass);
11429                         }
11430                         else
11431                                 klass = array_access_to_klass (*ip);
11432
11433                         if (sp [0]->type != STACK_OBJ)
11434                                 UNVERIFIED;
11435
11436                         emit_array_store (cfg, klass, sp, TRUE);
11437
11438                         if (*ip == CEE_STELEM)
11439                                 ip += 5;
11440                         else
11441                                 ++ip;
11442                         inline_costs += 1;
11443                         break;
11444                 }
11445                 case CEE_CKFINITE: {
11446                         CHECK_STACK (1);
11447                         --sp;
11448
11449                         if (cfg->llvm_only) {
11450                                 MonoInst *iargs [1];
11451
11452                                 iargs [0] = sp [0];
11453                                 *sp++ = mono_emit_jit_icall (cfg, mono_ckfinite, iargs);
11454                         } else  {
11455                                 MONO_INST_NEW (cfg, ins, OP_CKFINITE);
11456                                 ins->sreg1 = sp [0]->dreg;
11457                                 ins->dreg = alloc_freg (cfg);
11458                                 ins->type = STACK_R8;
11459                                 MONO_ADD_INS (cfg->cbb, ins);
11460
11461                                 *sp++ = mono_decompose_opcode (cfg, ins);
11462                         }
11463
11464                         ++ip;
11465                         break;
11466                 }
11467                 case CEE_REFANYVAL: {
11468                         MonoInst *src_var, *src;
11469
11470                         int klass_reg = alloc_preg (cfg);
11471                         int dreg = alloc_preg (cfg);
11472
11473                         GSHAREDVT_FAILURE (*ip);
11474
11475                         CHECK_STACK (1);
11476                         MONO_INST_NEW (cfg, ins, *ip);
11477                         --sp;
11478                         CHECK_OPSIZE (5);
11479                         klass = mini_get_class (method, read32 (ip + 1), generic_context);
11480                         CHECK_TYPELOAD (klass);
11481
11482                         context_used = mini_class_check_context_used (cfg, klass);
11483
11484                         // FIXME:
11485                         src_var = get_vreg_to_inst (cfg, sp [0]->dreg);
11486                         if (!src_var)
11487                                 src_var = mono_compile_create_var_for_vreg (cfg, &mono_defaults.typed_reference_class->byval_arg, OP_LOCAL, sp [0]->dreg);
11488                         EMIT_NEW_VARLOADA (cfg, src, src_var, src_var->inst_vtype);
11489                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, src->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, klass));
11490
11491                         if (context_used) {
11492                                 MonoInst *klass_ins;
11493
11494                                 klass_ins = mini_emit_get_rgctx_klass (cfg, context_used,
11495                                                 klass, MONO_RGCTX_INFO_KLASS);
11496
11497                                 // FIXME:
11498                                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, klass_reg, klass_ins->dreg);
11499                                 MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "InvalidCastException");
11500                         } else {
11501                                 mini_emit_class_check (cfg, klass_reg, klass);
11502                         }
11503                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, dreg, src->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, value));
11504                         ins->type = STACK_MP;
11505                         ins->klass = klass;
11506                         *sp++ = ins;
11507                         ip += 5;
11508                         break;
11509                 }
11510                 case CEE_MKREFANY: {
11511                         MonoInst *loc, *addr;
11512
11513                         GSHAREDVT_FAILURE (*ip);
11514
11515                         CHECK_STACK (1);
11516                         MONO_INST_NEW (cfg, ins, *ip);
11517                         --sp;
11518                         CHECK_OPSIZE (5);
11519                         klass = mini_get_class (method, read32 (ip + 1), generic_context);
11520                         CHECK_TYPELOAD (klass);
11521
11522                         context_used = mini_class_check_context_used (cfg, klass);
11523
11524                         loc = mono_compile_create_var (cfg, &mono_defaults.typed_reference_class->byval_arg, OP_LOCAL);
11525                         EMIT_NEW_TEMPLOADA (cfg, addr, loc->inst_c0);
11526
11527                         if (context_used) {
11528                                 MonoInst *const_ins;
11529                                 int type_reg = alloc_preg (cfg);
11530
11531                                 const_ins = mini_emit_get_rgctx_klass (cfg, context_used, klass, MONO_RGCTX_INFO_KLASS);
11532                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, klass), const_ins->dreg);
11533                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ADD_IMM, type_reg, const_ins->dreg, MONO_STRUCT_OFFSET (MonoClass, byval_arg));
11534                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, type), type_reg);
11535                         } else {
11536                                 int const_reg = alloc_preg (cfg);
11537                                 int type_reg = alloc_preg (cfg);
11538
11539                                 MONO_EMIT_NEW_CLASSCONST (cfg, const_reg, klass);
11540                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, klass), const_reg);
11541                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ADD_IMM, type_reg, const_reg, MONO_STRUCT_OFFSET (MonoClass, byval_arg));
11542                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, type), type_reg);
11543                         }
11544                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, value), sp [0]->dreg);
11545
11546                         EMIT_NEW_TEMPLOAD (cfg, ins, loc->inst_c0);
11547                         ins->type = STACK_VTYPE;
11548                         ins->klass = mono_defaults.typed_reference_class;
11549                         *sp++ = ins;
11550                         ip += 5;
11551                         break;
11552                 }
11553                 case CEE_LDTOKEN: {
11554                         gpointer handle;
11555                         MonoClass *handle_class;
11556
11557                         CHECK_STACK_OVF (1);
11558
11559                         CHECK_OPSIZE (5);
11560                         n = read32 (ip + 1);
11561
11562                         if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD ||
11563                                         method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED) {
11564                                 handle = mono_method_get_wrapper_data (method, n);
11565                                 handle_class = (MonoClass *)mono_method_get_wrapper_data (method, n + 1);
11566                                 if (handle_class == mono_defaults.typehandle_class)
11567                                         handle = &((MonoClass*)handle)->byval_arg;
11568                         }
11569                         else {
11570                                 handle = mono_ldtoken_checked (image, n, &handle_class, generic_context, &cfg->error);
11571                                 CHECK_CFG_ERROR;
11572                         }
11573                         if (!handle)
11574                                 LOAD_ERROR;
11575                         mono_class_init (handle_class);
11576                         if (cfg->gshared) {
11577                                 if (mono_metadata_token_table (n) == MONO_TABLE_TYPEDEF ||
11578                                                 mono_metadata_token_table (n) == MONO_TABLE_TYPEREF) {
11579                                         /* This case handles ldtoken
11580                                            of an open type, like for
11581                                            typeof(Gen<>). */
11582                                         context_used = 0;
11583                                 } else if (handle_class == mono_defaults.typehandle_class) {
11584                                         context_used = mini_class_check_context_used (cfg, mono_class_from_mono_type ((MonoType *)handle));
11585                                 } else if (handle_class == mono_defaults.fieldhandle_class)
11586                                         context_used = mini_class_check_context_used (cfg, ((MonoClassField*)handle)->parent);
11587                                 else if (handle_class == mono_defaults.methodhandle_class)
11588                                         context_used = mini_method_check_context_used (cfg, (MonoMethod *)handle);
11589                                 else
11590                                         g_assert_not_reached ();
11591                         }
11592
11593                         if ((cfg->opt & MONO_OPT_SHARED) &&
11594                                         method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD &&
11595                                         method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED) {
11596                                 MonoInst *addr, *vtvar, *iargs [3];
11597                                 int method_context_used;
11598
11599                                 method_context_used = mini_method_check_context_used (cfg, method);
11600
11601                                 vtvar = mono_compile_create_var (cfg, &handle_class->byval_arg, OP_LOCAL); 
11602
11603                                 EMIT_NEW_IMAGECONST (cfg, iargs [0], image);
11604                                 EMIT_NEW_ICONST (cfg, iargs [1], n);
11605                                 if (method_context_used) {
11606                                         iargs [2] = emit_get_rgctx_method (cfg, method_context_used,
11607                                                 method, MONO_RGCTX_INFO_METHOD);
11608                                         ins = mono_emit_jit_icall (cfg, mono_ldtoken_wrapper_generic_shared, iargs);
11609                                 } else {
11610                                         EMIT_NEW_PCONST (cfg, iargs [2], generic_context);
11611                                         ins = mono_emit_jit_icall (cfg, mono_ldtoken_wrapper, iargs);
11612                                 }
11613                                 EMIT_NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
11614
11615                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, addr->dreg, 0, ins->dreg);
11616
11617                                 EMIT_NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
11618                         } else {
11619                                 if ((ip + 5 < end) && ip_in_bb (cfg, cfg->cbb, ip + 5) && 
11620                                         ((ip [5] == CEE_CALL) || (ip [5] == CEE_CALLVIRT)) && 
11621                                         (cmethod = mini_get_method (cfg, method, read32 (ip + 6), NULL, generic_context)) &&
11622                                         (cmethod->klass == mono_defaults.systemtype_class) &&
11623                                         (strcmp (cmethod->name, "GetTypeFromHandle") == 0)) {
11624                                         MonoClass *tclass = mono_class_from_mono_type ((MonoType *)handle);
11625
11626                                         mono_class_init (tclass);
11627                                         if (context_used) {
11628                                                 ins = mini_emit_get_rgctx_klass (cfg, context_used,
11629                                                         tclass, MONO_RGCTX_INFO_REFLECTION_TYPE);
11630                                         } else if (cfg->compile_aot) {
11631                                                 if (method->wrapper_type) {
11632                                                         error_init (&error); //got to do it since there are multiple conditionals below
11633                                                         if (mono_class_get_checked (tclass->image, tclass->type_token, &error) == tclass && !generic_context) {
11634                                                                 /* Special case for static synchronized wrappers */
11635                                                                 EMIT_NEW_TYPE_FROM_HANDLE_CONST (cfg, ins, tclass->image, tclass->type_token, generic_context);
11636                                                         } else {
11637                                                                 mono_error_cleanup (&error); /* FIXME don't swallow the error */
11638                                                                 /* FIXME: n is not a normal token */
11639                                                                 DISABLE_AOT (cfg);
11640                                                                 EMIT_NEW_PCONST (cfg, ins, NULL);
11641                                                         }
11642                                                 } else {
11643                                                         EMIT_NEW_TYPE_FROM_HANDLE_CONST (cfg, ins, image, n, generic_context);
11644                                                 }
11645                                         } else {
11646                                                 MonoReflectionType *rt = mono_type_get_object_checked (cfg->domain, (MonoType *)handle, &cfg->error);
11647                                                 CHECK_CFG_ERROR;
11648                                                 EMIT_NEW_PCONST (cfg, ins, rt);
11649                                         }
11650                                         ins->type = STACK_OBJ;
11651                                         ins->klass = cmethod->klass;
11652                                         ip += 5;
11653                                 } else {
11654                                         MonoInst *addr, *vtvar;
11655
11656                                         vtvar = mono_compile_create_var (cfg, &handle_class->byval_arg, OP_LOCAL);
11657
11658                                         if (context_used) {
11659                                                 if (handle_class == mono_defaults.typehandle_class) {
11660                                                         ins = mini_emit_get_rgctx_klass (cfg, context_used,
11661                                                                         mono_class_from_mono_type ((MonoType *)handle),
11662                                                                         MONO_RGCTX_INFO_TYPE);
11663                                                 } else if (handle_class == mono_defaults.methodhandle_class) {
11664                                                         ins = emit_get_rgctx_method (cfg, context_used,
11665                                                                         (MonoMethod *)handle, MONO_RGCTX_INFO_METHOD);
11666                                                 } else if (handle_class == mono_defaults.fieldhandle_class) {
11667                                                         ins = emit_get_rgctx_field (cfg, context_used,
11668                                                                         (MonoClassField *)handle, MONO_RGCTX_INFO_CLASS_FIELD);
11669                                                 } else {
11670                                                         g_assert_not_reached ();
11671                                                 }
11672                                         } else if (cfg->compile_aot) {
11673                                                 EMIT_NEW_LDTOKENCONST (cfg, ins, image, n, generic_context);
11674                                         } else {
11675                                                 EMIT_NEW_PCONST (cfg, ins, handle);
11676                                         }
11677                                         EMIT_NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
11678                                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, addr->dreg, 0, ins->dreg);
11679                                         EMIT_NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
11680                                 }
11681                         }
11682
11683                         *sp++ = ins;
11684                         ip += 5;
11685                         break;
11686                 }
11687                 case CEE_THROW:
11688                         CHECK_STACK (1);
11689                         if (sp [-1]->type != STACK_OBJ)
11690                                 UNVERIFIED;
11691
11692                         MONO_INST_NEW (cfg, ins, OP_THROW);
11693                         --sp;
11694                         ins->sreg1 = sp [0]->dreg;
11695                         ip++;
11696                         cfg->cbb->out_of_line = TRUE;
11697                         MONO_ADD_INS (cfg->cbb, ins);
11698                         MONO_INST_NEW (cfg, ins, OP_NOT_REACHED);
11699                         MONO_ADD_INS (cfg->cbb, ins);
11700                         sp = stack_start;
11701                         
11702                         link_bblock (cfg, cfg->cbb, end_bblock);
11703                         start_new_bblock = 1;
11704                         /* This can complicate code generation for llvm since the return value might not be defined */
11705                         if (COMPILE_LLVM (cfg))
11706                                 INLINE_FAILURE ("throw");
11707                         break;
11708                 case CEE_ENDFINALLY:
11709                         if (!ip_in_finally_clause (cfg, ip - header->code))
11710                                 UNVERIFIED;
11711                         /* mono_save_seq_point_info () depends on this */
11712                         if (sp != stack_start)
11713                                 emit_seq_point (cfg, method, ip, FALSE, FALSE);
11714                         MONO_INST_NEW (cfg, ins, OP_ENDFINALLY);
11715                         MONO_ADD_INS (cfg->cbb, ins);
11716                         ip++;
11717                         start_new_bblock = 1;
11718
11719                         /*
11720                          * Control will leave the method so empty the stack, otherwise
11721                          * the next basic block will start with a nonempty stack.
11722                          */
11723                         while (sp != stack_start) {
11724                                 sp--;
11725                         }
11726                         break;
11727                 case CEE_LEAVE:
11728                 case CEE_LEAVE_S: {
11729                         GList *handlers;
11730
11731                         if (*ip == CEE_LEAVE) {
11732                                 CHECK_OPSIZE (5);
11733                                 target = ip + 5 + (gint32)read32(ip + 1);
11734                         } else {
11735                                 CHECK_OPSIZE (2);
11736                                 target = ip + 2 + (signed char)(ip [1]);
11737                         }
11738
11739                         /* empty the stack */
11740                         while (sp != stack_start) {
11741                                 sp--;
11742                         }
11743
11744                         /* 
11745                          * If this leave statement is in a catch block, check for a
11746                          * pending exception, and rethrow it if necessary.
11747                          * We avoid doing this in runtime invoke wrappers, since those are called
11748                          * by native code which excepts the wrapper to catch all exceptions.
11749                          */
11750                         for (i = 0; i < header->num_clauses; ++i) {
11751                                 MonoExceptionClause *clause = &header->clauses [i];
11752
11753                                 /* 
11754                                  * Use <= in the final comparison to handle clauses with multiple
11755                                  * leave statements, like in bug #78024.
11756                                  * The ordering of the exception clauses guarantees that we find the
11757                                  * innermost clause.
11758                                  */
11759                                 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) {
11760                                         MonoInst *exc_ins;
11761                                         MonoBasicBlock *dont_throw;
11762
11763                                         /*
11764                                           MonoInst *load;
11765
11766                                           NEW_TEMPLOAD (cfg, load, mono_find_exvar_for_offset (cfg, clause->handler_offset)->inst_c0);
11767                                         */
11768
11769                                         exc_ins = mono_emit_jit_icall (cfg, mono_thread_get_undeniable_exception, NULL);
11770
11771                                         NEW_BBLOCK (cfg, dont_throw);
11772
11773                                         /*
11774                                          * Currently, we always rethrow the abort exception, despite the 
11775                                          * fact that this is not correct. See thread6.cs for an example. 
11776                                          * But propagating the abort exception is more important than 
11777                                          * getting the sematics right.
11778                                          */
11779                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, exc_ins->dreg, 0);
11780                                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, dont_throw);
11781                                         MONO_EMIT_NEW_UNALU (cfg, OP_THROW, -1, exc_ins->dreg);
11782
11783                                         MONO_START_BB (cfg, dont_throw);
11784                                 }
11785                         }
11786
11787 #ifdef ENABLE_LLVM
11788                         cfg->cbb->try_end = (intptr_t)(ip - header->code);
11789 #endif
11790
11791                         if ((handlers = mono_find_final_block (cfg, ip, target, MONO_EXCEPTION_CLAUSE_FINALLY))) {
11792                                 GList *tmp;
11793                                 MonoExceptionClause *clause;
11794
11795                                 for (tmp = handlers; tmp; tmp = tmp->next) {
11796                                         clause = (MonoExceptionClause *)tmp->data;
11797                                         tblock = cfg->cil_offset_to_bb [clause->handler_offset];
11798                                         g_assert (tblock);
11799                                         link_bblock (cfg, cfg->cbb, tblock);
11800                                         MONO_INST_NEW (cfg, ins, OP_CALL_HANDLER);
11801                                         ins->inst_target_bb = tblock;
11802                                         ins->inst_eh_block = clause;
11803                                         MONO_ADD_INS (cfg->cbb, ins);
11804                                         cfg->cbb->has_call_handler = 1;
11805                                         if (COMPILE_LLVM (cfg)) {
11806                                                 MonoBasicBlock *target_bb;
11807
11808                                                 /* 
11809                                                  * Link the finally bblock with the target, since it will
11810                                                  * conceptually branch there.
11811                                                  */
11812                                                 GET_BBLOCK (cfg, tblock, cfg->cil_start + clause->handler_offset + clause->handler_len - 1);
11813                                                 GET_BBLOCK (cfg, target_bb, target);
11814                                                 link_bblock (cfg, tblock, target_bb);
11815                                         }
11816                                 }
11817                                 g_list_free (handlers);
11818                         } 
11819
11820                         MONO_INST_NEW (cfg, ins, OP_BR);
11821                         MONO_ADD_INS (cfg->cbb, ins);
11822                         GET_BBLOCK (cfg, tblock, target);
11823                         link_bblock (cfg, cfg->cbb, tblock);
11824                         ins->inst_target_bb = tblock;
11825
11826                         start_new_bblock = 1;
11827
11828                         if (*ip == CEE_LEAVE)
11829                                 ip += 5;
11830                         else
11831                                 ip += 2;
11832
11833                         break;
11834                 }
11835
11836                         /*
11837                          * Mono specific opcodes
11838                          */
11839                 case MONO_CUSTOM_PREFIX: {
11840
11841                         g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
11842
11843                         CHECK_OPSIZE (2);
11844                         switch (ip [1]) {
11845                         case CEE_MONO_ICALL: {
11846                                 gpointer func;
11847                                 MonoJitICallInfo *info;
11848
11849                                 token = read32 (ip + 2);
11850                                 func = mono_method_get_wrapper_data (method, token);
11851                                 info = mono_find_jit_icall_by_addr (func);
11852                                 if (!info)
11853                                         g_error ("Could not find icall address in wrapper %s", mono_method_full_name (method, 1));
11854                                 g_assert (info);
11855
11856                                 CHECK_STACK (info->sig->param_count);
11857                                 sp -= info->sig->param_count;
11858
11859                                 ins = mono_emit_jit_icall (cfg, info->func, sp);
11860                                 if (!MONO_TYPE_IS_VOID (info->sig->ret))
11861                                         *sp++ = ins;
11862
11863                                 ip += 6;
11864                                 inline_costs += 10 * num_calls++;
11865
11866                                 break;
11867                         }
11868                         case CEE_MONO_LDPTR_CARD_TABLE:
11869                         case CEE_MONO_LDPTR_NURSERY_START:
11870                         case CEE_MONO_LDPTR_NURSERY_BITS:
11871                         case CEE_MONO_LDPTR_INT_REQ_FLAG: {
11872                                 CHECK_STACK_OVF (1);
11873
11874                                 switch (ip [1]) {
11875                                         case CEE_MONO_LDPTR_CARD_TABLE:
11876                                                 ins = emit_runtime_constant (cfg, MONO_PATCH_INFO_GC_CARD_TABLE_ADDR, NULL);
11877                                                 break;
11878                                         case CEE_MONO_LDPTR_NURSERY_START:
11879                                                 ins = emit_runtime_constant (cfg, MONO_PATCH_INFO_GC_NURSERY_START, NULL);
11880                                                 break;
11881                                         case CEE_MONO_LDPTR_NURSERY_BITS:
11882                                                 ins = emit_runtime_constant (cfg, MONO_PATCH_INFO_GC_NURSERY_BITS, NULL);
11883                                                 break;
11884                                         case CEE_MONO_LDPTR_INT_REQ_FLAG:
11885                                                 ins = emit_runtime_constant (cfg, MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG, NULL);
11886                                                 break;
11887                                 }
11888
11889                                 *sp++ = ins;
11890                                 ip += 2;
11891                                 inline_costs += 10 * num_calls++;
11892                                 break;
11893                         }
11894                         case CEE_MONO_LDPTR: {
11895                                 gpointer ptr;
11896
11897                                 CHECK_STACK_OVF (1);
11898                                 CHECK_OPSIZE (6);
11899                                 token = read32 (ip + 2);
11900
11901                                 ptr = mono_method_get_wrapper_data (method, token);
11902                                 EMIT_NEW_PCONST (cfg, ins, ptr);
11903                                 *sp++ = ins;
11904                                 ip += 6;
11905                                 inline_costs += 10 * num_calls++;
11906                                 /* Can't embed random pointers into AOT code */
11907                                 DISABLE_AOT (cfg);
11908                                 break;
11909                         }
11910                         case CEE_MONO_JIT_ICALL_ADDR: {
11911                                 MonoJitICallInfo *callinfo;
11912                                 gpointer ptr;
11913
11914                                 CHECK_STACK_OVF (1);
11915                                 CHECK_OPSIZE (6);
11916                                 token = read32 (ip + 2);
11917
11918                                 ptr = mono_method_get_wrapper_data (method, token);
11919                                 callinfo = mono_find_jit_icall_by_addr (ptr);
11920                                 g_assert (callinfo);
11921                                 EMIT_NEW_JIT_ICALL_ADDRCONST (cfg, ins, (char*)callinfo->name);
11922                                 *sp++ = ins;
11923                                 ip += 6;
11924                                 inline_costs += 10 * num_calls++;
11925                                 break;
11926                         }
11927                         case CEE_MONO_ICALL_ADDR: {
11928                                 MonoMethod *cmethod;
11929                                 gpointer ptr;
11930
11931                                 CHECK_STACK_OVF (1);
11932                                 CHECK_OPSIZE (6);
11933                                 token = read32 (ip + 2);
11934
11935                                 cmethod = (MonoMethod *)mono_method_get_wrapper_data (method, token);
11936
11937                                 if (cfg->compile_aot) {
11938                                         if (cfg->direct_pinvoke && ip + 6 < end && (ip [6] == CEE_POP)) {
11939                                                 /*
11940                                                  * This is generated by emit_native_wrapper () to resolve the pinvoke address
11941                                                  * before the call, its not needed when using direct pinvoke.
11942                                                  * This is not an optimization, but its used to avoid looking up pinvokes
11943                                                  * on platforms which don't support dlopen ().
11944                                                  */
11945                                                 EMIT_NEW_PCONST (cfg, ins, NULL);
11946                                         } else {
11947                                                 EMIT_NEW_AOTCONST (cfg, ins, MONO_PATCH_INFO_ICALL_ADDR, cmethod);
11948                                         }
11949                                 } else {
11950                                         ptr = mono_lookup_internal_call (cmethod);
11951                                         g_assert (ptr);
11952                                         EMIT_NEW_PCONST (cfg, ins, ptr);
11953                                 }
11954                                 *sp++ = ins;
11955                                 ip += 6;
11956                                 break;
11957                         }
11958                         case CEE_MONO_VTADDR: {
11959                                 MonoInst *src_var, *src;
11960
11961                                 CHECK_STACK (1);
11962                                 --sp;
11963
11964                                 // FIXME:
11965                                 src_var = get_vreg_to_inst (cfg, sp [0]->dreg);
11966                                 EMIT_NEW_VARLOADA ((cfg), (src), src_var, src_var->inst_vtype);
11967                                 *sp++ = src;
11968                                 ip += 2;
11969                                 break;
11970                         }
11971                         case CEE_MONO_NEWOBJ: {
11972                                 MonoInst *iargs [2];
11973
11974                                 CHECK_STACK_OVF (1);
11975                                 CHECK_OPSIZE (6);
11976                                 token = read32 (ip + 2);
11977                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
11978                                 mono_class_init (klass);
11979                                 NEW_DOMAINCONST (cfg, iargs [0]);
11980                                 MONO_ADD_INS (cfg->cbb, iargs [0]);
11981                                 NEW_CLASSCONST (cfg, iargs [1], klass);
11982                                 MONO_ADD_INS (cfg->cbb, iargs [1]);
11983                                 *sp++ = mono_emit_jit_icall (cfg, ves_icall_object_new, iargs);
11984                                 ip += 6;
11985                                 inline_costs += 10 * num_calls++;
11986                                 break;
11987                         }
11988                         case CEE_MONO_OBJADDR:
11989                                 CHECK_STACK (1);
11990                                 --sp;
11991                                 MONO_INST_NEW (cfg, ins, OP_MOVE);
11992                                 ins->dreg = alloc_ireg_mp (cfg);
11993                                 ins->sreg1 = sp [0]->dreg;
11994                                 ins->type = STACK_MP;
11995                                 MONO_ADD_INS (cfg->cbb, ins);
11996                                 *sp++ = ins;
11997                                 ip += 2;
11998                                 break;
11999                         case CEE_MONO_LDNATIVEOBJ:
12000                                 /*
12001                                  * Similar to LDOBJ, but instead load the unmanaged 
12002                                  * representation of the vtype to the stack.
12003                                  */
12004                                 CHECK_STACK (1);
12005                                 CHECK_OPSIZE (6);
12006                                 --sp;
12007                                 token = read32 (ip + 2);
12008                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
12009                                 g_assert (klass->valuetype);
12010                                 mono_class_init (klass);
12011
12012                                 {
12013                                         MonoInst *src, *dest, *temp;
12014
12015                                         src = sp [0];
12016                                         temp = mono_compile_create_var (cfg, &klass->byval_arg, OP_LOCAL);
12017                                         temp->backend.is_pinvoke = 1;
12018                                         EMIT_NEW_TEMPLOADA (cfg, dest, temp->inst_c0);
12019                                         mini_emit_stobj (cfg, dest, src, klass, TRUE);
12020
12021                                         EMIT_NEW_TEMPLOAD (cfg, dest, temp->inst_c0);
12022                                         dest->type = STACK_VTYPE;
12023                                         dest->klass = klass;
12024
12025                                         *sp ++ = dest;
12026                                         ip += 6;
12027                                 }
12028                                 break;
12029                         case CEE_MONO_RETOBJ: {
12030                                 /*
12031                                  * Same as RET, but return the native representation of a vtype
12032                                  * to the caller.
12033                                  */
12034                                 g_assert (cfg->ret);
12035                                 g_assert (mono_method_signature (method)->pinvoke); 
12036                                 CHECK_STACK (1);
12037                                 --sp;
12038                                 
12039                                 CHECK_OPSIZE (6);
12040                                 token = read32 (ip + 2);    
12041                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
12042
12043                                 if (!cfg->vret_addr) {
12044                                         g_assert (cfg->ret_var_is_local);
12045
12046                                         EMIT_NEW_VARLOADA (cfg, ins, cfg->ret, cfg->ret->inst_vtype);
12047                                 } else {
12048                                         EMIT_NEW_RETLOADA (cfg, ins);
12049                                 }
12050                                 mini_emit_stobj (cfg, ins, sp [0], klass, TRUE);
12051                                 
12052                                 if (sp != stack_start)
12053                                         UNVERIFIED;
12054                                 
12055                                 MONO_INST_NEW (cfg, ins, OP_BR);
12056                                 ins->inst_target_bb = end_bblock;
12057                                 MONO_ADD_INS (cfg->cbb, ins);
12058                                 link_bblock (cfg, cfg->cbb, end_bblock);
12059                                 start_new_bblock = 1;
12060                                 ip += 6;
12061                                 break;
12062                         }
12063                         case CEE_MONO_SAVE_LMF:
12064                         case CEE_MONO_RESTORE_LMF:
12065                                 ip += 2;
12066                                 break;
12067                         case CEE_MONO_CLASSCONST:
12068                                 CHECK_STACK_OVF (1);
12069                                 CHECK_OPSIZE (6);
12070                                 token = read32 (ip + 2);
12071                                 EMIT_NEW_CLASSCONST (cfg, ins, mono_method_get_wrapper_data (method, token));
12072                                 *sp++ = ins;
12073                                 ip += 6;
12074                                 inline_costs += 10 * num_calls++;
12075                                 break;
12076                         case CEE_MONO_NOT_TAKEN:
12077                                 cfg->cbb->out_of_line = TRUE;
12078                                 ip += 2;
12079                                 break;
12080                         case CEE_MONO_TLS: {
12081                                 MonoTlsKey key;
12082
12083                                 CHECK_STACK_OVF (1);
12084                                 CHECK_OPSIZE (6);
12085                                 key = (MonoTlsKey)read32 (ip + 2);
12086                                 g_assert (key < TLS_KEY_NUM);
12087
12088                                 ins = mono_create_tls_get (cfg, key);
12089                                 g_assert (ins);
12090                                 ins->type = STACK_PTR;
12091                                 *sp++ = ins;
12092                                 ip += 6;
12093                                 break;
12094                         }
12095                         case CEE_MONO_DYN_CALL: {
12096                                 MonoCallInst *call;
12097
12098                                 /* It would be easier to call a trampoline, but that would put an
12099                                  * extra frame on the stack, confusing exception handling. So
12100                                  * implement it inline using an opcode for now.
12101                                  */
12102
12103                                 if (!cfg->dyn_call_var) {
12104                                         cfg->dyn_call_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
12105                                         /* prevent it from being register allocated */
12106                                         cfg->dyn_call_var->flags |= MONO_INST_VOLATILE;
12107                                 }
12108
12109                                 /* Has to use a call inst since it local regalloc expects it */
12110                                 MONO_INST_NEW_CALL (cfg, call, OP_DYN_CALL);
12111                                 ins = (MonoInst*)call;
12112                                 sp -= 2;
12113                                 ins->sreg1 = sp [0]->dreg;
12114                                 ins->sreg2 = sp [1]->dreg;
12115                                 MONO_ADD_INS (cfg->cbb, ins);
12116
12117                                 cfg->param_area = MAX (cfg->param_area, cfg->backend->dyn_call_param_area);
12118
12119                                 ip += 2;
12120                                 inline_costs += 10 * num_calls++;
12121
12122                                 break;
12123                         }
12124                         case CEE_MONO_MEMORY_BARRIER: {
12125                                 CHECK_OPSIZE (6);
12126                                 emit_memory_barrier (cfg, (int)read32 (ip + 2));
12127                                 ip += 6;
12128                                 break;
12129                         }
12130                         case CEE_MONO_ATOMIC_STORE_I4: {
12131                                 g_assert (mono_arch_opcode_supported (OP_ATOMIC_STORE_I4));
12132
12133                                 CHECK_OPSIZE (6);
12134                                 CHECK_STACK (2);
12135                                 sp -= 2;
12136
12137                                 MONO_INST_NEW (cfg, ins, OP_ATOMIC_STORE_I4);
12138                                 ins->dreg = sp [0]->dreg;
12139                                 ins->sreg1 = sp [1]->dreg;
12140                                 ins->backend.memory_barrier_kind = (int) read32 (ip + 2);
12141                                 MONO_ADD_INS (cfg->cbb, ins);
12142
12143                                 ip += 6;
12144                                 break;
12145                         }
12146                         case CEE_MONO_JIT_ATTACH: {
12147                                 MonoInst *args [16], *domain_ins;
12148                                 MonoInst *ad_ins, *jit_tls_ins;
12149                                 MonoBasicBlock *next_bb = NULL, *call_bb = NULL;
12150
12151                                 g_assert (!mono_threads_is_coop_enabled ());
12152
12153                                 cfg->orig_domain_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
12154
12155                                 EMIT_NEW_PCONST (cfg, ins, NULL);
12156                                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, cfg->orig_domain_var->dreg, ins->dreg);
12157
12158                                 ad_ins = mono_create_tls_get (cfg, TLS_KEY_DOMAIN);
12159                                 jit_tls_ins = mono_create_tls_get (cfg, TLS_KEY_JIT_TLS);
12160
12161                                 if (ad_ins && jit_tls_ins) {
12162                                         NEW_BBLOCK (cfg, next_bb);
12163                                         NEW_BBLOCK (cfg, call_bb);
12164
12165                                         if (cfg->compile_aot) {
12166                                                 /* AOT code is only used in the root domain */
12167                                                 EMIT_NEW_PCONST (cfg, domain_ins, NULL);
12168                                         } else {
12169                                                 EMIT_NEW_PCONST (cfg, domain_ins, cfg->domain);
12170                                         }
12171                                         MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, ad_ins->dreg, domain_ins->dreg);
12172                                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, call_bb);
12173
12174                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, jit_tls_ins->dreg, 0);
12175                                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, call_bb);
12176
12177                                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, next_bb);
12178                                         MONO_START_BB (cfg, call_bb);
12179                                 }
12180
12181                                 /* AOT code is only used in the root domain */
12182                                 EMIT_NEW_PCONST (cfg, args [0], cfg->compile_aot ? NULL : cfg->domain);
12183                                 if (cfg->compile_aot) {
12184                                         MonoInst *addr;
12185
12186                                         /*
12187                                          * This is called on unattached threads, so it cannot go through the trampoline
12188                                          * infrastructure. Use an indirect call through a got slot initialized at load time
12189                                          * instead.
12190                                          */
12191                                         EMIT_NEW_AOTCONST (cfg, addr, MONO_PATCH_INFO_JIT_THREAD_ATTACH, NULL);
12192                                         ins = mono_emit_calli (cfg, helper_sig_jit_thread_attach, args, addr, NULL, NULL);
12193                                 } else {
12194                                         ins = mono_emit_jit_icall (cfg, mono_jit_thread_attach, args);
12195                                 }
12196                                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, cfg->orig_domain_var->dreg, ins->dreg);
12197
12198                                 if (next_bb)
12199                                         MONO_START_BB (cfg, next_bb);
12200
12201                                 ip += 2;
12202                                 break;
12203                         }
12204                         case CEE_MONO_JIT_DETACH: {
12205                                 MonoInst *args [16];
12206
12207                                 /* Restore the original domain */
12208                                 dreg = alloc_ireg (cfg);
12209                                 EMIT_NEW_UNALU (cfg, args [0], OP_MOVE, dreg, cfg->orig_domain_var->dreg);
12210                                 mono_emit_jit_icall (cfg, mono_jit_set_domain, args);
12211                                 ip += 2;
12212                                 break;
12213                         }
12214                         case CEE_MONO_CALLI_EXTRA_ARG: {
12215                                 MonoInst *addr;
12216                                 MonoMethodSignature *fsig;
12217                                 MonoInst *arg;
12218
12219                                 /*
12220                                  * This is the same as CEE_CALLI, but passes an additional argument
12221                                  * to the called method in llvmonly mode.
12222                                  * This is only used by delegate invoke wrappers to call the
12223                                  * actual delegate method.
12224                                  */
12225                                 g_assert (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE);
12226
12227                                 CHECK_OPSIZE (6);
12228                                 token = read32 (ip + 2);
12229
12230                                 ins = NULL;
12231
12232                                 cmethod = NULL;
12233                                 CHECK_STACK (1);
12234                                 --sp;
12235                                 addr = *sp;
12236                                 fsig = mini_get_signature (method, token, generic_context, &cfg->error);
12237                                 CHECK_CFG_ERROR;
12238
12239                                 if (cfg->llvm_only)
12240                                         cfg->signatures = g_slist_prepend_mempool (cfg->mempool, cfg->signatures, fsig);
12241
12242                                 n = fsig->param_count + fsig->hasthis + 1;
12243
12244                                 CHECK_STACK (n);
12245
12246                                 sp -= n;
12247                                 arg = sp [n - 1];
12248
12249                                 if (cfg->llvm_only) {
12250                                         /*
12251                                          * The lowest bit of 'arg' determines whenever the callee uses the gsharedvt
12252                                          * cconv. This is set by mono_init_delegate ().
12253                                          */
12254                                         if (cfg->gsharedvt && mini_is_gsharedvt_variable_signature (fsig)) {
12255                                                 MonoInst *callee = addr;
12256                                                 MonoInst *call, *localloc_ins;
12257                                                 MonoBasicBlock *is_gsharedvt_bb, *end_bb;
12258                                                 int low_bit_reg = alloc_preg (cfg);
12259
12260                                                 NEW_BBLOCK (cfg, is_gsharedvt_bb);
12261                                                 NEW_BBLOCK (cfg, end_bb);
12262
12263                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PAND_IMM, low_bit_reg, arg->dreg, 1);
12264                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, low_bit_reg, 0);
12265                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, is_gsharedvt_bb);
12266
12267                                                 /* Normal case: callee uses a normal cconv, have to add an out wrapper */
12268                                                 addr = emit_get_rgctx_sig (cfg, context_used,
12269                                                                                                    fsig, MONO_RGCTX_INFO_SIG_GSHAREDVT_OUT_TRAMPOLINE_CALLI);
12270                                                 /*
12271                                                  * ADDR points to a gsharedvt-out wrapper, have to pass <callee, arg> as an extra arg.
12272                                                  */
12273                                                 MONO_INST_NEW (cfg, ins, OP_LOCALLOC_IMM);
12274                                                 ins->dreg = alloc_preg (cfg);
12275                                                 ins->inst_imm = 2 * SIZEOF_VOID_P;
12276                                                 MONO_ADD_INS (cfg->cbb, ins);
12277                                                 localloc_ins = ins;
12278                                                 cfg->flags |= MONO_CFG_HAS_ALLOCA;
12279                                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, localloc_ins->dreg, 0, callee->dreg);
12280                                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, localloc_ins->dreg, SIZEOF_VOID_P, arg->dreg);
12281
12282                                                 call = emit_extra_arg_calli (cfg, fsig, sp, localloc_ins->dreg, addr);
12283                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
12284
12285                                                 /* Gsharedvt case: callee uses a gsharedvt cconv, no conversion is needed */
12286                                                 MONO_START_BB (cfg, is_gsharedvt_bb);
12287                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PXOR_IMM, arg->dreg, arg->dreg, 1);
12288                                                 ins = emit_extra_arg_calli (cfg, fsig, sp, arg->dreg, callee);
12289                                                 ins->dreg = call->dreg;
12290
12291                                                 MONO_START_BB (cfg, end_bb);
12292                                         } else {
12293                                                 /* Caller uses a normal calling conv */
12294
12295                                                 MonoInst *callee = addr;
12296                                                 MonoInst *call, *localloc_ins;
12297                                                 MonoBasicBlock *is_gsharedvt_bb, *end_bb;
12298                                                 int low_bit_reg = alloc_preg (cfg);
12299
12300                                                 NEW_BBLOCK (cfg, is_gsharedvt_bb);
12301                                                 NEW_BBLOCK (cfg, end_bb);
12302
12303                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PAND_IMM, low_bit_reg, arg->dreg, 1);
12304                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, low_bit_reg, 0);
12305                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, is_gsharedvt_bb);
12306
12307                                                 /* Normal case: callee uses a normal cconv, no conversion is needed */
12308                                                 call = emit_extra_arg_calli (cfg, fsig, sp, arg->dreg, callee);
12309                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
12310                                                 /* Gsharedvt case: callee uses a gsharedvt cconv, have to add an in wrapper */
12311                                                 MONO_START_BB (cfg, is_gsharedvt_bb);
12312                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PXOR_IMM, arg->dreg, arg->dreg, 1);
12313                                                 NEW_AOTCONST (cfg, addr, MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER, fsig);
12314                                                 MONO_ADD_INS (cfg->cbb, addr);
12315                                                 /*
12316                                                  * ADDR points to a gsharedvt-in wrapper, have to pass <callee, arg> as an extra arg.
12317                                                  */
12318                                                 MONO_INST_NEW (cfg, ins, OP_LOCALLOC_IMM);
12319                                                 ins->dreg = alloc_preg (cfg);
12320                                                 ins->inst_imm = 2 * SIZEOF_VOID_P;
12321                                                 MONO_ADD_INS (cfg->cbb, ins);
12322                                                 localloc_ins = ins;
12323                                                 cfg->flags |= MONO_CFG_HAS_ALLOCA;
12324                                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, localloc_ins->dreg, 0, callee->dreg);
12325                                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, localloc_ins->dreg, SIZEOF_VOID_P, arg->dreg);
12326
12327                                                 ins = emit_extra_arg_calli (cfg, fsig, sp, localloc_ins->dreg, addr);
12328                                                 ins->dreg = call->dreg;
12329                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
12330
12331                                                 MONO_START_BB (cfg, end_bb);
12332                                         }
12333                                 } else {
12334                                         /* Same as CEE_CALLI */
12335                                         if (cfg->gsharedvt && mini_is_gsharedvt_signature (fsig)) {
12336                                                 /*
12337                                                  * We pass the address to the gsharedvt trampoline in the rgctx reg
12338                                                  */
12339                                                 MonoInst *callee = addr;
12340
12341                                                 addr = emit_get_rgctx_sig (cfg, context_used,
12342                                                                                                    fsig, MONO_RGCTX_INFO_SIG_GSHAREDVT_OUT_TRAMPOLINE_CALLI);
12343                                                 ins = (MonoInst*)mono_emit_calli (cfg, fsig, sp, addr, NULL, callee);
12344                                         } else {
12345                                                 ins = (MonoInst*)mono_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
12346                                         }
12347                                 }
12348
12349                                 if (!MONO_TYPE_IS_VOID (fsig->ret))
12350                                         *sp++ = mono_emit_widen_call_res (cfg, ins, fsig);
12351
12352                                 CHECK_CFG_EXCEPTION;
12353
12354                                 ip += 6;
12355                                 ins_flag = 0;
12356                                 constrained_class = NULL;
12357                                 break;
12358                         }
12359                         case CEE_MONO_LDDOMAIN:
12360                                 CHECK_STACK_OVF (1);
12361                                 EMIT_NEW_PCONST (cfg, ins, cfg->compile_aot ? NULL : cfg->domain);
12362                                 ip += 2;
12363                                 *sp++ = ins;
12364                                 break;
12365                         case CEE_MONO_GET_LAST_ERROR:
12366                                 CHECK_OPSIZE (2);
12367                                 CHECK_STACK_OVF (1);
12368
12369                                 MONO_INST_NEW (cfg, ins, OP_GET_LAST_ERROR);
12370                                 ins->dreg = alloc_dreg (cfg, STACK_I4);
12371                                 ins->type = STACK_I4;
12372                                 MONO_ADD_INS (cfg->cbb, ins);
12373
12374                                 ip += 2;
12375                                 *sp++ = ins;
12376                                 break;
12377                         case CEE_MONO_GET_RGCTX_ARG:
12378                                 CHECK_OPSIZE (2);
12379                                 CHECK_STACK_OVF (1);
12380
12381                                 mono_create_rgctx_var (cfg);
12382
12383                                 MONO_INST_NEW (cfg, ins, OP_MOVE);
12384                                 ins->dreg = alloc_dreg (cfg, STACK_PTR);
12385                                 ins->sreg1 = cfg->rgctx_var->dreg;
12386                                 ins->type = STACK_PTR;
12387                                 MONO_ADD_INS (cfg->cbb, ins);
12388
12389                                 ip += 2;
12390                                 *sp++ = ins;
12391                                 break;
12392                         default:
12393                                 g_error ("opcode 0x%02x 0x%02x not handled", MONO_CUSTOM_PREFIX, ip [1]);
12394                                 break;
12395                         }
12396                         break;
12397                 }
12398
12399                 case CEE_PREFIX1: {
12400                         CHECK_OPSIZE (2);
12401                         switch (ip [1]) {
12402                         case CEE_ARGLIST: {
12403                                 /* somewhat similar to LDTOKEN */
12404                                 MonoInst *addr, *vtvar;
12405                                 CHECK_STACK_OVF (1);
12406                                 vtvar = mono_compile_create_var (cfg, &mono_defaults.argumenthandle_class->byval_arg, OP_LOCAL); 
12407
12408                                 EMIT_NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
12409                                 EMIT_NEW_UNALU (cfg, ins, OP_ARGLIST, -1, addr->dreg);
12410
12411                                 EMIT_NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
12412                                 ins->type = STACK_VTYPE;
12413                                 ins->klass = mono_defaults.argumenthandle_class;
12414                                 *sp++ = ins;
12415                                 ip += 2;
12416                                 break;
12417                         }
12418                         case CEE_CEQ:
12419                         case CEE_CGT:
12420                         case CEE_CGT_UN:
12421                         case CEE_CLT:
12422                         case CEE_CLT_UN: {
12423                                 MonoInst *cmp, *arg1, *arg2;
12424
12425                                 CHECK_STACK (2);
12426                                 sp -= 2;
12427                                 arg1 = sp [0];
12428                                 arg2 = sp [1];
12429
12430                                 /*
12431                                  * The following transforms:
12432                                  *    CEE_CEQ    into OP_CEQ
12433                                  *    CEE_CGT    into OP_CGT
12434                                  *    CEE_CGT_UN into OP_CGT_UN
12435                                  *    CEE_CLT    into OP_CLT
12436                                  *    CEE_CLT_UN into OP_CLT_UN
12437                                  */
12438                                 MONO_INST_NEW (cfg, cmp, (OP_CEQ - CEE_CEQ) + ip [1]);
12439
12440                                 MONO_INST_NEW (cfg, ins, cmp->opcode);
12441                                 cmp->sreg1 = arg1->dreg;
12442                                 cmp->sreg2 = arg2->dreg;
12443                                 type_from_op (cfg, cmp, arg1, arg2);
12444                                 CHECK_TYPE (cmp);
12445                                 add_widen_op (cfg, cmp, &arg1, &arg2);
12446                                 if ((arg1->type == STACK_I8) || ((SIZEOF_VOID_P == 8) && ((arg1->type == STACK_PTR) || (arg1->type == STACK_OBJ) || (arg1->type == STACK_MP))))
12447                                         cmp->opcode = OP_LCOMPARE;
12448                                 else if (arg1->type == STACK_R4)
12449                                         cmp->opcode = OP_RCOMPARE;
12450                                 else if (arg1->type == STACK_R8)
12451                                         cmp->opcode = OP_FCOMPARE;
12452                                 else
12453                                         cmp->opcode = OP_ICOMPARE;
12454                                 MONO_ADD_INS (cfg->cbb, cmp);
12455                                 ins->type = STACK_I4;
12456                                 ins->dreg = alloc_dreg (cfg, (MonoStackType)ins->type);
12457                                 type_from_op (cfg, ins, arg1, arg2);
12458
12459                                 if (cmp->opcode == OP_FCOMPARE || cmp->opcode == OP_RCOMPARE) {
12460                                         /*
12461                                          * The backends expect the fceq opcodes to do the
12462                                          * comparison too.
12463                                          */
12464                                         ins->sreg1 = cmp->sreg1;
12465                                         ins->sreg2 = cmp->sreg2;
12466                                         NULLIFY_INS (cmp);
12467                                 }
12468                                 MONO_ADD_INS (cfg->cbb, ins);
12469                                 *sp++ = ins;
12470                                 ip += 2;
12471                                 break;
12472                         }
12473                         case CEE_LDFTN: {
12474                                 MonoInst *argconst;
12475                                 MonoMethod *cil_method;
12476
12477                                 CHECK_STACK_OVF (1);
12478                                 CHECK_OPSIZE (6);
12479                                 n = read32 (ip + 2);
12480                                 cmethod = mini_get_method (cfg, method, n, NULL, generic_context);
12481                                 CHECK_CFG_ERROR;
12482
12483                                 mono_class_init (cmethod->klass);
12484
12485                                 mono_save_token_info (cfg, image, n, cmethod);
12486
12487                                 context_used = mini_method_check_context_used (cfg, cmethod);
12488
12489                                 cil_method = cmethod;
12490                                 if (!dont_verify && !cfg->skip_visibility && !mono_method_can_access_method (method, cmethod))
12491                                         emit_method_access_failure (cfg, method, cil_method);
12492
12493                                 if (mono_security_core_clr_enabled ())
12494                                         ensure_method_is_allowed_to_call_method (cfg, method, cmethod);
12495
12496                                 /* 
12497                                  * Optimize the common case of ldftn+delegate creation
12498                                  */
12499                                 if ((sp > stack_start) && (ip + 6 + 5 < end) && ip_in_bb (cfg, cfg->cbb, ip + 6) && (ip [6] == CEE_NEWOBJ)) {
12500                                         MonoMethod *ctor_method = mini_get_method (cfg, method, read32 (ip + 7), NULL, generic_context);
12501                                         if (ctor_method && (ctor_method->klass->parent == mono_defaults.multicastdelegate_class)) {
12502                                                 MonoInst *target_ins, *handle_ins;
12503                                                 MonoMethod *invoke;
12504                                                 int invoke_context_used;
12505
12506                                                 invoke = mono_get_delegate_invoke (ctor_method->klass);
12507                                                 if (!invoke || !mono_method_signature (invoke))
12508                                                         LOAD_ERROR;
12509
12510                                                 invoke_context_used = mini_method_check_context_used (cfg, invoke);
12511
12512                                                 target_ins = sp [-1];
12513
12514                                                 if (mono_security_core_clr_enabled ())
12515                                                         ensure_method_is_allowed_to_call_method (cfg, method, ctor_method);
12516
12517                                                 if (!(cmethod->flags & METHOD_ATTRIBUTE_STATIC)) {
12518                                                         /*LAME IMPL: We must not add a null check for virtual invoke delegates.*/
12519                                                         if (mono_method_signature (invoke)->param_count == mono_method_signature (cmethod)->param_count) {
12520                                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, target_ins->dreg, 0);
12521                                                                 MONO_EMIT_NEW_COND_EXC (cfg, EQ, "ArgumentException");
12522                                                         }
12523                                                 }
12524
12525                                                 /* FIXME: SGEN support */
12526                                                 if (invoke_context_used == 0 || cfg->llvm_only) {
12527                                                         ip += 6;
12528                                                         if (cfg->verbose_level > 3)
12529                                                                 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));
12530                                                         if ((handle_ins = handle_delegate_ctor (cfg, ctor_method->klass, target_ins, cmethod, context_used, FALSE))) {
12531                                                                 sp --;
12532                                                                 *sp = handle_ins;
12533                                                                 CHECK_CFG_EXCEPTION;
12534                                                                 ip += 5;
12535                                                                 sp ++;
12536                                                                 break;
12537                                                         }
12538                                                         ip -= 6;
12539                                                 }
12540                                         }
12541                                 }
12542
12543                                 argconst = emit_get_rgctx_method (cfg, context_used, cmethod, MONO_RGCTX_INFO_METHOD);
12544                                 ins = mono_emit_jit_icall (cfg, mono_ldftn, &argconst);
12545                                 *sp++ = ins;
12546                                 
12547                                 ip += 6;
12548                                 inline_costs += 10 * num_calls++;
12549                                 break;
12550                         }
12551                         case CEE_LDVIRTFTN: {
12552                                 MonoInst *args [2];
12553
12554                                 CHECK_STACK (1);
12555                                 CHECK_OPSIZE (6);
12556                                 n = read32 (ip + 2);
12557                                 cmethod = mini_get_method (cfg, method, n, NULL, generic_context);
12558                                 CHECK_CFG_ERROR;
12559
12560                                 mono_class_init (cmethod->klass);
12561  
12562                                 context_used = mini_method_check_context_used (cfg, cmethod);
12563
12564                                 if (mono_security_core_clr_enabled ())
12565                                         ensure_method_is_allowed_to_call_method (cfg, method, cmethod);
12566
12567                                 /*
12568                                  * Optimize the common case of ldvirtftn+delegate creation
12569                                  */
12570                                 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)) {
12571                                         MonoMethod *ctor_method = mini_get_method (cfg, method, read32 (ip + 7), NULL, generic_context);
12572                                         if (ctor_method && (ctor_method->klass->parent == mono_defaults.multicastdelegate_class)) {
12573                                                 MonoInst *target_ins, *handle_ins;
12574                                                 MonoMethod *invoke;
12575                                                 int invoke_context_used;
12576                                                 gboolean is_virtual = cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL;
12577
12578                                                 invoke = mono_get_delegate_invoke (ctor_method->klass);
12579                                                 if (!invoke || !mono_method_signature (invoke))
12580                                                         LOAD_ERROR;
12581
12582                                                 invoke_context_used = mini_method_check_context_used (cfg, invoke);
12583
12584                                                 target_ins = sp [-1];
12585
12586                                                 if (mono_security_core_clr_enabled ())
12587                                                         ensure_method_is_allowed_to_call_method (cfg, method, ctor_method);
12588
12589                                                 /* FIXME: SGEN support */
12590                                                 if (invoke_context_used == 0 || cfg->llvm_only) {
12591                                                         ip += 6;
12592                                                         if (cfg->verbose_level > 3)
12593                                                                 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));
12594                                                         if ((handle_ins = handle_delegate_ctor (cfg, ctor_method->klass, target_ins, cmethod, context_used, is_virtual))) {
12595                                                                 sp -= 2;
12596                                                                 *sp = handle_ins;
12597                                                                 CHECK_CFG_EXCEPTION;
12598                                                                 ip += 5;
12599                                                                 sp ++;
12600                                                                 break;
12601                                                         }
12602                                                         ip -= 6;
12603                                                 }
12604                                         }
12605                                 }
12606
12607                                 --sp;
12608                                 args [0] = *sp;
12609
12610                                 args [1] = emit_get_rgctx_method (cfg, context_used,
12611                                                                                                   cmethod, MONO_RGCTX_INFO_METHOD);
12612
12613                                 if (context_used)
12614                                         *sp++ = mono_emit_jit_icall (cfg, mono_ldvirtfn_gshared, args);
12615                                 else
12616                                         *sp++ = mono_emit_jit_icall (cfg, mono_ldvirtfn, args);
12617
12618                                 ip += 6;
12619                                 inline_costs += 10 * num_calls++;
12620                                 break;
12621                         }
12622                         case CEE_LDARG:
12623                                 CHECK_STACK_OVF (1);
12624                                 CHECK_OPSIZE (4);
12625                                 n = read16 (ip + 2);
12626                                 CHECK_ARG (n);
12627                                 EMIT_NEW_ARGLOAD (cfg, ins, n);
12628                                 *sp++ = ins;
12629                                 ip += 4;
12630                                 break;
12631                         case CEE_LDARGA:
12632                                 CHECK_STACK_OVF (1);
12633                                 CHECK_OPSIZE (4);
12634                                 n = read16 (ip + 2);
12635                                 CHECK_ARG (n);
12636                                 NEW_ARGLOADA (cfg, ins, n);
12637                                 MONO_ADD_INS (cfg->cbb, ins);
12638                                 *sp++ = ins;
12639                                 ip += 4;
12640                                 break;
12641                         case CEE_STARG:
12642                                 CHECK_STACK (1);
12643                                 --sp;
12644                                 CHECK_OPSIZE (4);
12645                                 n = read16 (ip + 2);
12646                                 CHECK_ARG (n);
12647                                 if (!dont_verify_stloc && target_type_is_incompatible (cfg, param_types [n], *sp))
12648                                         UNVERIFIED;
12649                                 EMIT_NEW_ARGSTORE (cfg, ins, n, *sp);
12650                                 ip += 4;
12651                                 break;
12652                         case CEE_LDLOC:
12653                                 CHECK_STACK_OVF (1);
12654                                 CHECK_OPSIZE (4);
12655                                 n = read16 (ip + 2);
12656                                 CHECK_LOCAL (n);
12657                                 EMIT_NEW_LOCLOAD (cfg, ins, n);
12658                                 *sp++ = ins;
12659                                 ip += 4;
12660                                 break;
12661                         case CEE_LDLOCA: {
12662                                 unsigned char *tmp_ip;
12663                                 CHECK_STACK_OVF (1);
12664                                 CHECK_OPSIZE (4);
12665                                 n = read16 (ip + 2);
12666                                 CHECK_LOCAL (n);
12667
12668                                 if ((tmp_ip = emit_optimized_ldloca_ir (cfg, ip, end, 2))) {
12669                                         ip = tmp_ip;
12670                                         inline_costs += 1;
12671                                         break;
12672                                 }                       
12673                                 
12674                                 EMIT_NEW_LOCLOADA (cfg, ins, n);
12675                                 *sp++ = ins;
12676                                 ip += 4;
12677                                 break;
12678                         }
12679                         case CEE_STLOC:
12680                                 CHECK_STACK (1);
12681                                 --sp;
12682                                 CHECK_OPSIZE (4);
12683                                 n = read16 (ip + 2);
12684                                 CHECK_LOCAL (n);
12685                                 if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [n], *sp))
12686                                         UNVERIFIED;
12687                                 emit_stloc_ir (cfg, sp, header, n);
12688                                 ip += 4;
12689                                 inline_costs += 1;
12690                                 break;
12691                         case CEE_LOCALLOC: {
12692                                 CHECK_STACK (1);
12693                                 MonoBasicBlock *non_zero_bb, *end_bb;
12694                                 int alloc_ptr = alloc_preg (cfg);
12695                                 --sp;
12696                                 if (sp != stack_start) 
12697                                         UNVERIFIED;
12698                                 if (cfg->method != method) 
12699                                         /* 
12700                                          * Inlining this into a loop in a parent could lead to 
12701                                          * stack overflows which is different behavior than the
12702                                          * non-inlined case, thus disable inlining in this case.
12703                                          */
12704                                         INLINE_FAILURE("localloc");
12705
12706                                 NEW_BBLOCK (cfg, non_zero_bb);
12707                                 NEW_BBLOCK (cfg, end_bb);
12708
12709                                 /* if size != zero */
12710                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, sp [0]->dreg, 0);
12711                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, non_zero_bb);
12712
12713                                 //size is zero, so result is NULL
12714                                 MONO_EMIT_NEW_PCONST (cfg, alloc_ptr, NULL);
12715                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
12716
12717                                 MONO_START_BB (cfg, non_zero_bb);
12718                                 MONO_INST_NEW (cfg, ins, OP_LOCALLOC);
12719                                 ins->dreg = alloc_ptr;
12720                                 ins->sreg1 = sp [0]->dreg;
12721                                 ins->type = STACK_PTR;
12722                                 MONO_ADD_INS (cfg->cbb, ins);
12723
12724                                 cfg->flags |= MONO_CFG_HAS_ALLOCA;
12725                                 if (init_locals)
12726                                         ins->flags |= MONO_INST_INIT;
12727
12728                                 MONO_START_BB (cfg, end_bb);
12729                                 EMIT_NEW_UNALU (cfg, ins, OP_MOVE, alloc_preg (cfg), alloc_ptr);
12730                                 ins->type = STACK_PTR;
12731
12732                                 *sp++ = ins;
12733                                 ip += 2;
12734                                 break;
12735                         }
12736                         case CEE_ENDFILTER: {
12737                                 MonoExceptionClause *clause, *nearest;
12738                                 int cc;
12739
12740                                 CHECK_STACK (1);
12741                                 --sp;
12742                                 if ((sp != stack_start) || (sp [0]->type != STACK_I4)) 
12743                                         UNVERIFIED;
12744                                 MONO_INST_NEW (cfg, ins, OP_ENDFILTER);
12745                                 ins->sreg1 = (*sp)->dreg;
12746                                 MONO_ADD_INS (cfg->cbb, ins);
12747                                 start_new_bblock = 1;
12748                                 ip += 2;
12749
12750                                 nearest = NULL;
12751                                 for (cc = 0; cc < header->num_clauses; ++cc) {
12752                                         clause = &header->clauses [cc];
12753                                         if ((clause->flags & MONO_EXCEPTION_CLAUSE_FILTER) &&
12754                                                 ((ip - header->code) > clause->data.filter_offset && (ip - header->code) <= clause->handler_offset) &&
12755                                             (!nearest || (clause->data.filter_offset < nearest->data.filter_offset)))
12756                                                 nearest = clause;
12757                                 }
12758                                 g_assert (nearest);
12759                                 if ((ip - header->code) != nearest->handler_offset)
12760                                         UNVERIFIED;
12761
12762                                 break;
12763                         }
12764                         case CEE_UNALIGNED_:
12765                                 ins_flag |= MONO_INST_UNALIGNED;
12766                                 /* FIXME: record alignment? we can assume 1 for now */
12767                                 CHECK_OPSIZE (3);
12768                                 ip += 3;
12769                                 break;
12770                         case CEE_VOLATILE_:
12771                                 ins_flag |= MONO_INST_VOLATILE;
12772                                 ip += 2;
12773                                 break;
12774                         case CEE_TAIL_:
12775                                 ins_flag   |= MONO_INST_TAILCALL;
12776                                 cfg->flags |= MONO_CFG_HAS_TAIL;
12777                                 /* Can't inline tail calls at this time */
12778                                 inline_costs += 100000;
12779                                 ip += 2;
12780                                 break;
12781                         case CEE_INITOBJ:
12782                                 CHECK_STACK (1);
12783                                 --sp;
12784                                 CHECK_OPSIZE (6);
12785                                 token = read32 (ip + 2);
12786                                 klass = mini_get_class (method, token, generic_context);
12787                                 CHECK_TYPELOAD (klass);
12788                                 if (generic_class_is_reference_type (cfg, klass))
12789                                         MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STORE_MEMBASE_IMM, sp [0]->dreg, 0, 0);
12790                                 else
12791                                         mini_emit_initobj (cfg, *sp, NULL, klass);
12792                                 ip += 6;
12793                                 inline_costs += 1;
12794                                 break;
12795                         case CEE_CONSTRAINED_:
12796                                 CHECK_OPSIZE (6);
12797                                 token = read32 (ip + 2);
12798                                 constrained_class = mini_get_class (method, token, generic_context);
12799                                 CHECK_TYPELOAD (constrained_class);
12800                                 ip += 6;
12801                                 break;
12802                         case CEE_CPBLK:
12803                         case CEE_INITBLK: {
12804                                 MonoInst *iargs [3];
12805                                 CHECK_STACK (3);
12806                                 sp -= 3;
12807
12808                                 /* Skip optimized paths for volatile operations. */
12809                                 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)) {
12810                                         mini_emit_memcpy (cfg, sp [0]->dreg, 0, sp [1]->dreg, 0, sp [2]->inst_c0, 0);
12811                                 } 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)) {
12812                                         /* emit_memset only works when val == 0 */
12813                                         mini_emit_memset (cfg, sp [0]->dreg, 0, sp [2]->inst_c0, sp [1]->inst_c0, 0);
12814                                 } else {
12815                                         MonoInst *call;
12816                                         iargs [0] = sp [0];
12817                                         iargs [1] = sp [1];
12818                                         iargs [2] = sp [2];
12819                                         if (ip [1] == CEE_CPBLK) {
12820                                                 /*
12821                                                  * FIXME: It's unclear whether we should be emitting both the acquire
12822                                                  * and release barriers for cpblk. It is technically both a load and
12823                                                  * store operation, so it seems like that's the sensible thing to do.
12824                                                  *
12825                                                  * FIXME: We emit full barriers on both sides of the operation for
12826                                                  * simplicity. We should have a separate atomic memcpy method instead.
12827                                                  */
12828                                                 MonoMethod *memcpy_method = get_memcpy_method ();
12829
12830                                                 if (ins_flag & MONO_INST_VOLATILE)
12831                                                         emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
12832
12833                                                 call = mono_emit_method_call (cfg, memcpy_method, iargs, NULL);
12834                                                 call->flags |= ins_flag;
12835
12836                                                 if (ins_flag & MONO_INST_VOLATILE)
12837                                                         emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
12838                                         } else {
12839                                                 MonoMethod *memset_method = get_memset_method ();
12840                                                 if (ins_flag & MONO_INST_VOLATILE) {
12841                                                         /* Volatile stores have release semantics, see 12.6.7 in Ecma 335 */
12842                                                         emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_REL);
12843                                                 }
12844                                                 call = mono_emit_method_call (cfg, memset_method, iargs, NULL);
12845                                                 call->flags |= ins_flag;
12846                                         }
12847                                 }
12848                                 ip += 2;
12849                                 ins_flag = 0;
12850                                 inline_costs += 1;
12851                                 break;
12852                         }
12853                         case CEE_NO_:
12854                                 CHECK_OPSIZE (3);
12855                                 if (ip [2] & 0x1)
12856                                         ins_flag |= MONO_INST_NOTYPECHECK;
12857                                 if (ip [2] & 0x2)
12858                                         ins_flag |= MONO_INST_NORANGECHECK;
12859                                 /* we ignore the no-nullcheck for now since we
12860                                  * really do it explicitly only when doing callvirt->call
12861                                  */
12862                                 ip += 3;
12863                                 break;
12864                         case CEE_RETHROW: {
12865                                 MonoInst *load;
12866                                 int handler_offset = -1;
12867
12868                                 for (i = 0; i < header->num_clauses; ++i) {
12869                                         MonoExceptionClause *clause = &header->clauses [i];
12870                                         if (MONO_OFFSET_IN_HANDLER (clause, ip - header->code) && !(clause->flags & MONO_EXCEPTION_CLAUSE_FINALLY)) {
12871                                                 handler_offset = clause->handler_offset;
12872                                                 break;
12873                                         }
12874                                 }
12875
12876                                 cfg->cbb->flags |= BB_EXCEPTION_UNSAFE;
12877
12878                                 if (handler_offset == -1)
12879                                         UNVERIFIED;
12880
12881                                 EMIT_NEW_TEMPLOAD (cfg, load, mono_find_exvar_for_offset (cfg, handler_offset)->inst_c0);
12882                                 MONO_INST_NEW (cfg, ins, OP_RETHROW);
12883                                 ins->sreg1 = load->dreg;
12884                                 MONO_ADD_INS (cfg->cbb, ins);
12885
12886                                 MONO_INST_NEW (cfg, ins, OP_NOT_REACHED);
12887                                 MONO_ADD_INS (cfg->cbb, ins);
12888
12889                                 sp = stack_start;
12890                                 link_bblock (cfg, cfg->cbb, end_bblock);
12891                                 start_new_bblock = 1;
12892                                 ip += 2;
12893                                 break;
12894                         }
12895                         case CEE_SIZEOF: {
12896                                 guint32 val;
12897                                 int ialign;
12898
12899                                 CHECK_STACK_OVF (1);
12900                                 CHECK_OPSIZE (6);
12901                                 token = read32 (ip + 2);
12902                                 if (mono_metadata_token_table (token) == MONO_TABLE_TYPESPEC && !image_is_dynamic (method->klass->image) && !generic_context) {
12903                                         MonoType *type = mono_type_create_from_typespec_checked (image, token, &cfg->error);
12904                                         CHECK_CFG_ERROR;
12905
12906                                         val = mono_type_size (type, &ialign);
12907                                 } else {
12908                                         MonoClass *klass = mini_get_class (method, token, generic_context);
12909                                         CHECK_TYPELOAD (klass);
12910
12911                                         val = mono_type_size (&klass->byval_arg, &ialign);
12912
12913                                         if (mini_is_gsharedvt_klass (klass))
12914                                                 GSHAREDVT_FAILURE (*ip);
12915                                 }
12916                                 EMIT_NEW_ICONST (cfg, ins, val);
12917                                 *sp++= ins;
12918                                 ip += 6;
12919                                 break;
12920                         }
12921                         case CEE_REFANYTYPE: {
12922                                 MonoInst *src_var, *src;
12923
12924                                 GSHAREDVT_FAILURE (*ip);
12925
12926                                 CHECK_STACK (1);
12927                                 --sp;
12928
12929                                 // FIXME:
12930                                 src_var = get_vreg_to_inst (cfg, sp [0]->dreg);
12931                                 if (!src_var)
12932                                         src_var = mono_compile_create_var_for_vreg (cfg, &mono_defaults.typed_reference_class->byval_arg, OP_LOCAL, sp [0]->dreg);
12933                                 EMIT_NEW_VARLOADA (cfg, src, src_var, src_var->inst_vtype);
12934                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &mono_defaults.typehandle_class->byval_arg, src->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, type));
12935                                 *sp++ = ins;
12936                                 ip += 2;
12937                                 break;
12938                         }
12939                         case CEE_READONLY_:
12940                                 readonly = TRUE;
12941                                 ip += 2;
12942                                 break;
12943
12944                         case CEE_UNUSED56:
12945                         case CEE_UNUSED57:
12946                         case CEE_UNUSED70:
12947                         case CEE_UNUSED:
12948                         case CEE_UNUSED99:
12949                                 UNVERIFIED;
12950                                 
12951                         default:
12952                                 g_warning ("opcode 0xfe 0x%02x not handled", ip [1]);
12953                                 UNVERIFIED;
12954                         }
12955                         break;
12956                 }
12957                 case CEE_UNUSED58:
12958                 case CEE_UNUSED1:
12959                         UNVERIFIED;
12960
12961                 default:
12962                         g_warning ("opcode 0x%02x not handled", *ip);
12963                         UNVERIFIED;
12964                 }
12965         }
12966         if (start_new_bblock != 1)
12967                 UNVERIFIED;
12968
12969         cfg->cbb->cil_length = ip - cfg->cbb->cil_code;
12970         if (cfg->cbb->next_bb) {
12971                 /* This could already be set because of inlining, #693905 */
12972                 MonoBasicBlock *bb = cfg->cbb;
12973
12974                 while (bb->next_bb)
12975                         bb = bb->next_bb;
12976                 bb->next_bb = end_bblock;
12977         } else {
12978                 cfg->cbb->next_bb = end_bblock;
12979         }
12980
12981         if (cfg->method == method && cfg->domainvar) {
12982                 MonoInst *store;
12983                 MonoInst *get_domain;
12984
12985                 cfg->cbb = init_localsbb;
12986
12987                 get_domain = mono_create_tls_get (cfg, TLS_KEY_DOMAIN);
12988                 NEW_TEMPSTORE (cfg, store, cfg->domainvar->inst_c0, get_domain);
12989                 MONO_ADD_INS (cfg->cbb, store);
12990         }
12991
12992 #if defined(TARGET_POWERPC) || defined(TARGET_X86)
12993         if (cfg->compile_aot)
12994                 /* FIXME: The plt slots require a GOT var even if the method doesn't use it */
12995                 mono_get_got_var (cfg);
12996 #endif
12997
12998         if (cfg->method == method && cfg->got_var)
12999                 mono_emit_load_got_addr (cfg);
13000
13001         if (init_localsbb) {
13002                 cfg->cbb = init_localsbb;
13003                 cfg->ip = NULL;
13004                 for (i = 0; i < header->num_locals; ++i) {
13005                         emit_init_local (cfg, i, header->locals [i], init_locals);
13006                 }
13007         }
13008
13009         if (cfg->init_ref_vars && cfg->method == method) {
13010                 /* Emit initialization for ref vars */
13011                 // FIXME: Avoid duplication initialization for IL locals.
13012                 for (i = 0; i < cfg->num_varinfo; ++i) {
13013                         MonoInst *ins = cfg->varinfo [i];
13014
13015                         if (ins->opcode == OP_LOCAL && ins->type == STACK_OBJ)
13016                                 MONO_EMIT_NEW_PCONST (cfg, ins->dreg, NULL);
13017                 }
13018         }
13019
13020         if (cfg->lmf_var && cfg->method == method && !cfg->llvm_only) {
13021                 cfg->cbb = init_localsbb;
13022                 emit_push_lmf (cfg);
13023         }
13024
13025         cfg->cbb = init_localsbb;
13026         emit_instrumentation_call (cfg, mono_profiler_method_enter);
13027
13028         if (seq_points) {
13029                 MonoBasicBlock *bb;
13030
13031                 /*
13032                  * Make seq points at backward branch targets interruptable.
13033                  */
13034                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
13035                         if (bb->code && bb->in_count > 1 && bb->code->opcode == OP_SEQ_POINT)
13036                                 bb->code->flags |= MONO_INST_SINGLE_STEP_LOC;
13037         }
13038
13039         /* Add a sequence point for method entry/exit events */
13040         if (seq_points && cfg->gen_sdb_seq_points) {
13041                 NEW_SEQ_POINT (cfg, ins, METHOD_ENTRY_IL_OFFSET, FALSE);
13042                 MONO_ADD_INS (init_localsbb, ins);
13043                 NEW_SEQ_POINT (cfg, ins, METHOD_EXIT_IL_OFFSET, FALSE);
13044                 MONO_ADD_INS (cfg->bb_exit, ins);
13045         }
13046
13047         /*
13048          * Add seq points for IL offsets which have line number info, but wasn't generated a seq point during JITting because
13049          * the code they refer to was dead (#11880).
13050          */
13051         if (sym_seq_points) {
13052                 for (i = 0; i < header->code_size; ++i) {
13053                         if (mono_bitset_test_fast (seq_point_locs, i) && !mono_bitset_test_fast (seq_point_set_locs, i)) {
13054                                 MonoInst *ins;
13055
13056                                 NEW_SEQ_POINT (cfg, ins, i, FALSE);
13057                                 mono_add_seq_point (cfg, NULL, ins, SEQ_POINT_NATIVE_OFFSET_DEAD_CODE);
13058                         }
13059                 }
13060         }
13061
13062         cfg->ip = NULL;
13063
13064         if (cfg->method == method) {
13065                 MonoBasicBlock *bb;
13066                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
13067                         if (bb == cfg->bb_init)
13068                                 bb->region = -1;
13069                         else
13070                                 bb->region = mono_find_block_region (cfg, bb->real_offset);
13071                         if (cfg->spvars)
13072                                 mono_create_spvar_for_region (cfg, bb->region);
13073                         if (cfg->verbose_level > 2)
13074                                 printf ("REGION BB%d IL_%04x ID_%08X\n", bb->block_num, bb->real_offset, bb->region);
13075                 }
13076         } else {
13077                 MonoBasicBlock *bb;
13078                 /* get_most_deep_clause () in mini-llvm.c depends on this for inlined bblocks */
13079                 for (bb = start_bblock; bb != end_bblock; bb  = bb->next_bb) {
13080                         bb->real_offset = inline_offset;
13081                 }
13082         }
13083
13084         if (inline_costs < 0) {
13085                 char *mname;
13086
13087                 /* Method is too large */
13088                 mname = mono_method_full_name (method, TRUE);
13089                 mono_cfg_set_exception_invalid_program (cfg, g_strdup_printf ("Method %s is too complex.", mname));
13090                 g_free (mname);
13091         }
13092
13093         if ((cfg->verbose_level > 2) && (cfg->method == method)) 
13094                 mono_print_code (cfg, "AFTER METHOD-TO-IR");
13095
13096         goto cleanup;
13097
13098 mono_error_exit:
13099         g_assert (!mono_error_ok (&cfg->error));
13100         goto cleanup;
13101  
13102  exception_exit:
13103         g_assert (cfg->exception_type != MONO_EXCEPTION_NONE);
13104         goto cleanup;
13105
13106  unverified:
13107         set_exception_type_from_invalid_il (cfg, method, ip);
13108         goto cleanup;
13109
13110  cleanup:
13111         g_slist_free (class_inits);
13112         mono_basic_block_free (original_bb);
13113         cfg->dont_inline = g_list_remove (cfg->dont_inline, method);
13114         if (cfg->exception_type)
13115                 return -1;
13116         else
13117                 return inline_costs;
13118 }
13119
13120 static int
13121 store_membase_reg_to_store_membase_imm (int opcode)
13122 {
13123         switch (opcode) {
13124         case OP_STORE_MEMBASE_REG:
13125                 return OP_STORE_MEMBASE_IMM;
13126         case OP_STOREI1_MEMBASE_REG:
13127                 return OP_STOREI1_MEMBASE_IMM;
13128         case OP_STOREI2_MEMBASE_REG:
13129                 return OP_STOREI2_MEMBASE_IMM;
13130         case OP_STOREI4_MEMBASE_REG:
13131                 return OP_STOREI4_MEMBASE_IMM;
13132         case OP_STOREI8_MEMBASE_REG:
13133                 return OP_STOREI8_MEMBASE_IMM;
13134         default:
13135                 g_assert_not_reached ();
13136         }
13137
13138         return -1;
13139 }               
13140
13141 int
13142 mono_op_to_op_imm (int opcode)
13143 {
13144         switch (opcode) {
13145         case OP_IADD:
13146                 return OP_IADD_IMM;
13147         case OP_ISUB:
13148                 return OP_ISUB_IMM;
13149         case OP_IDIV:
13150                 return OP_IDIV_IMM;
13151         case OP_IDIV_UN:
13152                 return OP_IDIV_UN_IMM;
13153         case OP_IREM:
13154                 return OP_IREM_IMM;
13155         case OP_IREM_UN:
13156                 return OP_IREM_UN_IMM;
13157         case OP_IMUL:
13158                 return OP_IMUL_IMM;
13159         case OP_IAND:
13160                 return OP_IAND_IMM;
13161         case OP_IOR:
13162                 return OP_IOR_IMM;
13163         case OP_IXOR:
13164                 return OP_IXOR_IMM;
13165         case OP_ISHL:
13166                 return OP_ISHL_IMM;
13167         case OP_ISHR:
13168                 return OP_ISHR_IMM;
13169         case OP_ISHR_UN:
13170                 return OP_ISHR_UN_IMM;
13171
13172         case OP_LADD:
13173                 return OP_LADD_IMM;
13174         case OP_LSUB:
13175                 return OP_LSUB_IMM;
13176         case OP_LAND:
13177                 return OP_LAND_IMM;
13178         case OP_LOR:
13179                 return OP_LOR_IMM;
13180         case OP_LXOR:
13181                 return OP_LXOR_IMM;
13182         case OP_LSHL:
13183                 return OP_LSHL_IMM;
13184         case OP_LSHR:
13185                 return OP_LSHR_IMM;
13186         case OP_LSHR_UN:
13187                 return OP_LSHR_UN_IMM;
13188 #if SIZEOF_REGISTER == 8
13189         case OP_LREM:
13190                 return OP_LREM_IMM;
13191 #endif
13192
13193         case OP_COMPARE:
13194                 return OP_COMPARE_IMM;
13195         case OP_ICOMPARE:
13196                 return OP_ICOMPARE_IMM;
13197         case OP_LCOMPARE:
13198                 return OP_LCOMPARE_IMM;
13199
13200         case OP_STORE_MEMBASE_REG:
13201                 return OP_STORE_MEMBASE_IMM;
13202         case OP_STOREI1_MEMBASE_REG:
13203                 return OP_STOREI1_MEMBASE_IMM;
13204         case OP_STOREI2_MEMBASE_REG:
13205                 return OP_STOREI2_MEMBASE_IMM;
13206         case OP_STOREI4_MEMBASE_REG:
13207                 return OP_STOREI4_MEMBASE_IMM;
13208
13209 #if defined(TARGET_X86) || defined (TARGET_AMD64)
13210         case OP_X86_PUSH:
13211                 return OP_X86_PUSH_IMM;
13212         case OP_X86_COMPARE_MEMBASE_REG:
13213                 return OP_X86_COMPARE_MEMBASE_IMM;
13214 #endif
13215 #if defined(TARGET_AMD64)
13216         case OP_AMD64_ICOMPARE_MEMBASE_REG:
13217                 return OP_AMD64_ICOMPARE_MEMBASE_IMM;
13218 #endif
13219         case OP_VOIDCALL_REG:
13220                 return OP_VOIDCALL;
13221         case OP_CALL_REG:
13222                 return OP_CALL;
13223         case OP_LCALL_REG:
13224                 return OP_LCALL;
13225         case OP_FCALL_REG:
13226                 return OP_FCALL;
13227         case OP_LOCALLOC:
13228                 return OP_LOCALLOC_IMM;
13229         }
13230
13231         return -1;
13232 }
13233
13234 static int
13235 ldind_to_load_membase (int opcode)
13236 {
13237         switch (opcode) {
13238         case CEE_LDIND_I1:
13239                 return OP_LOADI1_MEMBASE;
13240         case CEE_LDIND_U1:
13241                 return OP_LOADU1_MEMBASE;
13242         case CEE_LDIND_I2:
13243                 return OP_LOADI2_MEMBASE;
13244         case CEE_LDIND_U2:
13245                 return OP_LOADU2_MEMBASE;
13246         case CEE_LDIND_I4:
13247                 return OP_LOADI4_MEMBASE;
13248         case CEE_LDIND_U4:
13249                 return OP_LOADU4_MEMBASE;
13250         case CEE_LDIND_I:
13251                 return OP_LOAD_MEMBASE;
13252         case CEE_LDIND_REF:
13253                 return OP_LOAD_MEMBASE;
13254         case CEE_LDIND_I8:
13255                 return OP_LOADI8_MEMBASE;
13256         case CEE_LDIND_R4:
13257                 return OP_LOADR4_MEMBASE;
13258         case CEE_LDIND_R8:
13259                 return OP_LOADR8_MEMBASE;
13260         default:
13261                 g_assert_not_reached ();
13262         }
13263
13264         return -1;
13265 }
13266
13267 static int
13268 stind_to_store_membase (int opcode)
13269 {
13270         switch (opcode) {
13271         case CEE_STIND_I1:
13272                 return OP_STOREI1_MEMBASE_REG;
13273         case CEE_STIND_I2:
13274                 return OP_STOREI2_MEMBASE_REG;
13275         case CEE_STIND_I4:
13276                 return OP_STOREI4_MEMBASE_REG;
13277         case CEE_STIND_I:
13278         case CEE_STIND_REF:
13279                 return OP_STORE_MEMBASE_REG;
13280         case CEE_STIND_I8:
13281                 return OP_STOREI8_MEMBASE_REG;
13282         case CEE_STIND_R4:
13283                 return OP_STORER4_MEMBASE_REG;
13284         case CEE_STIND_R8:
13285                 return OP_STORER8_MEMBASE_REG;
13286         default:
13287                 g_assert_not_reached ();
13288         }
13289
13290         return -1;
13291 }
13292
13293 int
13294 mono_load_membase_to_load_mem (int opcode)
13295 {
13296         // FIXME: Add a MONO_ARCH_HAVE_LOAD_MEM macro
13297 #if defined(TARGET_X86) || defined(TARGET_AMD64)
13298         switch (opcode) {
13299         case OP_LOAD_MEMBASE:
13300                 return OP_LOAD_MEM;
13301         case OP_LOADU1_MEMBASE:
13302                 return OP_LOADU1_MEM;
13303         case OP_LOADU2_MEMBASE:
13304                 return OP_LOADU2_MEM;
13305         case OP_LOADI4_MEMBASE:
13306                 return OP_LOADI4_MEM;
13307         case OP_LOADU4_MEMBASE:
13308                 return OP_LOADU4_MEM;
13309 #if SIZEOF_REGISTER == 8
13310         case OP_LOADI8_MEMBASE:
13311                 return OP_LOADI8_MEM;
13312 #endif
13313         }
13314 #endif
13315
13316         return -1;
13317 }
13318
13319 static inline int
13320 op_to_op_dest_membase (int store_opcode, int opcode)
13321 {
13322 #if defined(TARGET_X86)
13323         if (!((store_opcode == OP_STORE_MEMBASE_REG) || (store_opcode == OP_STOREI4_MEMBASE_REG)))
13324                 return -1;
13325
13326         switch (opcode) {
13327         case OP_IADD:
13328                 return OP_X86_ADD_MEMBASE_REG;
13329         case OP_ISUB:
13330                 return OP_X86_SUB_MEMBASE_REG;
13331         case OP_IAND:
13332                 return OP_X86_AND_MEMBASE_REG;
13333         case OP_IOR:
13334                 return OP_X86_OR_MEMBASE_REG;
13335         case OP_IXOR:
13336                 return OP_X86_XOR_MEMBASE_REG;
13337         case OP_ADD_IMM:
13338         case OP_IADD_IMM:
13339                 return OP_X86_ADD_MEMBASE_IMM;
13340         case OP_SUB_IMM:
13341         case OP_ISUB_IMM:
13342                 return OP_X86_SUB_MEMBASE_IMM;
13343         case OP_AND_IMM:
13344         case OP_IAND_IMM:
13345                 return OP_X86_AND_MEMBASE_IMM;
13346         case OP_OR_IMM:
13347         case OP_IOR_IMM:
13348                 return OP_X86_OR_MEMBASE_IMM;
13349         case OP_XOR_IMM:
13350         case OP_IXOR_IMM:
13351                 return OP_X86_XOR_MEMBASE_IMM;
13352         case OP_MOVE:
13353                 return OP_NOP;
13354         }
13355 #endif
13356
13357 #if defined(TARGET_AMD64)
13358         if (!((store_opcode == OP_STORE_MEMBASE_REG) || (store_opcode == OP_STOREI4_MEMBASE_REG) || (store_opcode == OP_STOREI8_MEMBASE_REG)))
13359                 return -1;
13360
13361         switch (opcode) {
13362         case OP_IADD:
13363                 return OP_X86_ADD_MEMBASE_REG;
13364         case OP_ISUB:
13365                 return OP_X86_SUB_MEMBASE_REG;
13366         case OP_IAND:
13367                 return OP_X86_AND_MEMBASE_REG;
13368         case OP_IOR:
13369                 return OP_X86_OR_MEMBASE_REG;
13370         case OP_IXOR:
13371                 return OP_X86_XOR_MEMBASE_REG;
13372         case OP_IADD_IMM:
13373                 return OP_X86_ADD_MEMBASE_IMM;
13374         case OP_ISUB_IMM:
13375                 return OP_X86_SUB_MEMBASE_IMM;
13376         case OP_IAND_IMM:
13377                 return OP_X86_AND_MEMBASE_IMM;
13378         case OP_IOR_IMM:
13379                 return OP_X86_OR_MEMBASE_IMM;
13380         case OP_IXOR_IMM:
13381                 return OP_X86_XOR_MEMBASE_IMM;
13382         case OP_LADD:
13383                 return OP_AMD64_ADD_MEMBASE_REG;
13384         case OP_LSUB:
13385                 return OP_AMD64_SUB_MEMBASE_REG;
13386         case OP_LAND:
13387                 return OP_AMD64_AND_MEMBASE_REG;
13388         case OP_LOR:
13389                 return OP_AMD64_OR_MEMBASE_REG;
13390         case OP_LXOR:
13391                 return OP_AMD64_XOR_MEMBASE_REG;
13392         case OP_ADD_IMM:
13393         case OP_LADD_IMM:
13394                 return OP_AMD64_ADD_MEMBASE_IMM;
13395         case OP_SUB_IMM:
13396         case OP_LSUB_IMM:
13397                 return OP_AMD64_SUB_MEMBASE_IMM;
13398         case OP_AND_IMM:
13399         case OP_LAND_IMM:
13400                 return OP_AMD64_AND_MEMBASE_IMM;
13401         case OP_OR_IMM:
13402         case OP_LOR_IMM:
13403                 return OP_AMD64_OR_MEMBASE_IMM;
13404         case OP_XOR_IMM:
13405         case OP_LXOR_IMM:
13406                 return OP_AMD64_XOR_MEMBASE_IMM;
13407         case OP_MOVE:
13408                 return OP_NOP;
13409         }
13410 #endif
13411
13412         return -1;
13413 }
13414
13415 static inline int
13416 op_to_op_store_membase (int store_opcode, int opcode)
13417 {
13418 #if defined(TARGET_X86) || defined(TARGET_AMD64)
13419         switch (opcode) {
13420         case OP_ICEQ:
13421                 if (store_opcode == OP_STOREI1_MEMBASE_REG)
13422                         return OP_X86_SETEQ_MEMBASE;
13423         case OP_CNE:
13424                 if (store_opcode == OP_STOREI1_MEMBASE_REG)
13425                         return OP_X86_SETNE_MEMBASE;
13426         }
13427 #endif
13428
13429         return -1;
13430 }
13431
13432 static inline int
13433 op_to_op_src1_membase (MonoCompile *cfg, int load_opcode, int opcode)
13434 {
13435 #ifdef TARGET_X86
13436         /* FIXME: This has sign extension issues */
13437         /*
13438         if ((opcode == OP_ICOMPARE_IMM) && (load_opcode == OP_LOADU1_MEMBASE))
13439                 return OP_X86_COMPARE_MEMBASE8_IMM;
13440         */
13441
13442         if (!((load_opcode == OP_LOAD_MEMBASE) || (load_opcode == OP_LOADI4_MEMBASE) || (load_opcode == OP_LOADU4_MEMBASE)))
13443                 return -1;
13444
13445         switch (opcode) {
13446         case OP_X86_PUSH:
13447                 return OP_X86_PUSH_MEMBASE;
13448         case OP_COMPARE_IMM:
13449         case OP_ICOMPARE_IMM:
13450                 return OP_X86_COMPARE_MEMBASE_IMM;
13451         case OP_COMPARE:
13452         case OP_ICOMPARE:
13453                 return OP_X86_COMPARE_MEMBASE_REG;
13454         }
13455 #endif
13456
13457 #ifdef TARGET_AMD64
13458         /* FIXME: This has sign extension issues */
13459         /*
13460         if ((opcode == OP_ICOMPARE_IMM) && (load_opcode == OP_LOADU1_MEMBASE))
13461                 return OP_X86_COMPARE_MEMBASE8_IMM;
13462         */
13463
13464         switch (opcode) {
13465         case OP_X86_PUSH:
13466                 if ((load_opcode == OP_LOAD_MEMBASE && !cfg->backend->ilp32) || (load_opcode == OP_LOADI8_MEMBASE))
13467                         return OP_X86_PUSH_MEMBASE;
13468                 break;
13469                 /* FIXME: This only works for 32 bit immediates
13470         case OP_COMPARE_IMM:
13471         case OP_LCOMPARE_IMM:
13472                 if ((load_opcode == OP_LOAD_MEMBASE) || (load_opcode == OP_LOADI8_MEMBASE))
13473                         return OP_AMD64_COMPARE_MEMBASE_IMM;
13474                 */
13475         case OP_ICOMPARE_IMM:
13476                 if ((load_opcode == OP_LOADI4_MEMBASE) || (load_opcode == OP_LOADU4_MEMBASE))
13477                         return OP_AMD64_ICOMPARE_MEMBASE_IMM;
13478                 break;
13479         case OP_COMPARE:
13480         case OP_LCOMPARE:
13481                 if (cfg->backend->ilp32 && load_opcode == OP_LOAD_MEMBASE)
13482                         return OP_AMD64_ICOMPARE_MEMBASE_REG;
13483                 if ((load_opcode == OP_LOAD_MEMBASE && !cfg->backend->ilp32) || (load_opcode == OP_LOADI8_MEMBASE))
13484                         return OP_AMD64_COMPARE_MEMBASE_REG;
13485                 break;
13486         case OP_ICOMPARE:
13487                 if ((load_opcode == OP_LOADI4_MEMBASE) || (load_opcode == OP_LOADU4_MEMBASE))
13488                         return OP_AMD64_ICOMPARE_MEMBASE_REG;
13489                 break;
13490         }
13491 #endif
13492
13493         return -1;
13494 }
13495
13496 static inline int
13497 op_to_op_src2_membase (MonoCompile *cfg, int load_opcode, int opcode)
13498 {
13499 #ifdef TARGET_X86
13500         if (!((load_opcode == OP_LOAD_MEMBASE) || (load_opcode == OP_LOADI4_MEMBASE) || (load_opcode == OP_LOADU4_MEMBASE)))
13501                 return -1;
13502         
13503         switch (opcode) {
13504         case OP_COMPARE:
13505         case OP_ICOMPARE:
13506                 return OP_X86_COMPARE_REG_MEMBASE;
13507         case OP_IADD:
13508                 return OP_X86_ADD_REG_MEMBASE;
13509         case OP_ISUB:
13510                 return OP_X86_SUB_REG_MEMBASE;
13511         case OP_IAND:
13512                 return OP_X86_AND_REG_MEMBASE;
13513         case OP_IOR:
13514                 return OP_X86_OR_REG_MEMBASE;
13515         case OP_IXOR:
13516                 return OP_X86_XOR_REG_MEMBASE;
13517         }
13518 #endif
13519
13520 #ifdef TARGET_AMD64
13521         if ((load_opcode == OP_LOADI4_MEMBASE) || (load_opcode == OP_LOADU4_MEMBASE) || (load_opcode == OP_LOAD_MEMBASE && cfg->backend->ilp32)) {
13522                 switch (opcode) {
13523                 case OP_ICOMPARE:
13524                         return OP_AMD64_ICOMPARE_REG_MEMBASE;
13525                 case OP_IADD:
13526                         return OP_X86_ADD_REG_MEMBASE;
13527                 case OP_ISUB:
13528                         return OP_X86_SUB_REG_MEMBASE;
13529                 case OP_IAND:
13530                         return OP_X86_AND_REG_MEMBASE;
13531                 case OP_IOR:
13532                         return OP_X86_OR_REG_MEMBASE;
13533                 case OP_IXOR:
13534                         return OP_X86_XOR_REG_MEMBASE;
13535                 }
13536         } else if ((load_opcode == OP_LOADI8_MEMBASE) || (load_opcode == OP_LOAD_MEMBASE && !cfg->backend->ilp32)) {
13537                 switch (opcode) {
13538                 case OP_COMPARE:
13539                 case OP_LCOMPARE:
13540                         return OP_AMD64_COMPARE_REG_MEMBASE;
13541                 case OP_LADD:
13542                         return OP_AMD64_ADD_REG_MEMBASE;
13543                 case OP_LSUB:
13544                         return OP_AMD64_SUB_REG_MEMBASE;
13545                 case OP_LAND:
13546                         return OP_AMD64_AND_REG_MEMBASE;
13547                 case OP_LOR:
13548                         return OP_AMD64_OR_REG_MEMBASE;
13549                 case OP_LXOR:
13550                         return OP_AMD64_XOR_REG_MEMBASE;
13551                 }
13552         }
13553 #endif
13554
13555         return -1;
13556 }
13557
13558 int
13559 mono_op_to_op_imm_noemul (int opcode)
13560 {
13561         switch (opcode) {
13562 #if SIZEOF_REGISTER == 4 && !defined(MONO_ARCH_NO_EMULATE_LONG_SHIFT_OPS)
13563         case OP_LSHR:
13564         case OP_LSHL:
13565         case OP_LSHR_UN:
13566                 return -1;
13567 #endif
13568 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_EMULATE_DIV)
13569         case OP_IDIV:
13570         case OP_IDIV_UN:
13571         case OP_IREM:
13572         case OP_IREM_UN:
13573                 return -1;
13574 #endif
13575 #if defined(MONO_ARCH_EMULATE_MUL_DIV)
13576         case OP_IMUL:
13577                 return -1;
13578 #endif
13579         default:
13580                 return mono_op_to_op_imm (opcode);
13581         }
13582 }
13583
13584 /**
13585  * mono_handle_global_vregs:
13586  *
13587  *   Make vregs used in more than one bblock 'global', i.e. allocate a variable
13588  * for them.
13589  */
13590 void
13591 mono_handle_global_vregs (MonoCompile *cfg)
13592 {
13593         gint32 *vreg_to_bb;
13594         MonoBasicBlock *bb;
13595         int i, pos;
13596
13597         vreg_to_bb = (gint32 *)mono_mempool_alloc0 (cfg->mempool, sizeof (gint32*) * cfg->next_vreg + 1);
13598
13599 #ifdef MONO_ARCH_SIMD_INTRINSICS
13600         if (cfg->uses_simd_intrinsics)
13601                 mono_simd_simplify_indirection (cfg);
13602 #endif
13603
13604         /* Find local vregs used in more than one bb */
13605         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
13606                 MonoInst *ins = bb->code;       
13607                 int block_num = bb->block_num;
13608
13609                 if (cfg->verbose_level > 2)
13610                         printf ("\nHANDLE-GLOBAL-VREGS BLOCK %d:\n", bb->block_num);
13611
13612                 cfg->cbb = bb;
13613                 for (; ins; ins = ins->next) {
13614                         const char *spec = INS_INFO (ins->opcode);
13615                         int regtype = 0, regindex;
13616                         gint32 prev_bb;
13617
13618                         if (G_UNLIKELY (cfg->verbose_level > 2))
13619                                 mono_print_ins (ins);
13620
13621                         g_assert (ins->opcode >= MONO_CEE_LAST);
13622
13623                         for (regindex = 0; regindex < 4; regindex ++) {
13624                                 int vreg = 0;
13625
13626                                 if (regindex == 0) {
13627                                         regtype = spec [MONO_INST_DEST];
13628                                         if (regtype == ' ')
13629                                                 continue;
13630                                         vreg = ins->dreg;
13631                                 } else if (regindex == 1) {
13632                                         regtype = spec [MONO_INST_SRC1];
13633                                         if (regtype == ' ')
13634                                                 continue;
13635                                         vreg = ins->sreg1;
13636                                 } else if (regindex == 2) {
13637                                         regtype = spec [MONO_INST_SRC2];
13638                                         if (regtype == ' ')
13639                                                 continue;
13640                                         vreg = ins->sreg2;
13641                                 } else if (regindex == 3) {
13642                                         regtype = spec [MONO_INST_SRC3];
13643                                         if (regtype == ' ')
13644                                                 continue;
13645                                         vreg = ins->sreg3;
13646                                 }
13647
13648 #if SIZEOF_REGISTER == 4
13649                                 /* In the LLVM case, the long opcodes are not decomposed */
13650                                 if (regtype == 'l' && !COMPILE_LLVM (cfg)) {
13651                                         /*
13652                                          * Since some instructions reference the original long vreg,
13653                                          * and some reference the two component vregs, it is quite hard
13654                                          * to determine when it needs to be global. So be conservative.
13655                                          */
13656                                         if (!get_vreg_to_inst (cfg, vreg)) {
13657                                                 mono_compile_create_var_for_vreg (cfg, &mono_defaults.int64_class->byval_arg, OP_LOCAL, vreg);
13658
13659                                                 if (cfg->verbose_level > 2)
13660                                                         printf ("LONG VREG R%d made global.\n", vreg);
13661                                         }
13662
13663                                         /*
13664                                          * Make the component vregs volatile since the optimizations can
13665                                          * get confused otherwise.
13666                                          */
13667                                         get_vreg_to_inst (cfg, MONO_LVREG_LS (vreg))->flags |= MONO_INST_VOLATILE;
13668                                         get_vreg_to_inst (cfg, MONO_LVREG_MS (vreg))->flags |= MONO_INST_VOLATILE;
13669                                 }
13670 #endif
13671
13672                                 g_assert (vreg != -1);
13673
13674                                 prev_bb = vreg_to_bb [vreg];
13675                                 if (prev_bb == 0) {
13676                                         /* 0 is a valid block num */
13677                                         vreg_to_bb [vreg] = block_num + 1;
13678                                 } else if ((prev_bb != block_num + 1) && (prev_bb != -1)) {
13679                                         if (((regtype == 'i' && (vreg < MONO_MAX_IREGS))) || (regtype == 'f' && (vreg < MONO_MAX_FREGS)))
13680                                                 continue;
13681
13682                                         if (!get_vreg_to_inst (cfg, vreg)) {
13683                                                 if (G_UNLIKELY (cfg->verbose_level > 2))
13684                                                         printf ("VREG R%d used in BB%d and BB%d made global.\n", vreg, vreg_to_bb [vreg], block_num);
13685
13686                                                 switch (regtype) {
13687                                                 case 'i':
13688                                                         if (vreg_is_ref (cfg, vreg))
13689                                                                 mono_compile_create_var_for_vreg (cfg, &mono_defaults.object_class->byval_arg, OP_LOCAL, vreg);
13690                                                         else
13691                                                                 mono_compile_create_var_for_vreg (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL, vreg);
13692                                                         break;
13693                                                 case 'l':
13694                                                         mono_compile_create_var_for_vreg (cfg, &mono_defaults.int64_class->byval_arg, OP_LOCAL, vreg);
13695                                                         break;
13696                                                 case 'f':
13697                                                         mono_compile_create_var_for_vreg (cfg, &mono_defaults.double_class->byval_arg, OP_LOCAL, vreg);
13698                                                         break;
13699                                                 case 'v':
13700                                                 case 'x':
13701                                                         mono_compile_create_var_for_vreg (cfg, &ins->klass->byval_arg, OP_LOCAL, vreg);
13702                                                         break;
13703                                                 default:
13704                                                         g_assert_not_reached ();
13705                                                 }
13706                                         }
13707
13708                                         /* Flag as having been used in more than one bb */
13709                                         vreg_to_bb [vreg] = -1;
13710                                 }
13711                         }
13712                 }
13713         }
13714
13715         /* If a variable is used in only one bblock, convert it into a local vreg */
13716         for (i = 0; i < cfg->num_varinfo; i++) {
13717                 MonoInst *var = cfg->varinfo [i];
13718                 MonoMethodVar *vmv = MONO_VARINFO (cfg, i);
13719
13720                 switch (var->type) {
13721                 case STACK_I4:
13722                 case STACK_OBJ:
13723                 case STACK_PTR:
13724                 case STACK_MP:
13725                 case STACK_VTYPE:
13726 #if SIZEOF_REGISTER == 8
13727                 case STACK_I8:
13728 #endif
13729 #if !defined(TARGET_X86)
13730                 /* Enabling this screws up the fp stack on x86 */
13731                 case STACK_R8:
13732 #endif
13733                         if (mono_arch_is_soft_float ())
13734                                 break;
13735
13736                         /*
13737                         if (var->type == STACK_VTYPE && cfg->gsharedvt && mini_is_gsharedvt_variable_type (var->inst_vtype))
13738                                 break;
13739                         */
13740
13741                         /* Arguments are implicitly global */
13742                         /* Putting R4 vars into registers doesn't work currently */
13743                         /* The gsharedvt vars are implicitly referenced by ldaddr opcodes, but those opcodes are only generated later */
13744                         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) {
13745                                 /* 
13746                                  * Make that the variable's liveness interval doesn't contain a call, since
13747                                  * that would cause the lvreg to be spilled, making the whole optimization
13748                                  * useless.
13749                                  */
13750                                 /* This is too slow for JIT compilation */
13751 #if 0
13752                                 if (cfg->compile_aot && vreg_to_bb [var->dreg]) {
13753                                         MonoInst *ins;
13754                                         int def_index, call_index, ins_index;
13755                                         gboolean spilled = FALSE;
13756
13757                                         def_index = -1;
13758                                         call_index = -1;
13759                                         ins_index = 0;
13760                                         for (ins = vreg_to_bb [var->dreg]->code; ins; ins = ins->next) {
13761                                                 const char *spec = INS_INFO (ins->opcode);
13762
13763                                                 if ((spec [MONO_INST_DEST] != ' ') && (ins->dreg == var->dreg))
13764                                                         def_index = ins_index;
13765
13766                                                 if (((spec [MONO_INST_SRC1] != ' ') && (ins->sreg1 == var->dreg)) ||
13767                                                         ((spec [MONO_INST_SRC1] != ' ') && (ins->sreg1 == var->dreg))) {
13768                                                         if (call_index > def_index) {
13769                                                                 spilled = TRUE;
13770                                                                 break;
13771                                                         }
13772                                                 }
13773
13774                                                 if (MONO_IS_CALL (ins))
13775                                                         call_index = ins_index;
13776
13777                                                 ins_index ++;
13778                                         }
13779
13780                                         if (spilled)
13781                                                 break;
13782                                 }
13783 #endif
13784
13785                                 if (G_UNLIKELY (cfg->verbose_level > 2))
13786                                         printf ("CONVERTED R%d(%d) TO VREG.\n", var->dreg, vmv->idx);
13787                                 var->flags |= MONO_INST_IS_DEAD;
13788                                 cfg->vreg_to_inst [var->dreg] = NULL;
13789                         }
13790                         break;
13791                 }
13792         }
13793
13794         /* 
13795          * Compress the varinfo and vars tables so the liveness computation is faster and
13796          * takes up less space.
13797          */
13798         pos = 0;
13799         for (i = 0; i < cfg->num_varinfo; ++i) {
13800                 MonoInst *var = cfg->varinfo [i];
13801                 if (pos < i && cfg->locals_start == i)
13802                         cfg->locals_start = pos;
13803                 if (!(var->flags & MONO_INST_IS_DEAD)) {
13804                         if (pos < i) {
13805                                 cfg->varinfo [pos] = cfg->varinfo [i];
13806                                 cfg->varinfo [pos]->inst_c0 = pos;
13807                                 memcpy (&cfg->vars [pos], &cfg->vars [i], sizeof (MonoMethodVar));
13808                                 cfg->vars [pos].idx = pos;
13809 #if SIZEOF_REGISTER == 4
13810                                 if (cfg->varinfo [pos]->type == STACK_I8) {
13811                                         /* Modify the two component vars too */
13812                                         MonoInst *var1;
13813
13814                                         var1 = get_vreg_to_inst (cfg, MONO_LVREG_LS (cfg->varinfo [pos]->dreg));
13815                                         var1->inst_c0 = pos;
13816                                         var1 = get_vreg_to_inst (cfg, MONO_LVREG_MS (cfg->varinfo [pos]->dreg));
13817                                         var1->inst_c0 = pos;
13818                                 }
13819 #endif
13820                         }
13821                         pos ++;
13822                 }
13823         }
13824         cfg->num_varinfo = pos;
13825         if (cfg->locals_start > cfg->num_varinfo)
13826                 cfg->locals_start = cfg->num_varinfo;
13827 }
13828
13829 /*
13830  * mono_allocate_gsharedvt_vars:
13831  *
13832  *   Allocate variables with gsharedvt types to entries in the MonoGSharedVtMethodRuntimeInfo.entries array.
13833  * Initialize cfg->gsharedvt_vreg_to_idx with the mapping between vregs and indexes.
13834  */
13835 void
13836 mono_allocate_gsharedvt_vars (MonoCompile *cfg)
13837 {
13838         int i;
13839
13840         cfg->gsharedvt_vreg_to_idx = (int *)mono_mempool_alloc0 (cfg->mempool, sizeof (int) * cfg->next_vreg);
13841
13842         for (i = 0; i < cfg->num_varinfo; ++i) {
13843                 MonoInst *ins = cfg->varinfo [i];
13844                 int idx;
13845
13846                 if (mini_is_gsharedvt_variable_type (ins->inst_vtype)) {
13847                         if (i >= cfg->locals_start) {
13848                                 /* Local */
13849                                 idx = get_gsharedvt_info_slot (cfg, ins->inst_vtype, MONO_RGCTX_INFO_LOCAL_OFFSET);
13850                                 cfg->gsharedvt_vreg_to_idx [ins->dreg] = idx + 1;
13851                                 ins->opcode = OP_GSHAREDVT_LOCAL;
13852                                 ins->inst_imm = idx;
13853                         } else {
13854                                 /* Arg */
13855                                 cfg->gsharedvt_vreg_to_idx [ins->dreg] = -1;
13856                                 ins->opcode = OP_GSHAREDVT_ARG_REGOFFSET;
13857                         }
13858                 }
13859         }
13860 }
13861
13862 /**
13863  * mono_spill_global_vars:
13864  *
13865  *   Generate spill code for variables which are not allocated to registers, 
13866  * and replace vregs with their allocated hregs. *need_local_opts is set to TRUE if
13867  * code is generated which could be optimized by the local optimization passes.
13868  */
13869 void
13870 mono_spill_global_vars (MonoCompile *cfg, gboolean *need_local_opts)
13871 {
13872         MonoBasicBlock *bb;
13873         char spec2 [16];
13874         int orig_next_vreg;
13875         guint32 *vreg_to_lvreg;
13876         guint32 *lvregs;
13877         guint32 i, lvregs_len, lvregs_size;
13878         gboolean dest_has_lvreg = FALSE;
13879         MonoStackType stacktypes [128];
13880         MonoInst **live_range_start, **live_range_end;
13881         MonoBasicBlock **live_range_start_bb, **live_range_end_bb;
13882
13883         *need_local_opts = FALSE;
13884
13885         memset (spec2, 0, sizeof (spec2));
13886
13887         /* FIXME: Move this function to mini.c */
13888         stacktypes ['i'] = STACK_PTR;
13889         stacktypes ['l'] = STACK_I8;
13890         stacktypes ['f'] = STACK_R8;
13891 #ifdef MONO_ARCH_SIMD_INTRINSICS
13892         stacktypes ['x'] = STACK_VTYPE;
13893 #endif
13894
13895 #if SIZEOF_REGISTER == 4
13896         /* Create MonoInsts for longs */
13897         for (i = 0; i < cfg->num_varinfo; i++) {
13898                 MonoInst *ins = cfg->varinfo [i];
13899
13900                 if ((ins->opcode != OP_REGVAR) && !(ins->flags & MONO_INST_IS_DEAD)) {
13901                         switch (ins->type) {
13902                         case STACK_R8:
13903                         case STACK_I8: {
13904                                 MonoInst *tree;
13905
13906                                 if (ins->type == STACK_R8 && !COMPILE_SOFT_FLOAT (cfg))
13907                                         break;
13908
13909                                 g_assert (ins->opcode == OP_REGOFFSET);
13910
13911                                 tree = get_vreg_to_inst (cfg, MONO_LVREG_LS (ins->dreg));
13912                                 g_assert (tree);
13913                                 tree->opcode = OP_REGOFFSET;
13914                                 tree->inst_basereg = ins->inst_basereg;
13915                                 tree->inst_offset = ins->inst_offset + MINI_LS_WORD_OFFSET;
13916
13917                                 tree = get_vreg_to_inst (cfg, MONO_LVREG_MS (ins->dreg));
13918                                 g_assert (tree);
13919                                 tree->opcode = OP_REGOFFSET;
13920                                 tree->inst_basereg = ins->inst_basereg;
13921                                 tree->inst_offset = ins->inst_offset + MINI_MS_WORD_OFFSET;
13922                                 break;
13923                         }
13924                         default:
13925                                 break;
13926                         }
13927                 }
13928         }
13929 #endif
13930
13931         if (cfg->compute_gc_maps) {
13932                 /* registers need liveness info even for !non refs */
13933                 for (i = 0; i < cfg->num_varinfo; i++) {
13934                         MonoInst *ins = cfg->varinfo [i];
13935
13936                         if (ins->opcode == OP_REGVAR)
13937                                 ins->flags |= MONO_INST_GC_TRACK;
13938                 }
13939         }
13940                 
13941         /* FIXME: widening and truncation */
13942
13943         /*
13944          * As an optimization, when a variable allocated to the stack is first loaded into 
13945          * an lvreg, we will remember the lvreg and use it the next time instead of loading
13946          * the variable again.
13947          */
13948         orig_next_vreg = cfg->next_vreg;
13949         vreg_to_lvreg = (guint32 *)mono_mempool_alloc0 (cfg->mempool, sizeof (guint32) * cfg->next_vreg);
13950         lvregs_size = 1024;
13951         lvregs = (guint32 *)mono_mempool_alloc (cfg->mempool, sizeof (guint32) * lvregs_size);
13952         lvregs_len = 0;
13953
13954         /* 
13955          * These arrays contain the first and last instructions accessing a given
13956          * variable.
13957          * Since we emit bblocks in the same order we process them here, and we
13958          * don't split live ranges, these will precisely describe the live range of
13959          * the variable, i.e. the instruction range where a valid value can be found
13960          * in the variables location.
13961          * The live range is computed using the liveness info computed by the liveness pass.
13962          * We can't use vmv->range, since that is an abstract live range, and we need
13963          * one which is instruction precise.
13964          * FIXME: Variables used in out-of-line bblocks have a hole in their live range.
13965          */
13966         /* FIXME: Only do this if debugging info is requested */
13967         live_range_start = g_new0 (MonoInst*, cfg->next_vreg);
13968         live_range_end = g_new0 (MonoInst*, cfg->next_vreg);
13969         live_range_start_bb = g_new (MonoBasicBlock*, cfg->next_vreg);
13970         live_range_end_bb = g_new (MonoBasicBlock*, cfg->next_vreg);
13971         
13972         /* Add spill loads/stores */
13973         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
13974                 MonoInst *ins;
13975
13976                 if (cfg->verbose_level > 2)
13977                         printf ("\nSPILL BLOCK %d:\n", bb->block_num);
13978
13979                 /* Clear vreg_to_lvreg array */
13980                 for (i = 0; i < lvregs_len; i++)
13981                         vreg_to_lvreg [lvregs [i]] = 0;
13982                 lvregs_len = 0;
13983
13984                 cfg->cbb = bb;
13985                 MONO_BB_FOR_EACH_INS (bb, ins) {
13986                         const char *spec = INS_INFO (ins->opcode);
13987                         int regtype, srcindex, sreg, tmp_reg, prev_dreg, num_sregs;
13988                         gboolean store, no_lvreg;
13989                         int sregs [MONO_MAX_SRC_REGS];
13990
13991                         if (G_UNLIKELY (cfg->verbose_level > 2))
13992                                 mono_print_ins (ins);
13993
13994                         if (ins->opcode == OP_NOP)
13995                                 continue;
13996
13997                         /* 
13998                          * We handle LDADDR here as well, since it can only be decomposed
13999                          * when variable addresses are known.
14000                          */
14001                         if (ins->opcode == OP_LDADDR) {
14002                                 MonoInst *var = (MonoInst *)ins->inst_p0;
14003
14004                                 if (var->opcode == OP_VTARG_ADDR) {
14005                                         /* Happens on SPARC/S390 where vtypes are passed by reference */
14006                                         MonoInst *vtaddr = var->inst_left;
14007                                         if (vtaddr->opcode == OP_REGVAR) {
14008                                                 ins->opcode = OP_MOVE;
14009                                                 ins->sreg1 = vtaddr->dreg;
14010                                         }
14011                                         else if (var->inst_left->opcode == OP_REGOFFSET) {
14012                                                 ins->opcode = OP_LOAD_MEMBASE;
14013                                                 ins->inst_basereg = vtaddr->inst_basereg;
14014                                                 ins->inst_offset = vtaddr->inst_offset;
14015                                         } else
14016                                                 NOT_IMPLEMENTED;
14017                                 } else if (cfg->gsharedvt && cfg->gsharedvt_vreg_to_idx [var->dreg] < 0) {
14018                                         /* gsharedvt arg passed by ref */
14019                                         g_assert (var->opcode == OP_GSHAREDVT_ARG_REGOFFSET);
14020
14021                                         ins->opcode = OP_LOAD_MEMBASE;
14022                                         ins->inst_basereg = var->inst_basereg;
14023                                         ins->inst_offset = var->inst_offset;
14024                                 } else if (cfg->gsharedvt && cfg->gsharedvt_vreg_to_idx [var->dreg]) {
14025                                         MonoInst *load, *load2, *load3;
14026                                         int idx = cfg->gsharedvt_vreg_to_idx [var->dreg] - 1;
14027                                         int reg1, reg2, reg3;
14028                                         MonoInst *info_var = cfg->gsharedvt_info_var;
14029                                         MonoInst *locals_var = cfg->gsharedvt_locals_var;
14030
14031                                         /*
14032                                          * gsharedvt local.
14033                                          * Compute the address of the local as gsharedvt_locals_var + gsharedvt_info_var->locals_offsets [idx].
14034                                          */
14035
14036                                         g_assert (var->opcode == OP_GSHAREDVT_LOCAL);
14037
14038                                         g_assert (info_var);
14039                                         g_assert (locals_var);
14040
14041                                         /* Mark the instruction used to compute the locals var as used */
14042                                         cfg->gsharedvt_locals_var_ins = NULL;
14043
14044                                         /* Load the offset */
14045                                         if (info_var->opcode == OP_REGOFFSET) {
14046                                                 reg1 = alloc_ireg (cfg);
14047                                                 NEW_LOAD_MEMBASE (cfg, load, OP_LOAD_MEMBASE, reg1, info_var->inst_basereg, info_var->inst_offset);
14048                                         } else if (info_var->opcode == OP_REGVAR) {
14049                                                 load = NULL;
14050                                                 reg1 = info_var->dreg;
14051                                         } else {
14052                                                 g_assert_not_reached ();
14053                                         }
14054                                         reg2 = alloc_ireg (cfg);
14055                                         NEW_LOAD_MEMBASE (cfg, load2, OP_LOADI4_MEMBASE, reg2, reg1, MONO_STRUCT_OFFSET (MonoGSharedVtMethodRuntimeInfo, entries) + (idx * sizeof (gpointer)));
14056                                         /* Load the locals area address */
14057                                         reg3 = alloc_ireg (cfg);
14058                                         if (locals_var->opcode == OP_REGOFFSET) {
14059                                                 NEW_LOAD_MEMBASE (cfg, load3, OP_LOAD_MEMBASE, reg3, locals_var->inst_basereg, locals_var->inst_offset);
14060                                         } else if (locals_var->opcode == OP_REGVAR) {
14061                                                 NEW_UNALU (cfg, load3, OP_MOVE, reg3, locals_var->dreg);
14062                                         } else {
14063                                                 g_assert_not_reached ();
14064                                         }
14065                                         /* Compute the address */
14066                                         ins->opcode = OP_PADD;
14067                                         ins->sreg1 = reg3;
14068                                         ins->sreg2 = reg2;
14069
14070                                         mono_bblock_insert_before_ins (bb, ins, load3);
14071                                         mono_bblock_insert_before_ins (bb, load3, load2);
14072                                         if (load)
14073                                                 mono_bblock_insert_before_ins (bb, load2, load);
14074                                 } else {
14075                                         g_assert (var->opcode == OP_REGOFFSET);
14076
14077                                         ins->opcode = OP_ADD_IMM;
14078                                         ins->sreg1 = var->inst_basereg;
14079                                         ins->inst_imm = var->inst_offset;
14080                                 }
14081
14082                                 *need_local_opts = TRUE;
14083                                 spec = INS_INFO (ins->opcode);
14084                         }
14085
14086                         if (ins->opcode < MONO_CEE_LAST) {
14087                                 mono_print_ins (ins);
14088                                 g_assert_not_reached ();
14089                         }
14090
14091                         /*
14092                          * Store opcodes have destbasereg in the dreg, but in reality, it is an
14093                          * src register.
14094                          * FIXME:
14095                          */
14096                         if (MONO_IS_STORE_MEMBASE (ins)) {
14097                                 tmp_reg = ins->dreg;
14098                                 ins->dreg = ins->sreg2;
14099                                 ins->sreg2 = tmp_reg;
14100                                 store = TRUE;
14101
14102                                 spec2 [MONO_INST_DEST] = ' ';
14103                                 spec2 [MONO_INST_SRC1] = spec [MONO_INST_SRC1];
14104                                 spec2 [MONO_INST_SRC2] = spec [MONO_INST_DEST];
14105                                 spec2 [MONO_INST_SRC3] = ' ';
14106                                 spec = spec2;
14107                         } else if (MONO_IS_STORE_MEMINDEX (ins))
14108                                 g_assert_not_reached ();
14109                         else
14110                                 store = FALSE;
14111                         no_lvreg = FALSE;
14112
14113                         if (G_UNLIKELY (cfg->verbose_level > 2)) {
14114                                 printf ("\t %.3s %d", spec, ins->dreg);
14115                                 num_sregs = mono_inst_get_src_registers (ins, sregs);
14116                                 for (srcindex = 0; srcindex < num_sregs; ++srcindex)
14117                                         printf (" %d", sregs [srcindex]);
14118                                 printf ("\n");
14119                         }
14120
14121                         /***************/
14122                         /*    DREG     */
14123                         /***************/
14124                         regtype = spec [MONO_INST_DEST];
14125                         g_assert (((ins->dreg == -1) && (regtype == ' ')) || ((ins->dreg != -1) && (regtype != ' ')));
14126                         prev_dreg = -1;
14127
14128                         if ((ins->dreg != -1) && get_vreg_to_inst (cfg, ins->dreg)) {
14129                                 MonoInst *var = get_vreg_to_inst (cfg, ins->dreg);
14130                                 MonoInst *store_ins;
14131                                 int store_opcode;
14132                                 MonoInst *def_ins = ins;
14133                                 int dreg = ins->dreg; /* The original vreg */
14134
14135                                 store_opcode = mono_type_to_store_membase (cfg, var->inst_vtype);
14136
14137                                 if (var->opcode == OP_REGVAR) {
14138                                         ins->dreg = var->dreg;
14139                                 } 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)) {
14140                                         /* 
14141                                          * Instead of emitting a load+store, use a _membase opcode.
14142                                          */
14143                                         g_assert (var->opcode == OP_REGOFFSET);
14144                                         if (ins->opcode == OP_MOVE) {
14145                                                 NULLIFY_INS (ins);
14146                                                 def_ins = NULL;
14147                                         } else {
14148                                                 ins->opcode = op_to_op_dest_membase (store_opcode, ins->opcode);
14149                                                 ins->inst_basereg = var->inst_basereg;
14150                                                 ins->inst_offset = var->inst_offset;
14151                                                 ins->dreg = -1;
14152                                         }
14153                                         spec = INS_INFO (ins->opcode);
14154                                 } else {
14155                                         guint32 lvreg;
14156
14157                                         g_assert (var->opcode == OP_REGOFFSET);
14158
14159                                         prev_dreg = ins->dreg;
14160
14161                                         /* Invalidate any previous lvreg for this vreg */
14162                                         vreg_to_lvreg [ins->dreg] = 0;
14163
14164                                         lvreg = 0;
14165
14166                                         if (COMPILE_SOFT_FLOAT (cfg) && store_opcode == OP_STORER8_MEMBASE_REG) {
14167                                                 regtype = 'l';
14168                                                 store_opcode = OP_STOREI8_MEMBASE_REG;
14169                                         }
14170
14171                                         ins->dreg = alloc_dreg (cfg, stacktypes [regtype]);
14172
14173 #if SIZEOF_REGISTER != 8
14174                                         if (regtype == 'l') {
14175                                                 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));
14176                                                 mono_bblock_insert_after_ins (bb, ins, store_ins);
14177                                                 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));
14178                                                 mono_bblock_insert_after_ins (bb, ins, store_ins);
14179                                                 def_ins = store_ins;
14180                                         }
14181                                         else
14182 #endif
14183                                         {
14184                                                 g_assert (store_opcode != OP_STOREV_MEMBASE);
14185
14186                                                 /* Try to fuse the store into the instruction itself */
14187                                                 /* FIXME: Add more instructions */
14188                                                 if (!lvreg && ((ins->opcode == OP_ICONST) || ((ins->opcode == OP_I8CONST) && (ins->inst_c0 == 0)))) {
14189                                                         ins->opcode = store_membase_reg_to_store_membase_imm (store_opcode);
14190                                                         ins->inst_imm = ins->inst_c0;
14191                                                         ins->inst_destbasereg = var->inst_basereg;
14192                                                         ins->inst_offset = var->inst_offset;
14193                                                         spec = INS_INFO (ins->opcode);
14194                                                 } else if (!lvreg && ((ins->opcode == OP_MOVE) || (ins->opcode == OP_FMOVE) || (ins->opcode == OP_LMOVE) || (ins->opcode == OP_RMOVE))) {
14195                                                         ins->opcode = store_opcode;
14196                                                         ins->inst_destbasereg = var->inst_basereg;
14197                                                         ins->inst_offset = var->inst_offset;
14198
14199                                                         no_lvreg = TRUE;
14200
14201                                                         tmp_reg = ins->dreg;
14202                                                         ins->dreg = ins->sreg2;
14203                                                         ins->sreg2 = tmp_reg;
14204                                                         store = TRUE;
14205
14206                                                         spec2 [MONO_INST_DEST] = ' ';
14207                                                         spec2 [MONO_INST_SRC1] = spec [MONO_INST_SRC1];
14208                                                         spec2 [MONO_INST_SRC2] = spec [MONO_INST_DEST];
14209                                                         spec2 [MONO_INST_SRC3] = ' ';
14210                                                         spec = spec2;
14211                                                 } else if (!lvreg && (op_to_op_store_membase (store_opcode, ins->opcode) != -1)) {
14212                                                         // FIXME: The backends expect the base reg to be in inst_basereg
14213                                                         ins->opcode = op_to_op_store_membase (store_opcode, ins->opcode);
14214                                                         ins->dreg = -1;
14215                                                         ins->inst_basereg = var->inst_basereg;
14216                                                         ins->inst_offset = var->inst_offset;
14217                                                         spec = INS_INFO (ins->opcode);
14218                                                 } else {
14219                                                         /* printf ("INS: "); mono_print_ins (ins); */
14220                                                         /* Create a store instruction */
14221                                                         NEW_STORE_MEMBASE (cfg, store_ins, store_opcode, var->inst_basereg, var->inst_offset, ins->dreg);
14222
14223                                                         /* Insert it after the instruction */
14224                                                         mono_bblock_insert_after_ins (bb, ins, store_ins);
14225
14226                                                         def_ins = store_ins;
14227
14228                                                         /* 
14229                                                          * We can't assign ins->dreg to var->dreg here, since the
14230                                                          * sregs could use it. So set a flag, and do it after
14231                                                          * the sregs.
14232                                                          */
14233                                                         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)))
14234                                                                 dest_has_lvreg = TRUE;
14235                                                 }
14236                                         }
14237                                 }
14238
14239                                 if (def_ins && !live_range_start [dreg]) {
14240                                         live_range_start [dreg] = def_ins;
14241                                         live_range_start_bb [dreg] = bb;
14242                                 }
14243
14244                                 if (cfg->compute_gc_maps && def_ins && (var->flags & MONO_INST_GC_TRACK)) {
14245                                         MonoInst *tmp;
14246
14247                                         MONO_INST_NEW (cfg, tmp, OP_GC_LIVENESS_DEF);
14248                                         tmp->inst_c1 = dreg;
14249                                         mono_bblock_insert_after_ins (bb, def_ins, tmp);
14250                                 }
14251                         }
14252
14253                         /************/
14254                         /*  SREGS   */
14255                         /************/
14256                         num_sregs = mono_inst_get_src_registers (ins, sregs);
14257                         for (srcindex = 0; srcindex < 3; ++srcindex) {
14258                                 regtype = spec [MONO_INST_SRC1 + srcindex];
14259                                 sreg = sregs [srcindex];
14260
14261                                 g_assert (((sreg == -1) && (regtype == ' ')) || ((sreg != -1) && (regtype != ' ')));
14262                                 if ((sreg != -1) && get_vreg_to_inst (cfg, sreg)) {
14263                                         MonoInst *var = get_vreg_to_inst (cfg, sreg);
14264                                         MonoInst *use_ins = ins;
14265                                         MonoInst *load_ins;
14266                                         guint32 load_opcode;
14267
14268                                         if (var->opcode == OP_REGVAR) {
14269                                                 sregs [srcindex] = var->dreg;
14270                                                 //mono_inst_set_src_registers (ins, sregs);
14271                                                 live_range_end [sreg] = use_ins;
14272                                                 live_range_end_bb [sreg] = bb;
14273
14274                                                 if (cfg->compute_gc_maps && var->dreg < orig_next_vreg && (var->flags & MONO_INST_GC_TRACK)) {
14275                                                         MonoInst *tmp;
14276
14277                                                         MONO_INST_NEW (cfg, tmp, OP_GC_LIVENESS_USE);
14278                                                         /* var->dreg is a hreg */
14279                                                         tmp->inst_c1 = sreg;
14280                                                         mono_bblock_insert_after_ins (bb, ins, tmp);
14281                                                 }
14282
14283                                                 continue;
14284                                         }
14285
14286                                         g_assert (var->opcode == OP_REGOFFSET);
14287                                                 
14288                                         load_opcode = mono_type_to_load_membase (cfg, var->inst_vtype);
14289
14290                                         g_assert (load_opcode != OP_LOADV_MEMBASE);
14291
14292                                         if (vreg_to_lvreg [sreg]) {
14293                                                 g_assert (vreg_to_lvreg [sreg] != -1);
14294
14295                                                 /* The variable is already loaded to an lvreg */
14296                                                 if (G_UNLIKELY (cfg->verbose_level > 2))
14297                                                         printf ("\t\tUse lvreg R%d for R%d.\n", vreg_to_lvreg [sreg], sreg);
14298                                                 sregs [srcindex] = vreg_to_lvreg [sreg];
14299                                                 //mono_inst_set_src_registers (ins, sregs);
14300                                                 continue;
14301                                         }
14302
14303                                         /* Try to fuse the load into the instruction */
14304                                         if ((srcindex == 0) && (op_to_op_src1_membase (cfg, load_opcode, ins->opcode) != -1)) {
14305                                                 ins->opcode = op_to_op_src1_membase (cfg, load_opcode, ins->opcode);
14306                                                 sregs [0] = var->inst_basereg;
14307                                                 //mono_inst_set_src_registers (ins, sregs);
14308                                                 ins->inst_offset = var->inst_offset;
14309                                         } else if ((srcindex == 1) && (op_to_op_src2_membase (cfg, load_opcode, ins->opcode) != -1)) {
14310                                                 ins->opcode = op_to_op_src2_membase (cfg, load_opcode, ins->opcode);
14311                                                 sregs [1] = var->inst_basereg;
14312                                                 //mono_inst_set_src_registers (ins, sregs);
14313                                                 ins->inst_offset = var->inst_offset;
14314                                         } else {
14315                                                 if (MONO_IS_REAL_MOVE (ins)) {
14316                                                         ins->opcode = OP_NOP;
14317                                                         sreg = ins->dreg;
14318                                                 } else {
14319                                                         //printf ("%d ", srcindex); mono_print_ins (ins);
14320
14321                                                         sreg = alloc_dreg (cfg, stacktypes [regtype]);
14322
14323                                                         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) {
14324                                                                 if (var->dreg == prev_dreg) {
14325                                                                         /*
14326                                                                          * sreg refers to the value loaded by the load
14327                                                                          * emitted below, but we need to use ins->dreg
14328                                                                          * since it refers to the store emitted earlier.
14329                                                                          */
14330                                                                         sreg = ins->dreg;
14331                                                                 }
14332                                                                 g_assert (sreg != -1);
14333                                                                 vreg_to_lvreg [var->dreg] = sreg;
14334                                                                 if (lvregs_len >= lvregs_size) {
14335                                                                         guint32 *new_lvregs = mono_mempool_alloc0 (cfg->mempool, sizeof (guint32) * lvregs_size * 2);
14336                                                                         memcpy (new_lvregs, lvregs, sizeof (guint32) * lvregs_size);
14337                                                                         lvregs = new_lvregs;
14338                                                                         lvregs_size *= 2;
14339                                                                 }
14340                                                                 lvregs [lvregs_len ++] = var->dreg;
14341                                                         }
14342                                                 }
14343
14344                                                 sregs [srcindex] = sreg;
14345                                                 //mono_inst_set_src_registers (ins, sregs);
14346
14347 #if SIZEOF_REGISTER != 8
14348                                                 if (regtype == 'l') {
14349                                                         NEW_LOAD_MEMBASE (cfg, load_ins, OP_LOADI4_MEMBASE, MONO_LVREG_MS (sreg), var->inst_basereg, var->inst_offset + MINI_MS_WORD_OFFSET);
14350                                                         mono_bblock_insert_before_ins (bb, ins, load_ins);
14351                                                         NEW_LOAD_MEMBASE (cfg, load_ins, OP_LOADI4_MEMBASE, MONO_LVREG_LS (sreg), var->inst_basereg, var->inst_offset + MINI_LS_WORD_OFFSET);
14352                                                         mono_bblock_insert_before_ins (bb, ins, load_ins);
14353                                                         use_ins = load_ins;
14354                                                 }
14355                                                 else
14356 #endif
14357                                                 {
14358 #if SIZEOF_REGISTER == 4
14359                                                         g_assert (load_opcode != OP_LOADI8_MEMBASE);
14360 #endif
14361                                                         NEW_LOAD_MEMBASE (cfg, load_ins, load_opcode, sreg, var->inst_basereg, var->inst_offset);
14362                                                         mono_bblock_insert_before_ins (bb, ins, load_ins);
14363                                                         use_ins = load_ins;
14364                                                 }
14365                                         }
14366
14367                                         if (var->dreg < orig_next_vreg) {
14368                                                 live_range_end [var->dreg] = use_ins;
14369                                                 live_range_end_bb [var->dreg] = bb;
14370                                         }
14371
14372                                         if (cfg->compute_gc_maps && var->dreg < orig_next_vreg && (var->flags & MONO_INST_GC_TRACK)) {
14373                                                 MonoInst *tmp;
14374
14375                                                 MONO_INST_NEW (cfg, tmp, OP_GC_LIVENESS_USE);
14376                                                 tmp->inst_c1 = var->dreg;
14377                                                 mono_bblock_insert_after_ins (bb, ins, tmp);
14378                                         }
14379                                 }
14380                         }
14381                         mono_inst_set_src_registers (ins, sregs);
14382
14383                         if (dest_has_lvreg) {
14384                                 g_assert (ins->dreg != -1);
14385                                 vreg_to_lvreg [prev_dreg] = ins->dreg;
14386                                 if (lvregs_len >= lvregs_size) {
14387                                         guint32 *new_lvregs = mono_mempool_alloc0 (cfg->mempool, sizeof (guint32) * lvregs_size * 2);
14388                                         memcpy (new_lvregs, lvregs, sizeof (guint32) * lvregs_size);
14389                                         lvregs = new_lvregs;
14390                                         lvregs_size *= 2;
14391                                 }
14392                                 lvregs [lvregs_len ++] = prev_dreg;
14393                                 dest_has_lvreg = FALSE;
14394                         }
14395
14396                         if (store) {
14397                                 tmp_reg = ins->dreg;
14398                                 ins->dreg = ins->sreg2;
14399                                 ins->sreg2 = tmp_reg;
14400                         }
14401
14402                         if (MONO_IS_CALL (ins)) {
14403                                 /* Clear vreg_to_lvreg array */
14404                                 for (i = 0; i < lvregs_len; i++)
14405                                         vreg_to_lvreg [lvregs [i]] = 0;
14406                                 lvregs_len = 0;
14407                         } else if (ins->opcode == OP_NOP) {
14408                                 ins->dreg = -1;
14409                                 MONO_INST_NULLIFY_SREGS (ins);
14410                         }
14411
14412                         if (cfg->verbose_level > 2)
14413                                 mono_print_ins_index (1, ins);
14414                 }
14415
14416                 /* Extend the live range based on the liveness info */
14417                 if (cfg->compute_precise_live_ranges && bb->live_out_set && bb->code) {
14418                         for (i = 0; i < cfg->num_varinfo; i ++) {
14419                                 MonoMethodVar *vi = MONO_VARINFO (cfg, i);
14420
14421                                 if (vreg_is_volatile (cfg, vi->vreg))
14422                                         /* The liveness info is incomplete */
14423                                         continue;
14424
14425                                 if (mono_bitset_test_fast (bb->live_in_set, i) && !live_range_start [vi->vreg]) {
14426                                         /* Live from at least the first ins of this bb */
14427                                         live_range_start [vi->vreg] = bb->code;
14428                                         live_range_start_bb [vi->vreg] = bb;
14429                                 }
14430
14431                                 if (mono_bitset_test_fast (bb->live_out_set, i)) {
14432                                         /* Live at least until the last ins of this bb */
14433                                         live_range_end [vi->vreg] = bb->last_ins;
14434                                         live_range_end_bb [vi->vreg] = bb;
14435                                 }
14436                         }
14437                 }
14438         }
14439         
14440         /*
14441          * Emit LIVERANGE_START/LIVERANGE_END opcodes, the backend will implement them
14442          * by storing the current native offset into MonoMethodVar->live_range_start/end.
14443          */
14444         if (cfg->backend->have_liverange_ops && cfg->compute_precise_live_ranges && cfg->comp_done & MONO_COMP_LIVENESS) {
14445                 for (i = 0; i < cfg->num_varinfo; ++i) {
14446                         int vreg = MONO_VARINFO (cfg, i)->vreg;
14447                         MonoInst *ins;
14448
14449                         if (live_range_start [vreg]) {
14450                                 MONO_INST_NEW (cfg, ins, OP_LIVERANGE_START);
14451                                 ins->inst_c0 = i;
14452                                 ins->inst_c1 = vreg;
14453                                 mono_bblock_insert_after_ins (live_range_start_bb [vreg], live_range_start [vreg], ins);
14454                         }
14455                         if (live_range_end [vreg]) {
14456                                 MONO_INST_NEW (cfg, ins, OP_LIVERANGE_END);
14457                                 ins->inst_c0 = i;
14458                                 ins->inst_c1 = vreg;
14459                                 if (live_range_end [vreg] == live_range_end_bb [vreg]->last_ins)
14460                                         mono_add_ins_to_end (live_range_end_bb [vreg], ins);
14461                                 else
14462                                         mono_bblock_insert_after_ins (live_range_end_bb [vreg], live_range_end [vreg], ins);
14463                         }
14464                 }
14465         }
14466
14467         if (cfg->gsharedvt_locals_var_ins) {
14468                 /* Nullify if unused */
14469                 cfg->gsharedvt_locals_var_ins->opcode = OP_PCONST;
14470                 cfg->gsharedvt_locals_var_ins->inst_imm = 0;
14471         }
14472
14473         g_free (live_range_start);
14474         g_free (live_range_end);
14475         g_free (live_range_start_bb);
14476         g_free (live_range_end_bb);
14477 }
14478
14479
14480 /**
14481  * FIXME:
14482  * - use 'iadd' instead of 'int_add'
14483  * - handling ovf opcodes: decompose in method_to_ir.
14484  * - unify iregs/fregs
14485  *   -> partly done, the missing parts are:
14486  *   - a more complete unification would involve unifying the hregs as well, so
14487  *     code wouldn't need if (fp) all over the place. but that would mean the hregs
14488  *     would no longer map to the machine hregs, so the code generators would need to
14489  *     be modified. Also, on ia64 for example, niregs + nfregs > 256 -> bitmasks
14490  *     wouldn't work any more. Duplicating the code in mono_local_regalloc () into
14491  *     fp/non-fp branches speeds it up by about 15%.
14492  * - use sext/zext opcodes instead of shifts
14493  * - add OP_ICALL
14494  * - get rid of TEMPLOADs if possible and use vregs instead
14495  * - clean up usage of OP_P/OP_ opcodes
14496  * - cleanup usage of DUMMY_USE
14497  * - cleanup the setting of ins->type for MonoInst's which are pushed on the 
14498  *   stack
14499  * - set the stack type and allocate a dreg in the EMIT_NEW macros
14500  * - get rid of all the <foo>2 stuff when the new JIT is ready.
14501  * - make sure handle_stack_args () is called before the branch is emitted
14502  * - when the new IR is done, get rid of all unused stuff
14503  * - COMPARE/BEQ as separate instructions or unify them ?
14504  *   - keeping them separate allows specialized compare instructions like
14505  *     compare_imm, compare_membase
14506  *   - most back ends unify fp compare+branch, fp compare+ceq
14507  * - integrate mono_save_args into inline_method
14508  * - get rid of the empty bblocks created by MONO_EMIT_NEW_BRACH_BLOCK2
14509  * - handle long shift opts on 32 bit platforms somehow: they require 
14510  *   3 sregs (2 for arg1 and 1 for arg2)
14511  * - make byref a 'normal' type.
14512  * - use vregs for bb->out_stacks if possible, handle_global_vreg will make them a
14513  *   variable if needed.
14514  * - do not start a new IL level bblock when cfg->cbb is changed by a function call
14515  *   like inline_method.
14516  * - remove inlining restrictions
14517  * - fix LNEG and enable cfold of INEG
14518  * - generalize x86 optimizations like ldelema as a peephole optimization
14519  * - add store_mem_imm for amd64
14520  * - optimize the loading of the interruption flag in the managed->native wrappers
14521  * - avoid special handling of OP_NOP in passes
14522  * - move code inserting instructions into one function/macro.
14523  * - try a coalescing phase after liveness analysis
14524  * - add float -> vreg conversion + local optimizations on !x86
14525  * - figure out how to handle decomposed branches during optimizations, ie.
14526  *   compare+branch, op_jump_table+op_br etc.
14527  * - promote RuntimeXHandles to vregs
14528  * - vtype cleanups:
14529  *   - add a NEW_VARLOADA_VREG macro
14530  * - the vtype optimizations are blocked by the LDADDR opcodes generated for 
14531  *   accessing vtype fields.
14532  * - get rid of I8CONST on 64 bit platforms
14533  * - dealing with the increase in code size due to branches created during opcode
14534  *   decomposition:
14535  *   - use extended basic blocks
14536  *     - all parts of the JIT
14537  *     - handle_global_vregs () && local regalloc
14538  *   - avoid introducing global vregs during decomposition, like 'vtable' in isinst
14539  * - sources of increase in code size:
14540  *   - vtypes
14541  *   - long compares
14542  *   - isinst and castclass
14543  *   - lvregs not allocated to global registers even if used multiple times
14544  * - call cctors outside the JIT, to make -v output more readable and JIT timings more
14545  *   meaningful.
14546  * - check for fp stack leakage in other opcodes too. (-> 'exceptions' optimization)
14547  * - add all micro optimizations from the old JIT
14548  * - put tree optimizations into the deadce pass
14549  * - decompose op_start_handler/op_endfilter/op_endfinally earlier using an arch
14550  *   specific function.
14551  * - unify the float comparison opcodes with the other comparison opcodes, i.e.
14552  *   fcompare + branchCC.
14553  * - create a helper function for allocating a stack slot, taking into account 
14554  *   MONO_CFG_HAS_SPILLUP.
14555  * - merge r68207.
14556  * - merge the ia64 switch changes.
14557  * - optimize mono_regstate2_alloc_int/float.
14558  * - fix the pessimistic handling of variables accessed in exception handler blocks.
14559  * - need to write a tree optimization pass, but the creation of trees is difficult, i.e.
14560  *   parts of the tree could be separated by other instructions, killing the tree
14561  *   arguments, or stores killing loads etc. Also, should we fold loads into other
14562  *   instructions if the result of the load is used multiple times ?
14563  * - make the REM_IMM optimization in mini-x86.c arch-independent.
14564  * - LAST MERGE: 108395.
14565  * - when returning vtypes in registers, generate IR and append it to the end of the
14566  *   last bb instead of doing it in the epilog.
14567  * - change the store opcodes so they use sreg1 instead of dreg to store the base register.
14568  */
14569
14570 /*
14571
14572 NOTES
14573 -----
14574
14575 - When to decompose opcodes:
14576   - earlier: this makes some optimizations hard to implement, since the low level IR
14577   no longer contains the neccessary information. But it is easier to do.
14578   - later: harder to implement, enables more optimizations.
14579 - Branches inside bblocks:
14580   - created when decomposing complex opcodes. 
14581     - branches to another bblock: harmless, but not tracked by the branch 
14582       optimizations, so need to branch to a label at the start of the bblock.
14583     - branches to inside the same bblock: very problematic, trips up the local
14584       reg allocator. Can be fixed by spitting the current bblock, but that is a
14585       complex operation, since some local vregs can become global vregs etc.
14586 - Local/global vregs:
14587   - local vregs: temporary vregs used inside one bblock. Assigned to hregs by the
14588     local register allocator.
14589   - global vregs: used in more than one bblock. Have an associated MonoMethodVar
14590     structure, created by mono_create_var (). Assigned to hregs or the stack by
14591     the global register allocator.
14592 - When to do optimizations like alu->alu_imm:
14593   - earlier -> saves work later on since the IR will be smaller/simpler
14594   - later -> can work on more instructions
14595 - Handling of valuetypes:
14596   - When a vtype is pushed on the stack, a new temporary is created, an 
14597     instruction computing its address (LDADDR) is emitted and pushed on
14598     the stack. Need to optimize cases when the vtype is used immediately as in
14599     argument passing, stloc etc.
14600 - Instead of the to_end stuff in the old JIT, simply call the function handling
14601   the values on the stack before emitting the last instruction of the bb.
14602 */
14603
14604 #else /* !DISABLE_JIT */
14605
14606 void
14607 mono_set_break_policy (MonoBreakPolicyFunc policy_callback)
14608 {
14609 }
14610
14611 #endif /* !DISABLE_JIT */