[mini] Intrinsify Marshal.PtrToStructure<T>
[mono.git] / mono / mini / method-to-ir.c
1 /**
2  * \file
3  * Convert CIL to the JIT internal representation
4  *
5  * Author:
6  *   Paolo Molaro (lupus@ximian.com)
7  *   Dietmar Maurer (dietmar@ximian.com)
8  *
9  * (C) 2002 Ximian, Inc.
10  * Copyright 2003-2010 Novell, Inc (http://www.novell.com)
11  * Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
12  * Licensed under the MIT license. See LICENSE file in the project root for full license information.
13  */
14
15 #include <config.h>
16 #include <mono/utils/mono-compiler.h>
17 #include "mini.h"
18
19 #ifndef DISABLE_JIT
20
21 #include <signal.h>
22
23 #ifdef HAVE_UNISTD_H
24 #include <unistd.h>
25 #endif
26
27 #include <math.h>
28 #include <string.h>
29 #include <ctype.h>
30
31 #ifdef HAVE_SYS_TIME_H
32 #include <sys/time.h>
33 #endif
34
35 #ifdef HAVE_ALLOCA_H
36 #include <alloca.h>
37 #endif
38
39 #include <mono/utils/memcheck.h>
40 #include <mono/metadata/abi-details.h>
41 #include <mono/metadata/assembly.h>
42 #include <mono/metadata/attrdefs.h>
43 #include <mono/metadata/loader.h>
44 #include <mono/metadata/tabledefs.h>
45 #include <mono/metadata/class.h>
46 #include <mono/metadata/object.h>
47 #include <mono/metadata/exception.h>
48 #include <mono/metadata/opcodes.h>
49 #include <mono/metadata/mono-endian.h>
50 #include <mono/metadata/tokentype.h>
51 #include <mono/metadata/tabledefs.h>
52 #include <mono/metadata/marshal.h>
53 #include <mono/metadata/debug-helpers.h>
54 #include <mono/metadata/debug-internals.h>
55 #include <mono/metadata/gc-internals.h>
56 #include <mono/metadata/security-manager.h>
57 #include <mono/metadata/threads-types.h>
58 #include <mono/metadata/security-core-clr.h>
59 #include <mono/metadata/profiler-private.h>
60 #include <mono/metadata/profiler.h>
61 #include <mono/metadata/monitor.h>
62 #include <mono/utils/mono-memory-model.h>
63 #include <mono/utils/mono-error-internals.h>
64 #include <mono/metadata/mono-basic-block.h>
65 #include <mono/metadata/reflection-internals.h>
66 #include <mono/utils/mono-threads-coop.h>
67
68 #include "trace.h"
69
70 #include "ir-emit.h"
71
72 #include "jit-icalls.h"
73 #include "jit.h"
74 #include "debugger-agent.h"
75 #include "seq-points.h"
76 #include "aot-compiler.h"
77 #include "mini-llvm.h"
78
79 #define BRANCH_COST 10
80 #define INLINE_LENGTH_LIMIT 20
81
82 /* These have 'cfg' as an implicit argument */
83 #define INLINE_FAILURE(msg) do {                                                                        \
84         if ((cfg->method != cfg->current_method) && (cfg->current_method->wrapper_type == MONO_WRAPPER_NONE)) { \
85                 inline_failure (cfg, msg);                                                                              \
86                 goto exception_exit;                                                                                    \
87         } \
88         } while (0)
89 #define CHECK_CFG_EXCEPTION do {\
90                 if (cfg->exception_type != MONO_EXCEPTION_NONE) \
91                         goto exception_exit;                                            \
92         } while (0)
93 #define FIELD_ACCESS_FAILURE(method, field) do {                                        \
94                 field_access_failure ((cfg), (method), (field));                        \
95                 goto exception_exit;    \
96         } while (0)
97 #define GENERIC_SHARING_FAILURE(opcode) do {            \
98                 if (cfg->gshared) {                                                                     \
99                         gshared_failure (cfg, opcode, __FILE__, __LINE__);      \
100                         goto exception_exit;    \
101                 }                       \
102         } while (0)
103 #define GSHAREDVT_FAILURE(opcode) do {          \
104         if (cfg->gsharedvt) {                                                                                           \
105                 gsharedvt_failure (cfg, opcode, __FILE__, __LINE__);                    \
106                 goto exception_exit;                                                                                    \
107         }                                                                                                                                       \
108         } while (0)
109 #define OUT_OF_MEMORY_FAILURE do {      \
110                 mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);                \
111                 mono_error_set_out_of_memory (&cfg->error, "");                                 \
112                 goto exception_exit;    \
113         } while (0)
114 #define DISABLE_AOT(cfg) do { \
115                 if ((cfg)->verbose_level >= 2)                                            \
116                         printf ("AOT disabled: %s:%d\n", __FILE__, __LINE__);   \
117                 (cfg)->disable_aot = TRUE;                                                        \
118         } while (0)
119 #define LOAD_ERROR do { \
120                 break_on_unverified ();                                                         \
121                 mono_cfg_set_exception (cfg, MONO_EXCEPTION_TYPE_LOAD); \
122                 goto exception_exit;                                                                    \
123         } while (0)
124
125 #define TYPE_LOAD_ERROR(klass) do { \
126                 cfg->exception_ptr = klass; \
127                 LOAD_ERROR;                                     \
128         } while (0)
129
130 #define CHECK_CFG_ERROR do {\
131                 if (!mono_error_ok (&cfg->error)) { \
132                         mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);        \
133                         goto mono_error_exit; \
134                 } \
135         } while (0)
136
137 /* Determine whenever 'ins' represents a load of the 'this' argument */
138 #define MONO_CHECK_THIS(ins) (mono_method_signature (cfg->method)->hasthis && ((ins)->opcode == OP_MOVE) && ((ins)->sreg1 == cfg->args [0]->dreg))
139
140 static int ldind_to_load_membase (int opcode);
141 static int stind_to_store_membase (int opcode);
142
143 int mono_op_to_op_imm (int opcode);
144 int mono_op_to_op_imm_noemul (int opcode);
145
146 static int inline_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **sp,
147                                                   guchar *ip, guint real_offset, gboolean inline_always);
148 static MonoInst*
149 emit_llvmonly_virtual_call (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, int context_used, MonoInst **sp);
150
151 /* helper methods signatures */
152 static MonoMethodSignature *helper_sig_domain_get;
153 static MonoMethodSignature *helper_sig_rgctx_lazy_fetch_trampoline;
154 static MonoMethodSignature *helper_sig_llvmonly_imt_trampoline;
155 static MonoMethodSignature *helper_sig_jit_thread_attach;
156 static MonoMethodSignature *helper_sig_get_tls_tramp;
157 static MonoMethodSignature *helper_sig_set_tls_tramp;
158
159 /* type loading helpers */
160 static GENERATE_GET_CLASS_WITH_CACHE (runtime_helpers, "System.Runtime.CompilerServices", "RuntimeHelpers")
161 static GENERATE_TRY_GET_CLASS_WITH_CACHE (debuggable_attribute, "System.Diagnostics", "DebuggableAttribute")
162
163 /*
164  * Instruction metadata
165  */
166 #ifdef MINI_OP
167 #undef MINI_OP
168 #endif
169 #ifdef MINI_OP3
170 #undef MINI_OP3
171 #endif
172 #define MINI_OP(a,b,dest,src1,src2) dest, src1, src2, ' ',
173 #define MINI_OP3(a,b,dest,src1,src2,src3) dest, src1, src2, src3,
174 #define NONE ' '
175 #define IREG 'i'
176 #define FREG 'f'
177 #define VREG 'v'
178 #define XREG 'x'
179 #if SIZEOF_REGISTER == 8 && SIZEOF_REGISTER == SIZEOF_VOID_P
180 #define LREG IREG
181 #else
182 #define LREG 'l'
183 #endif
184 /* keep in sync with the enum in mini.h */
185 const char
186 ins_info[] = {
187 #include "mini-ops.h"
188 };
189 #undef MINI_OP
190 #undef MINI_OP3
191
192 #define MINI_OP(a,b,dest,src1,src2) ((src2) != NONE ? 2 : ((src1) != NONE ? 1 : 0)),
193 #define MINI_OP3(a,b,dest,src1,src2,src3) ((src3) != NONE ? 3 : ((src2) != NONE ? 2 : ((src1) != NONE ? 1 : 0))),
194 /* 
195  * This should contain the index of the last sreg + 1. This is not the same
196  * as the number of sregs for opcodes like IA64_CMP_EQ_IMM.
197  */
198 const gint8 ins_sreg_counts[] = {
199 #include "mini-ops.h"
200 };
201 #undef MINI_OP
202 #undef MINI_OP3
203
204 guint32
205 mono_alloc_ireg (MonoCompile *cfg)
206 {
207         return alloc_ireg (cfg);
208 }
209
210 guint32
211 mono_alloc_lreg (MonoCompile *cfg)
212 {
213         return alloc_lreg (cfg);
214 }
215
216 guint32
217 mono_alloc_freg (MonoCompile *cfg)
218 {
219         return alloc_freg (cfg);
220 }
221
222 guint32
223 mono_alloc_preg (MonoCompile *cfg)
224 {
225         return alloc_preg (cfg);
226 }
227
228 guint32
229 mono_alloc_dreg (MonoCompile *cfg, MonoStackType stack_type)
230 {
231         return alloc_dreg (cfg, stack_type);
232 }
233
234 /*
235  * mono_alloc_ireg_ref:
236  *
237  *   Allocate an IREG, and mark it as holding a GC ref.
238  */
239 guint32
240 mono_alloc_ireg_ref (MonoCompile *cfg)
241 {
242         return alloc_ireg_ref (cfg);
243 }
244
245 /*
246  * mono_alloc_ireg_mp:
247  *
248  *   Allocate an IREG, and mark it as holding a managed pointer.
249  */
250 guint32
251 mono_alloc_ireg_mp (MonoCompile *cfg)
252 {
253         return alloc_ireg_mp (cfg);
254 }
255
256 /*
257  * mono_alloc_ireg_copy:
258  *
259  *   Allocate an IREG with the same GC type as VREG.
260  */
261 guint32
262 mono_alloc_ireg_copy (MonoCompile *cfg, guint32 vreg)
263 {
264         if (vreg_is_ref (cfg, vreg))
265                 return alloc_ireg_ref (cfg);
266         else if (vreg_is_mp (cfg, vreg))
267                 return alloc_ireg_mp (cfg);
268         else
269                 return alloc_ireg (cfg);
270 }
271
272 guint
273 mono_type_to_regmove (MonoCompile *cfg, MonoType *type)
274 {
275         if (type->byref)
276                 return OP_MOVE;
277
278         type = mini_get_underlying_type (type);
279 handle_enum:
280         switch (type->type) {
281         case MONO_TYPE_I1:
282         case MONO_TYPE_U1:
283                 return OP_MOVE;
284         case MONO_TYPE_I2:
285         case MONO_TYPE_U2:
286                 return OP_MOVE;
287         case MONO_TYPE_I4:
288         case MONO_TYPE_U4:
289                 return OP_MOVE;
290         case MONO_TYPE_I:
291         case MONO_TYPE_U:
292         case MONO_TYPE_PTR:
293         case MONO_TYPE_FNPTR:
294                 return OP_MOVE;
295         case MONO_TYPE_CLASS:
296         case MONO_TYPE_STRING:
297         case MONO_TYPE_OBJECT:
298         case MONO_TYPE_SZARRAY:
299         case MONO_TYPE_ARRAY:    
300                 return OP_MOVE;
301         case MONO_TYPE_I8:
302         case MONO_TYPE_U8:
303 #if SIZEOF_REGISTER == 8
304                 return OP_MOVE;
305 #else
306                 return OP_LMOVE;
307 #endif
308         case MONO_TYPE_R4:
309                 return cfg->r4fp ? OP_RMOVE : OP_FMOVE;
310         case MONO_TYPE_R8:
311                 return OP_FMOVE;
312         case MONO_TYPE_VALUETYPE:
313                 if (type->data.klass->enumtype) {
314                         type = mono_class_enum_basetype (type->data.klass);
315                         goto handle_enum;
316                 }
317                 if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type (type)))
318                         return OP_XMOVE;
319                 return OP_VMOVE;
320         case MONO_TYPE_TYPEDBYREF:
321                 return OP_VMOVE;
322         case MONO_TYPE_GENERICINST:
323                 if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type (type)))
324                         return OP_XMOVE;
325                 type = &type->data.generic_class->container_class->byval_arg;
326                 goto handle_enum;
327         case MONO_TYPE_VAR:
328         case MONO_TYPE_MVAR:
329                 g_assert (cfg->gshared);
330                 if (mini_type_var_is_vt (type))
331                         return OP_VMOVE;
332                 else
333                         return mono_type_to_regmove (cfg, mini_get_underlying_type (type));
334         default:
335                 g_error ("unknown type 0x%02x in type_to_regstore", type->type);
336         }
337         return -1;
338 }
339
340 void
341 mono_print_bb (MonoBasicBlock *bb, const char *msg)
342 {
343         int i;
344         MonoInst *tree;
345         GString *str = g_string_new ("");
346
347         g_string_append_printf (str, "%s %d: [IN: ", msg, bb->block_num);
348         for (i = 0; i < bb->in_count; ++i)
349                 g_string_append_printf (str, " BB%d(%d)", bb->in_bb [i]->block_num, bb->in_bb [i]->dfn);
350         g_string_append_printf (str, ", OUT: ");
351         for (i = 0; i < bb->out_count; ++i)
352                 g_string_append_printf (str, " BB%d(%d)", bb->out_bb [i]->block_num, bb->out_bb [i]->dfn);
353         g_string_append_printf (str, " ]\n");
354
355         g_print ("%s", str->str);
356         g_string_free (str, TRUE);
357
358         for (tree = bb->code; tree; tree = tree->next)
359                 mono_print_ins_index (-1, tree);
360 }
361
362 void
363 mono_create_helper_signatures (void)
364 {
365         helper_sig_domain_get = mono_create_icall_signature ("ptr");
366         helper_sig_rgctx_lazy_fetch_trampoline = mono_create_icall_signature ("ptr ptr");
367         helper_sig_llvmonly_imt_trampoline = mono_create_icall_signature ("ptr ptr ptr");
368         helper_sig_jit_thread_attach = mono_create_icall_signature ("ptr ptr");
369         helper_sig_get_tls_tramp = mono_create_icall_signature ("ptr");
370         helper_sig_set_tls_tramp = mono_create_icall_signature ("void ptr");
371 }
372
373 static MONO_NEVER_INLINE void
374 break_on_unverified (void)
375 {
376         if (mini_get_debug_options ()->break_on_unverified)
377                 G_BREAKPOINT ();
378 }
379
380 static MONO_NEVER_INLINE void
381 field_access_failure (MonoCompile *cfg, MonoMethod *method, MonoClassField *field)
382 {
383         char *method_fname = mono_method_full_name (method, TRUE);
384         char *field_fname = mono_field_full_name (field);
385         mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
386         mono_error_set_generic_error (&cfg->error, "System", "FieldAccessException", "Field `%s' is inaccessible from method `%s'\n", field_fname, method_fname);
387         g_free (method_fname);
388         g_free (field_fname);
389 }
390
391 static MONO_NEVER_INLINE void
392 inline_failure (MonoCompile *cfg, const char *msg)
393 {
394         if (cfg->verbose_level >= 2)
395                 printf ("inline failed: %s\n", msg);
396         mono_cfg_set_exception (cfg, MONO_EXCEPTION_INLINE_FAILED);
397 }
398
399 static MONO_NEVER_INLINE void
400 gshared_failure (MonoCompile *cfg, int opcode, const char *file, int line)
401 {
402         if (cfg->verbose_level > 2)                                                                                     \
403                 printf ("sharing failed for method %s.%s.%s/%d opcode %s line %d\n", cfg->current_method->klass->name_space, cfg->current_method->klass->name, cfg->current_method->name, cfg->current_method->signature->param_count, mono_opcode_name ((opcode)), line);
404         mono_cfg_set_exception (cfg, MONO_EXCEPTION_GENERIC_SHARING_FAILED);
405 }
406
407 static MONO_NEVER_INLINE void
408 gsharedvt_failure (MonoCompile *cfg, int opcode, const char *file, int line)
409 {
410         cfg->exception_message = g_strdup_printf ("gsharedvt failed for method %s.%s.%s/%d opcode %s %s:%d", cfg->current_method->klass->name_space, cfg->current_method->klass->name, cfg->current_method->name, cfg->current_method->signature->param_count, mono_opcode_name ((opcode)), file, line);
411         if (cfg->verbose_level >= 2)
412                 printf ("%s\n", cfg->exception_message);
413         mono_cfg_set_exception (cfg, MONO_EXCEPTION_GENERIC_SHARING_FAILED);
414 }
415
416 /*
417  * When using gsharedvt, some instatiations might be verifiable, and some might be not. i.e. 
418  * foo<T> (int i) { ldarg.0; box T; }
419  */
420 #define UNVERIFIED do { \
421         if (cfg->gsharedvt) { \
422                 if (cfg->verbose_level > 2)                                                                     \
423                         printf ("gsharedvt method failed to verify, falling back to instantiation.\n"); \
424                 mono_cfg_set_exception (cfg, MONO_EXCEPTION_GENERIC_SHARING_FAILED); \
425                 goto exception_exit;                                                                                    \
426         }                                                                                                                                       \
427         break_on_unverified ();                                                                                         \
428         goto unverified;                                                                                                        \
429 } while (0)
430
431 #define GET_BBLOCK(cfg,tblock,ip) do {  \
432                 (tblock) = cfg->cil_offset_to_bb [(ip) - cfg->cil_start]; \
433                 if (!(tblock)) {        \
434                         if ((ip) >= end || (ip) < header->code) UNVERIFIED; \
435             NEW_BBLOCK (cfg, (tblock)); \
436                         (tblock)->cil_code = (ip);      \
437                         ADD_BBLOCK (cfg, (tblock));     \
438                 } \
439         } while (0)
440
441 #if defined(TARGET_X86) || defined(TARGET_AMD64)
442 #define EMIT_NEW_X86_LEA(cfg,dest,sr1,sr2,shift,imm) do { \
443                 MONO_INST_NEW (cfg, dest, OP_X86_LEA); \
444                 (dest)->dreg = alloc_ireg_mp ((cfg)); \
445                 (dest)->sreg1 = (sr1); \
446                 (dest)->sreg2 = (sr2); \
447                 (dest)->inst_imm = (imm); \
448                 (dest)->backend.shift_amount = (shift); \
449                 MONO_ADD_INS ((cfg)->cbb, (dest)); \
450         } while (0)
451 #endif
452
453 /* Emit conversions so both operands of a binary opcode are of the same type */
454 static void
455 add_widen_op (MonoCompile *cfg, MonoInst *ins, MonoInst **arg1_ref, MonoInst **arg2_ref)
456 {
457         MonoInst *arg1 = *arg1_ref;
458         MonoInst *arg2 = *arg2_ref;
459
460         if (cfg->r4fp &&
461                 ((arg1->type == STACK_R4 && arg2->type == STACK_R8) ||
462                  (arg1->type == STACK_R8 && arg2->type == STACK_R4))) {
463                 MonoInst *conv;
464
465                 /* Mixing r4/r8 is allowed by the spec */
466                 if (arg1->type == STACK_R4) {
467                         int dreg = alloc_freg (cfg);
468
469                         EMIT_NEW_UNALU (cfg, conv, OP_RCONV_TO_R8, dreg, arg1->dreg);
470                         conv->type = STACK_R8;
471                         ins->sreg1 = dreg;
472                         *arg1_ref = conv;
473                 }
474                 if (arg2->type == STACK_R4) {
475                         int dreg = alloc_freg (cfg);
476
477                         EMIT_NEW_UNALU (cfg, conv, OP_RCONV_TO_R8, dreg, arg2->dreg);
478                         conv->type = STACK_R8;
479                         ins->sreg2 = dreg;
480                         *arg2_ref = conv;
481                 }
482         }
483
484 #if SIZEOF_REGISTER == 8
485         /* FIXME: Need to add many more cases */
486         if ((arg1)->type == STACK_PTR && (arg2)->type == STACK_I4) {
487                 MonoInst *widen;
488
489                 int dr = alloc_preg (cfg);
490                 EMIT_NEW_UNALU (cfg, widen, OP_SEXT_I4, dr, (arg2)->dreg);
491                 (ins)->sreg2 = widen->dreg;
492         }
493 #endif
494 }
495
496 #define ADD_BINOP(op) do {      \
497                 MONO_INST_NEW (cfg, ins, (op)); \
498                 sp -= 2;        \
499                 ins->sreg1 = sp [0]->dreg;      \
500                 ins->sreg2 = sp [1]->dreg;      \
501                 type_from_op (cfg, ins, sp [0], sp [1]);        \
502                 CHECK_TYPE (ins);       \
503                 /* Have to insert a widening op */               \
504         add_widen_op (cfg, ins, &sp [0], &sp [1]);               \
505         ins->dreg = alloc_dreg ((cfg), (MonoStackType)(ins)->type); \
506         MONO_ADD_INS ((cfg)->cbb, (ins)); \
507         *sp++ = mono_decompose_opcode ((cfg), (ins));   \
508         } while (0)
509
510 #define ADD_UNOP(op) do {       \
511                 MONO_INST_NEW (cfg, ins, (op)); \
512                 sp--;   \
513                 ins->sreg1 = sp [0]->dreg;      \
514                 type_from_op (cfg, ins, sp [0], NULL);  \
515                 CHECK_TYPE (ins);       \
516         (ins)->dreg = alloc_dreg ((cfg), (MonoStackType)(ins)->type); \
517         MONO_ADD_INS ((cfg)->cbb, (ins)); \
518                 *sp++ = mono_decompose_opcode (cfg, ins);       \
519         } while (0)
520
521 #define ADD_BINCOND(next_block) do {    \
522                 MonoInst *cmp;  \
523                 sp -= 2; \
524                 MONO_INST_NEW(cfg, cmp, OP_COMPARE);    \
525                 cmp->sreg1 = sp [0]->dreg;      \
526                 cmp->sreg2 = sp [1]->dreg;      \
527                 type_from_op (cfg, cmp, sp [0], sp [1]);        \
528                 CHECK_TYPE (cmp);       \
529                 add_widen_op (cfg, cmp, &sp [0], &sp [1]);                                              \
530                 type_from_op (cfg, ins, sp [0], sp [1]);                                                        \
531                 ins->inst_many_bb = (MonoBasicBlock **)mono_mempool_alloc (cfg->mempool, sizeof(gpointer)*2);   \
532                 GET_BBLOCK (cfg, tblock, target);               \
533                 link_bblock (cfg, cfg->cbb, tblock);    \
534                 ins->inst_true_bb = tblock;     \
535                 if ((next_block)) {     \
536                         link_bblock (cfg, cfg->cbb, (next_block));      \
537                         ins->inst_false_bb = (next_block);      \
538                         start_new_bblock = 1;   \
539                 } else {        \
540                         GET_BBLOCK (cfg, tblock, ip);           \
541                         link_bblock (cfg, cfg->cbb, tblock);    \
542                         ins->inst_false_bb = tblock;    \
543                         start_new_bblock = 2;   \
544                 }       \
545                 if (sp != stack_start) {                                                                        \
546                     handle_stack_args (cfg, stack_start, sp - stack_start); \
547                         CHECK_UNVERIFIABLE (cfg); \
548                 } \
549         MONO_ADD_INS (cfg->cbb, cmp); \
550                 MONO_ADD_INS (cfg->cbb, ins);   \
551         } while (0)
552
553 /* *
554  * link_bblock: Links two basic blocks
555  *
556  * links two basic blocks in the control flow graph, the 'from'
557  * argument is the starting block and the 'to' argument is the block
558  * the control flow ends to after 'from'.
559  */
560 static void
561 link_bblock (MonoCompile *cfg, MonoBasicBlock *from, MonoBasicBlock* to)
562 {
563         MonoBasicBlock **newa;
564         int i, found;
565
566 #if 0
567         if (from->cil_code) {
568                 if (to->cil_code)
569                         printf ("edge from IL%04x to IL_%04x\n", from->cil_code - cfg->cil_code, to->cil_code - cfg->cil_code);
570                 else
571                         printf ("edge from IL%04x to exit\n", from->cil_code - cfg->cil_code);
572         } else {
573                 if (to->cil_code)
574                         printf ("edge from entry to IL_%04x\n", to->cil_code - cfg->cil_code);
575                 else
576                         printf ("edge from entry to exit\n");
577         }
578 #endif
579
580         found = FALSE;
581         for (i = 0; i < from->out_count; ++i) {
582                 if (to == from->out_bb [i]) {
583                         found = TRUE;
584                         break;
585                 }
586         }
587         if (!found) {
588                 newa = (MonoBasicBlock **)mono_mempool_alloc (cfg->mempool, sizeof (gpointer) * (from->out_count + 1));
589                 for (i = 0; i < from->out_count; ++i) {
590                         newa [i] = from->out_bb [i];
591                 }
592                 newa [i] = to;
593                 from->out_count++;
594                 from->out_bb = newa;
595         }
596
597         found = FALSE;
598         for (i = 0; i < to->in_count; ++i) {
599                 if (from == to->in_bb [i]) {
600                         found = TRUE;
601                         break;
602                 }
603         }
604         if (!found) {
605                 newa = (MonoBasicBlock **)mono_mempool_alloc (cfg->mempool, sizeof (gpointer) * (to->in_count + 1));
606                 for (i = 0; i < to->in_count; ++i) {
607                         newa [i] = to->in_bb [i];
608                 }
609                 newa [i] = from;
610                 to->in_count++;
611                 to->in_bb = newa;
612         }
613 }
614
615 void
616 mono_link_bblock (MonoCompile *cfg, MonoBasicBlock *from, MonoBasicBlock* to)
617 {
618         link_bblock (cfg, from, to);
619 }
620
621 /**
622  * mono_find_block_region:
623  *
624  *   We mark each basic block with a region ID. We use that to avoid BB
625  *   optimizations when blocks are in different regions.
626  *
627  * Returns:
628  *   A region token that encodes where this region is, and information
629  *   about the clause owner for this block.
630  *
631  *   The region encodes the try/catch/filter clause that owns this block
632  *   as well as the type.  -1 is a special value that represents a block
633  *   that is in none of try/catch/filter.
634  */
635 static int
636 mono_find_block_region (MonoCompile *cfg, int offset)
637 {
638         MonoMethodHeader *header = cfg->header;
639         MonoExceptionClause *clause;
640         int i;
641
642         for (i = 0; i < header->num_clauses; ++i) {
643                 clause = &header->clauses [i];
644                 if ((clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) && (offset >= clause->data.filter_offset) &&
645                     (offset < (clause->handler_offset)))
646                         return ((i + 1) << 8) | MONO_REGION_FILTER | clause->flags;
647                            
648                 if (MONO_OFFSET_IN_HANDLER (clause, offset)) {
649                         if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
650                                 return ((i + 1) << 8) | MONO_REGION_FINALLY | clause->flags;
651                         else if (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT)
652                                 return ((i + 1) << 8) | MONO_REGION_FAULT | clause->flags;
653                         else
654                                 return ((i + 1) << 8) | MONO_REGION_CATCH | clause->flags;
655                 }
656         }
657         for (i = 0; i < header->num_clauses; ++i) {
658                 clause = &header->clauses [i];
659
660                 if (MONO_OFFSET_IN_CLAUSE (clause, offset))
661                         return ((i + 1) << 8) | clause->flags;
662         }
663
664         return -1;
665 }
666
667 static gboolean
668 ip_in_finally_clause (MonoCompile *cfg, int offset)
669 {
670         MonoMethodHeader *header = cfg->header;
671         MonoExceptionClause *clause;
672         int i;
673
674         for (i = 0; i < header->num_clauses; ++i) {
675                 clause = &header->clauses [i];
676                 if (clause->flags != MONO_EXCEPTION_CLAUSE_FINALLY && clause->flags != MONO_EXCEPTION_CLAUSE_FAULT)
677                         continue;
678
679                 if (MONO_OFFSET_IN_HANDLER (clause, offset))
680                         return TRUE;
681         }
682         return FALSE;
683 }
684
685 static GList*
686 mono_find_final_block (MonoCompile *cfg, unsigned char *ip, unsigned char *target, int type)
687 {
688         MonoMethodHeader *header = cfg->header;
689         MonoExceptionClause *clause;
690         int i;
691         GList *res = NULL;
692
693         for (i = 0; i < header->num_clauses; ++i) {
694                 clause = &header->clauses [i];
695                 if (MONO_OFFSET_IN_CLAUSE (clause, (ip - header->code)) && 
696                     (!MONO_OFFSET_IN_CLAUSE (clause, (target - header->code)))) {
697                         if (clause->flags == type)
698                                 res = g_list_append (res, clause);
699                 }
700         }
701         return res;
702 }
703
704 static void
705 mono_create_spvar_for_region (MonoCompile *cfg, int region)
706 {
707         MonoInst *var;
708
709         var = (MonoInst *)g_hash_table_lookup (cfg->spvars, GINT_TO_POINTER (region));
710         if (var)
711                 return;
712
713         var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
714         /* prevent it from being register allocated */
715         var->flags |= MONO_INST_VOLATILE;
716
717         g_hash_table_insert (cfg->spvars, GINT_TO_POINTER (region), var);
718 }
719
720 MonoInst *
721 mono_find_exvar_for_offset (MonoCompile *cfg, int offset)
722 {
723         return (MonoInst *)g_hash_table_lookup (cfg->exvars, GINT_TO_POINTER (offset));
724 }
725
726 static MonoInst*
727 mono_create_exvar_for_offset (MonoCompile *cfg, int offset)
728 {
729         MonoInst *var;
730
731         var = (MonoInst *)g_hash_table_lookup (cfg->exvars, GINT_TO_POINTER (offset));
732         if (var)
733                 return var;
734
735         var = mono_compile_create_var (cfg, &mono_defaults.object_class->byval_arg, OP_LOCAL);
736         /* prevent it from being register allocated */
737         var->flags |= MONO_INST_VOLATILE;
738
739         g_hash_table_insert (cfg->exvars, GINT_TO_POINTER (offset), var);
740
741         return var;
742 }
743
744 /*
745  * Returns the type used in the eval stack when @type is loaded.
746  * FIXME: return a MonoType/MonoClass for the byref and VALUETYPE cases.
747  */
748 void
749 type_to_eval_stack_type (MonoCompile *cfg, MonoType *type, MonoInst *inst)
750 {
751         MonoClass *klass;
752
753         type = mini_get_underlying_type (type);
754         inst->klass = klass = mono_class_from_mono_type (type);
755         if (type->byref) {
756                 inst->type = STACK_MP;
757                 return;
758         }
759
760 handle_enum:
761         switch (type->type) {
762         case MONO_TYPE_VOID:
763                 inst->type = STACK_INV;
764                 return;
765         case MONO_TYPE_I1:
766         case MONO_TYPE_U1:
767         case MONO_TYPE_I2:
768         case MONO_TYPE_U2:
769         case MONO_TYPE_I4:
770         case MONO_TYPE_U4:
771                 inst->type = STACK_I4;
772                 return;
773         case MONO_TYPE_I:
774         case MONO_TYPE_U:
775         case MONO_TYPE_PTR:
776         case MONO_TYPE_FNPTR:
777                 inst->type = STACK_PTR;
778                 return;
779         case MONO_TYPE_CLASS:
780         case MONO_TYPE_STRING:
781         case MONO_TYPE_OBJECT:
782         case MONO_TYPE_SZARRAY:
783         case MONO_TYPE_ARRAY:    
784                 inst->type = STACK_OBJ;
785                 return;
786         case MONO_TYPE_I8:
787         case MONO_TYPE_U8:
788                 inst->type = STACK_I8;
789                 return;
790         case MONO_TYPE_R4:
791                 inst->type = cfg->r4_stack_type;
792                 break;
793         case MONO_TYPE_R8:
794                 inst->type = STACK_R8;
795                 return;
796         case MONO_TYPE_VALUETYPE:
797                 if (type->data.klass->enumtype) {
798                         type = mono_class_enum_basetype (type->data.klass);
799                         goto handle_enum;
800                 } else {
801                         inst->klass = klass;
802                         inst->type = STACK_VTYPE;
803                         return;
804                 }
805         case MONO_TYPE_TYPEDBYREF:
806                 inst->klass = mono_defaults.typed_reference_class;
807                 inst->type = STACK_VTYPE;
808                 return;
809         case MONO_TYPE_GENERICINST:
810                 type = &type->data.generic_class->container_class->byval_arg;
811                 goto handle_enum;
812         case MONO_TYPE_VAR:
813         case MONO_TYPE_MVAR:
814                 g_assert (cfg->gshared);
815                 if (mini_is_gsharedvt_type (type)) {
816                         g_assert (cfg->gsharedvt);
817                         inst->type = STACK_VTYPE;
818                 } else {
819                         type_to_eval_stack_type (cfg, mini_get_underlying_type (type), inst);
820                 }
821                 return;
822         default:
823                 g_error ("unknown type 0x%02x in eval stack type", type->type);
824         }
825 }
826
827 /*
828  * The following tables are used to quickly validate the IL code in type_from_op ().
829  */
830 static const char
831 bin_num_table [STACK_MAX] [STACK_MAX] = {
832         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
833         {STACK_INV, STACK_I4,  STACK_INV, STACK_PTR, STACK_INV, STACK_MP,  STACK_INV, STACK_INV},
834         {STACK_INV, STACK_INV, STACK_I8,  STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
835         {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_MP,  STACK_INV, STACK_INV},
836         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_R8,  STACK_INV, STACK_INV, STACK_INV, STACK_R8},
837         {STACK_INV, STACK_MP,  STACK_INV, STACK_MP,  STACK_INV, STACK_PTR, STACK_INV, STACK_INV},
838         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
839         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
840         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_R8, STACK_INV, STACK_INV, STACK_INV, STACK_R4}
841 };
842
843 static const char 
844 neg_table [] = {
845         STACK_INV, STACK_I4, STACK_I8, STACK_PTR, STACK_R8, STACK_INV, STACK_INV, STACK_INV, STACK_R4
846 };
847
848 /* reduce the size of this table */
849 static const char
850 bin_int_table [STACK_MAX] [STACK_MAX] = {
851         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
852         {STACK_INV, STACK_I4,  STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
853         {STACK_INV, STACK_INV, STACK_I8,  STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
854         {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
855         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
856         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
857         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
858         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
859 };
860
861 static const char
862 bin_comp_table [STACK_MAX] [STACK_MAX] = {
863 /*      Inv i  L  p  F  &  O  vt r4 */
864         {0},
865         {0, 1, 0, 1, 0, 0, 0, 0}, /* i, int32 */
866         {0, 0, 1, 0, 0, 0, 0, 0}, /* L, int64 */
867         {0, 1, 0, 1, 0, 2, 4, 0}, /* p, ptr */
868         {0, 0, 0, 0, 1, 0, 0, 0, 1}, /* F, R8 */
869         {0, 0, 0, 2, 0, 1, 0, 0}, /* &, managed pointer */
870         {0, 0, 0, 4, 0, 0, 3, 0}, /* O, reference */
871         {0, 0, 0, 0, 0, 0, 0, 0}, /* vt value type */
872         {0, 0, 0, 0, 1, 0, 0, 0, 1}, /* r, r4 */
873 };
874
875 /* reduce the size of this table */
876 static const char
877 shift_table [STACK_MAX] [STACK_MAX] = {
878         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
879         {STACK_INV, STACK_I4,  STACK_INV, STACK_I4,  STACK_INV, STACK_INV, STACK_INV, STACK_INV},
880         {STACK_INV, STACK_I8,  STACK_INV, STACK_I8,  STACK_INV, STACK_INV, STACK_INV, STACK_INV},
881         {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
882         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
883         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
884         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
885         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
886 };
887
888 /*
889  * Tables to map from the non-specific opcode to the matching
890  * type-specific opcode.
891  */
892 /* handles from CEE_ADD to CEE_SHR_UN (CEE_REM_UN for floats) */
893 static const guint16
894 binops_op_map [STACK_MAX] = {
895         0, OP_IADD-CEE_ADD, OP_LADD-CEE_ADD, OP_PADD-CEE_ADD, OP_FADD-CEE_ADD, OP_PADD-CEE_ADD, 0, 0, OP_RADD-CEE_ADD
896 };
897
898 /* handles from CEE_NEG to CEE_CONV_U8 */
899 static const guint16
900 unops_op_map [STACK_MAX] = {
901         0, OP_INEG-CEE_NEG, OP_LNEG-CEE_NEG, OP_PNEG-CEE_NEG, OP_FNEG-CEE_NEG, OP_PNEG-CEE_NEG, 0, 0, OP_RNEG-CEE_NEG
902 };
903
904 /* handles from CEE_CONV_U2 to CEE_SUB_OVF_UN */
905 static const guint16
906 ovfops_op_map [STACK_MAX] = {
907         0, OP_ICONV_TO_U2-CEE_CONV_U2, OP_LCONV_TO_U2-CEE_CONV_U2, OP_PCONV_TO_U2-CEE_CONV_U2, OP_FCONV_TO_U2-CEE_CONV_U2, OP_PCONV_TO_U2-CEE_CONV_U2, OP_PCONV_TO_U2-CEE_CONV_U2, 0, OP_RCONV_TO_U2-CEE_CONV_U2
908 };
909
910 /* handles from CEE_CONV_OVF_I1_UN to CEE_CONV_OVF_U_UN */
911 static const guint16
912 ovf2ops_op_map [STACK_MAX] = {
913         0, OP_ICONV_TO_OVF_I1_UN-CEE_CONV_OVF_I1_UN, OP_LCONV_TO_OVF_I1_UN-CEE_CONV_OVF_I1_UN, OP_PCONV_TO_OVF_I1_UN-CEE_CONV_OVF_I1_UN, OP_FCONV_TO_OVF_I1_UN-CEE_CONV_OVF_I1_UN, OP_PCONV_TO_OVF_I1_UN-CEE_CONV_OVF_I1_UN, 0, 0, OP_RCONV_TO_OVF_I1_UN-CEE_CONV_OVF_I1_UN
914 };
915
916 /* handles from CEE_CONV_OVF_I1 to CEE_CONV_OVF_U8 */
917 static const guint16
918 ovf3ops_op_map [STACK_MAX] = {
919         0, OP_ICONV_TO_OVF_I1-CEE_CONV_OVF_I1, OP_LCONV_TO_OVF_I1-CEE_CONV_OVF_I1, OP_PCONV_TO_OVF_I1-CEE_CONV_OVF_I1, OP_FCONV_TO_OVF_I1-CEE_CONV_OVF_I1, OP_PCONV_TO_OVF_I1-CEE_CONV_OVF_I1, 0, 0, OP_RCONV_TO_OVF_I1-CEE_CONV_OVF_I1
920 };
921
922 /* handles from CEE_BEQ to CEE_BLT_UN */
923 static const guint16
924 beqops_op_map [STACK_MAX] = {
925         0, OP_IBEQ-CEE_BEQ, OP_LBEQ-CEE_BEQ, OP_PBEQ-CEE_BEQ, OP_FBEQ-CEE_BEQ, OP_PBEQ-CEE_BEQ, OP_PBEQ-CEE_BEQ, 0, OP_FBEQ-CEE_BEQ
926 };
927
928 /* handles from CEE_CEQ to CEE_CLT_UN */
929 static const guint16
930 ceqops_op_map [STACK_MAX] = {
931         0, OP_ICEQ-OP_CEQ, OP_LCEQ-OP_CEQ, OP_PCEQ-OP_CEQ, OP_FCEQ-OP_CEQ, OP_PCEQ-OP_CEQ, OP_PCEQ-OP_CEQ, 0, OP_RCEQ-OP_CEQ
932 };
933
934 /*
935  * Sets ins->type (the type on the eval stack) according to the
936  * type of the opcode and the arguments to it.
937  * Invalid IL code is marked by setting ins->type to the invalid value STACK_INV.
938  *
939  * FIXME: this function sets ins->type unconditionally in some cases, but
940  * it should set it to invalid for some types (a conv.x on an object)
941  */
942 static void
943 type_from_op (MonoCompile *cfg, MonoInst *ins, MonoInst *src1, MonoInst *src2)
944 {
945         switch (ins->opcode) {
946         /* binops */
947         case CEE_ADD:
948         case CEE_SUB:
949         case CEE_MUL:
950         case CEE_DIV:
951         case CEE_REM:
952                 /* FIXME: check unverifiable args for STACK_MP */
953                 ins->type = bin_num_table [src1->type] [src2->type];
954                 ins->opcode += binops_op_map [ins->type];
955                 break;
956         case CEE_DIV_UN:
957         case CEE_REM_UN:
958         case CEE_AND:
959         case CEE_OR:
960         case CEE_XOR:
961                 ins->type = bin_int_table [src1->type] [src2->type];
962                 ins->opcode += binops_op_map [ins->type];
963                 break;
964         case CEE_SHL:
965         case CEE_SHR:
966         case CEE_SHR_UN:
967                 ins->type = shift_table [src1->type] [src2->type];
968                 ins->opcode += binops_op_map [ins->type];
969                 break;
970         case OP_COMPARE:
971         case OP_LCOMPARE:
972         case OP_ICOMPARE:
973                 ins->type = bin_comp_table [src1->type] [src2->type] ? STACK_I4: STACK_INV;
974                 if ((src1->type == STACK_I8) || ((SIZEOF_VOID_P == 8) && ((src1->type == STACK_PTR) || (src1->type == STACK_OBJ) || (src1->type == STACK_MP))))
975                         ins->opcode = OP_LCOMPARE;
976                 else if (src1->type == STACK_R4)
977                         ins->opcode = OP_RCOMPARE;
978                 else if (src1->type == STACK_R8)
979                         ins->opcode = OP_FCOMPARE;
980                 else
981                         ins->opcode = OP_ICOMPARE;
982                 break;
983         case OP_ICOMPARE_IMM:
984                 ins->type = bin_comp_table [src1->type] [src1->type] ? STACK_I4 : STACK_INV;
985                 if ((src1->type == STACK_I8) || ((SIZEOF_VOID_P == 8) && ((src1->type == STACK_PTR) || (src1->type == STACK_OBJ) || (src1->type == STACK_MP))))
986                         ins->opcode = OP_LCOMPARE_IMM;          
987                 break;
988         case CEE_BEQ:
989         case CEE_BGE:
990         case CEE_BGT:
991         case CEE_BLE:
992         case CEE_BLT:
993         case CEE_BNE_UN:
994         case CEE_BGE_UN:
995         case CEE_BGT_UN:
996         case CEE_BLE_UN:
997         case CEE_BLT_UN:
998                 ins->opcode += beqops_op_map [src1->type];
999                 break;
1000         case OP_CEQ:
1001                 ins->type = bin_comp_table [src1->type] [src2->type] ? STACK_I4: STACK_INV;
1002                 ins->opcode += ceqops_op_map [src1->type];
1003                 break;
1004         case OP_CGT:
1005         case OP_CGT_UN:
1006         case OP_CLT:
1007         case OP_CLT_UN:
1008                 ins->type = (bin_comp_table [src1->type] [src2->type] & 1) ? STACK_I4: STACK_INV;
1009                 ins->opcode += ceqops_op_map [src1->type];
1010                 break;
1011         /* unops */
1012         case CEE_NEG:
1013                 ins->type = neg_table [src1->type];
1014                 ins->opcode += unops_op_map [ins->type];
1015                 break;
1016         case CEE_NOT:
1017                 if (src1->type >= STACK_I4 && src1->type <= STACK_PTR)
1018                         ins->type = src1->type;
1019                 else
1020                         ins->type = STACK_INV;
1021                 ins->opcode += unops_op_map [ins->type];
1022                 break;
1023         case CEE_CONV_I1:
1024         case CEE_CONV_I2:
1025         case CEE_CONV_I4:
1026         case CEE_CONV_U4:
1027                 ins->type = STACK_I4;
1028                 ins->opcode += unops_op_map [src1->type];
1029                 break;
1030         case CEE_CONV_R_UN:
1031                 ins->type = STACK_R8;
1032                 switch (src1->type) {
1033                 case STACK_I4:
1034                 case STACK_PTR:
1035                         ins->opcode = OP_ICONV_TO_R_UN;
1036                         break;
1037                 case STACK_I8:
1038                         ins->opcode = OP_LCONV_TO_R_UN; 
1039                         break;
1040                 }
1041                 break;
1042         case CEE_CONV_OVF_I1:
1043         case CEE_CONV_OVF_U1:
1044         case CEE_CONV_OVF_I2:
1045         case CEE_CONV_OVF_U2:
1046         case CEE_CONV_OVF_I4:
1047         case CEE_CONV_OVF_U4:
1048                 ins->type = STACK_I4;
1049                 ins->opcode += ovf3ops_op_map [src1->type];
1050                 break;
1051         case CEE_CONV_OVF_I_UN:
1052         case CEE_CONV_OVF_U_UN:
1053                 ins->type = STACK_PTR;
1054                 ins->opcode += ovf2ops_op_map [src1->type];
1055                 break;
1056         case CEE_CONV_OVF_I1_UN:
1057         case CEE_CONV_OVF_I2_UN:
1058         case CEE_CONV_OVF_I4_UN:
1059         case CEE_CONV_OVF_U1_UN:
1060         case CEE_CONV_OVF_U2_UN:
1061         case CEE_CONV_OVF_U4_UN:
1062                 ins->type = STACK_I4;
1063                 ins->opcode += ovf2ops_op_map [src1->type];
1064                 break;
1065         case CEE_CONV_U:
1066                 ins->type = STACK_PTR;
1067                 switch (src1->type) {
1068                 case STACK_I4:
1069                         ins->opcode = OP_ICONV_TO_U;
1070                         break;
1071                 case STACK_PTR:
1072                 case STACK_MP:
1073 #if SIZEOF_VOID_P == 8
1074                         ins->opcode = OP_LCONV_TO_U;
1075 #else
1076                         ins->opcode = OP_MOVE;
1077 #endif
1078                         break;
1079                 case STACK_I8:
1080                         ins->opcode = OP_LCONV_TO_U;
1081                         break;
1082                 case STACK_R8:
1083                         ins->opcode = OP_FCONV_TO_U;
1084                         break;
1085                 }
1086                 break;
1087         case CEE_CONV_I8:
1088         case CEE_CONV_U8:
1089                 ins->type = STACK_I8;
1090                 ins->opcode += unops_op_map [src1->type];
1091                 break;
1092         case CEE_CONV_OVF_I8:
1093         case CEE_CONV_OVF_U8:
1094                 ins->type = STACK_I8;
1095                 ins->opcode += ovf3ops_op_map [src1->type];
1096                 break;
1097         case CEE_CONV_OVF_U8_UN:
1098         case CEE_CONV_OVF_I8_UN:
1099                 ins->type = STACK_I8;
1100                 ins->opcode += ovf2ops_op_map [src1->type];
1101                 break;
1102         case CEE_CONV_R4:
1103                 ins->type = cfg->r4_stack_type;
1104                 ins->opcode += unops_op_map [src1->type];
1105                 break;
1106         case CEE_CONV_R8:
1107                 ins->type = STACK_R8;
1108                 ins->opcode += unops_op_map [src1->type];
1109                 break;
1110         case OP_CKFINITE:
1111                 ins->type = STACK_R8;           
1112                 break;
1113         case CEE_CONV_U2:
1114         case CEE_CONV_U1:
1115                 ins->type = STACK_I4;
1116                 ins->opcode += ovfops_op_map [src1->type];
1117                 break;
1118         case CEE_CONV_I:
1119         case CEE_CONV_OVF_I:
1120         case CEE_CONV_OVF_U:
1121                 ins->type = STACK_PTR;
1122                 ins->opcode += ovfops_op_map [src1->type];
1123                 break;
1124         case CEE_ADD_OVF:
1125         case CEE_ADD_OVF_UN:
1126         case CEE_MUL_OVF:
1127         case CEE_MUL_OVF_UN:
1128         case CEE_SUB_OVF:
1129         case CEE_SUB_OVF_UN:
1130                 ins->type = bin_num_table [src1->type] [src2->type];
1131                 ins->opcode += ovfops_op_map [src1->type];
1132                 if (ins->type == STACK_R8)
1133                         ins->type = STACK_INV;
1134                 break;
1135         case OP_LOAD_MEMBASE:
1136                 ins->type = STACK_PTR;
1137                 break;
1138         case OP_LOADI1_MEMBASE:
1139         case OP_LOADU1_MEMBASE:
1140         case OP_LOADI2_MEMBASE:
1141         case OP_LOADU2_MEMBASE:
1142         case OP_LOADI4_MEMBASE:
1143         case OP_LOADU4_MEMBASE:
1144                 ins->type = STACK_PTR;
1145                 break;
1146         case OP_LOADI8_MEMBASE:
1147                 ins->type = STACK_I8;
1148                 break;
1149         case OP_LOADR4_MEMBASE:
1150                 ins->type = cfg->r4_stack_type;
1151                 break;
1152         case OP_LOADR8_MEMBASE:
1153                 ins->type = STACK_R8;
1154                 break;
1155         default:
1156                 g_error ("opcode 0x%04x not handled in type from op", ins->opcode);
1157                 break;
1158         }
1159
1160         if (ins->type == STACK_MP)
1161                 ins->klass = mono_defaults.object_class;
1162 }
1163
1164 static MonoClass*
1165 ldind_to_type (int op)
1166 {
1167         switch (op) {
1168         case CEE_LDIND_I1: return mono_defaults.sbyte_class;
1169         case CEE_LDIND_U1: return mono_defaults.byte_class;
1170         case CEE_LDIND_I2: return mono_defaults.int16_class;
1171         case CEE_LDIND_U2: return mono_defaults.uint16_class;
1172         case CEE_LDIND_I4: return mono_defaults.int32_class;
1173         case CEE_LDIND_U4: return mono_defaults.uint32_class;
1174         case CEE_LDIND_I8: return mono_defaults.int64_class;
1175         case CEE_LDIND_I: return mono_defaults.int_class;
1176         case CEE_LDIND_R4: return mono_defaults.single_class;
1177         case CEE_LDIND_R8: return mono_defaults.double_class;
1178         case CEE_LDIND_REF:return mono_defaults.object_class; //FIXME we should try to return a more specific type
1179         default: g_error ("Unknown ldind type %d", op);
1180         }
1181 }
1182
1183 #if 0
1184
1185 static const char
1186 param_table [STACK_MAX] [STACK_MAX] = {
1187         {0},
1188 };
1189
1190 static int
1191 check_values_to_signature (MonoInst *args, MonoType *this_ins, MonoMethodSignature *sig)
1192 {
1193         int i;
1194
1195         if (sig->hasthis) {
1196                 switch (args->type) {
1197                 case STACK_I4:
1198                 case STACK_I8:
1199                 case STACK_R8:
1200                 case STACK_VTYPE:
1201                 case STACK_INV:
1202                         return 0;
1203                 }
1204                 args++;
1205         }
1206         for (i = 0; i < sig->param_count; ++i) {
1207                 switch (args [i].type) {
1208                 case STACK_INV:
1209                         return 0;
1210                 case STACK_MP:
1211                         if (!sig->params [i]->byref)
1212                                 return 0;
1213                         continue;
1214                 case STACK_OBJ:
1215                         if (sig->params [i]->byref)
1216                                 return 0;
1217                         switch (sig->params [i]->type) {
1218                         case MONO_TYPE_CLASS:
1219                         case MONO_TYPE_STRING:
1220                         case MONO_TYPE_OBJECT:
1221                         case MONO_TYPE_SZARRAY:
1222                         case MONO_TYPE_ARRAY:
1223                                 break;
1224                         default:
1225                                 return 0;
1226                         }
1227                         continue;
1228                 case STACK_R8:
1229                         if (sig->params [i]->byref)
1230                                 return 0;
1231                         if (sig->params [i]->type != MONO_TYPE_R4 && sig->params [i]->type != MONO_TYPE_R8)
1232                                 return 0;
1233                         continue;
1234                 case STACK_PTR:
1235                 case STACK_I4:
1236                 case STACK_I8:
1237                 case STACK_VTYPE:
1238                         break;
1239                 }
1240                 /*if (!param_table [args [i].type] [sig->params [i]->type])
1241                         return 0;*/
1242         }
1243         return 1;
1244 }
1245 #endif
1246
1247 /*
1248  * When we need a pointer to the current domain many times in a method, we
1249  * call mono_domain_get() once and we store the result in a local variable.
1250  * This function returns the variable that represents the MonoDomain*.
1251  */
1252 inline static MonoInst *
1253 mono_get_domainvar (MonoCompile *cfg)
1254 {
1255         if (!cfg->domainvar)
1256                 cfg->domainvar = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1257         return cfg->domainvar;
1258 }
1259
1260 /*
1261  * The got_var contains the address of the Global Offset Table when AOT 
1262  * compiling.
1263  */
1264 MonoInst *
1265 mono_get_got_var (MonoCompile *cfg)
1266 {
1267         if (!cfg->compile_aot || !cfg->backend->need_got_var)
1268                 return NULL;
1269         if (!cfg->got_var) {
1270                 cfg->got_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1271         }
1272         return cfg->got_var;
1273 }
1274
1275 static void
1276 mono_create_rgctx_var (MonoCompile *cfg)
1277 {
1278         if (!cfg->rgctx_var) {
1279                 cfg->rgctx_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1280                 /* force the var to be stack allocated */
1281                 cfg->rgctx_var->flags |= MONO_INST_VOLATILE;
1282         }
1283 }
1284
1285 static MonoInst *
1286 mono_get_vtable_var (MonoCompile *cfg)
1287 {
1288         g_assert (cfg->gshared);
1289
1290         mono_create_rgctx_var (cfg);
1291
1292         return cfg->rgctx_var;
1293 }
1294
1295 static MonoType*
1296 type_from_stack_type (MonoInst *ins) {
1297         switch (ins->type) {
1298         case STACK_I4: return &mono_defaults.int32_class->byval_arg;
1299         case STACK_I8: return &mono_defaults.int64_class->byval_arg;
1300         case STACK_PTR: return &mono_defaults.int_class->byval_arg;
1301         case STACK_R4: return &mono_defaults.single_class->byval_arg;
1302         case STACK_R8: return &mono_defaults.double_class->byval_arg;
1303         case STACK_MP:
1304                 return &ins->klass->this_arg;
1305         case STACK_OBJ: return &mono_defaults.object_class->byval_arg;
1306         case STACK_VTYPE: return &ins->klass->byval_arg;
1307         default:
1308                 g_error ("stack type %d to monotype not handled\n", ins->type);
1309         }
1310         return NULL;
1311 }
1312
1313 static G_GNUC_UNUSED int
1314 type_to_stack_type (MonoCompile *cfg, MonoType *t)
1315 {
1316         t = mono_type_get_underlying_type (t);
1317         switch (t->type) {
1318         case MONO_TYPE_I1:
1319         case MONO_TYPE_U1:
1320         case MONO_TYPE_I2:
1321         case MONO_TYPE_U2:
1322         case MONO_TYPE_I4:
1323         case MONO_TYPE_U4:
1324                 return STACK_I4;
1325         case MONO_TYPE_I:
1326         case MONO_TYPE_U:
1327         case MONO_TYPE_PTR:
1328         case MONO_TYPE_FNPTR:
1329                 return STACK_PTR;
1330         case MONO_TYPE_CLASS:
1331         case MONO_TYPE_STRING:
1332         case MONO_TYPE_OBJECT:
1333         case MONO_TYPE_SZARRAY:
1334         case MONO_TYPE_ARRAY:    
1335                 return STACK_OBJ;
1336         case MONO_TYPE_I8:
1337         case MONO_TYPE_U8:
1338                 return STACK_I8;
1339         case MONO_TYPE_R4:
1340                 return cfg->r4_stack_type;
1341         case MONO_TYPE_R8:
1342                 return STACK_R8;
1343         case MONO_TYPE_VALUETYPE:
1344         case MONO_TYPE_TYPEDBYREF:
1345                 return STACK_VTYPE;
1346         case MONO_TYPE_GENERICINST:
1347                 if (mono_type_generic_inst_is_valuetype (t))
1348                         return STACK_VTYPE;
1349                 else
1350                         return STACK_OBJ;
1351                 break;
1352         default:
1353                 g_assert_not_reached ();
1354         }
1355
1356         return -1;
1357 }
1358
1359 static MonoClass*
1360 array_access_to_klass (int opcode)
1361 {
1362         switch (opcode) {
1363         case CEE_LDELEM_U1:
1364                 return mono_defaults.byte_class;
1365         case CEE_LDELEM_U2:
1366                 return mono_defaults.uint16_class;
1367         case CEE_LDELEM_I:
1368         case CEE_STELEM_I:
1369                 return mono_defaults.int_class;
1370         case CEE_LDELEM_I1:
1371         case CEE_STELEM_I1:
1372                 return mono_defaults.sbyte_class;
1373         case CEE_LDELEM_I2:
1374         case CEE_STELEM_I2:
1375                 return mono_defaults.int16_class;
1376         case CEE_LDELEM_I4:
1377         case CEE_STELEM_I4:
1378                 return mono_defaults.int32_class;
1379         case CEE_LDELEM_U4:
1380                 return mono_defaults.uint32_class;
1381         case CEE_LDELEM_I8:
1382         case CEE_STELEM_I8:
1383                 return mono_defaults.int64_class;
1384         case CEE_LDELEM_R4:
1385         case CEE_STELEM_R4:
1386                 return mono_defaults.single_class;
1387         case CEE_LDELEM_R8:
1388         case CEE_STELEM_R8:
1389                 return mono_defaults.double_class;
1390         case CEE_LDELEM_REF:
1391         case CEE_STELEM_REF:
1392                 return mono_defaults.object_class;
1393         default:
1394                 g_assert_not_reached ();
1395         }
1396         return NULL;
1397 }
1398
1399 /*
1400  * We try to share variables when possible
1401  */
1402 static MonoInst *
1403 mono_compile_get_interface_var (MonoCompile *cfg, int slot, MonoInst *ins)
1404 {
1405         MonoInst *res;
1406         int pos, vnum;
1407
1408         /* inlining can result in deeper stacks */ 
1409         if (slot >= cfg->header->max_stack)
1410                 return mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
1411
1412         pos = ins->type - 1 + slot * STACK_MAX;
1413
1414         switch (ins->type) {
1415         case STACK_I4:
1416         case STACK_I8:
1417         case STACK_R8:
1418         case STACK_PTR:
1419         case STACK_MP:
1420         case STACK_OBJ:
1421                 if ((vnum = cfg->intvars [pos]))
1422                         return cfg->varinfo [vnum];
1423                 res = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
1424                 cfg->intvars [pos] = res->inst_c0;
1425                 break;
1426         default:
1427                 res = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
1428         }
1429         return res;
1430 }
1431
1432 static void
1433 mono_save_token_info (MonoCompile *cfg, MonoImage *image, guint32 token, gpointer key)
1434 {
1435         /* 
1436          * Don't use this if a generic_context is set, since that means AOT can't
1437          * look up the method using just the image+token.
1438          * table == 0 means this is a reference made from a wrapper.
1439          */
1440         if (cfg->compile_aot && !cfg->generic_context && (mono_metadata_token_table (token) > 0)) {
1441                 MonoJumpInfoToken *jump_info_token = (MonoJumpInfoToken *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoJumpInfoToken));
1442                 jump_info_token->image = image;
1443                 jump_info_token->token = token;
1444                 g_hash_table_insert (cfg->token_info_hash, key, jump_info_token);
1445         }
1446 }
1447
1448 /*
1449  * This function is called to handle items that are left on the evaluation stack
1450  * at basic block boundaries. What happens is that we save the values to local variables
1451  * and we reload them later when first entering the target basic block (with the
1452  * handle_loaded_temps () function).
1453  * A single joint point will use the same variables (stored in the array bb->out_stack or
1454  * bb->in_stack, if the basic block is before or after the joint point).
1455  *
1456  * This function needs to be called _before_ emitting the last instruction of
1457  * the bb (i.e. before emitting a branch).
1458  * If the stack merge fails at a join point, cfg->unverifiable is set.
1459  */
1460 static void
1461 handle_stack_args (MonoCompile *cfg, MonoInst **sp, int count)
1462 {
1463         int i, bindex;
1464         MonoBasicBlock *bb = cfg->cbb;
1465         MonoBasicBlock *outb;
1466         MonoInst *inst, **locals;
1467         gboolean found;
1468
1469         if (!count)
1470                 return;
1471         if (cfg->verbose_level > 3)
1472                 printf ("%d item(s) on exit from B%d\n", count, bb->block_num);
1473         if (!bb->out_scount) {
1474                 bb->out_scount = count;
1475                 //printf ("bblock %d has out:", bb->block_num);
1476                 found = FALSE;
1477                 for (i = 0; i < bb->out_count; ++i) {
1478                         outb = bb->out_bb [i];
1479                         /* exception handlers are linked, but they should not be considered for stack args */
1480                         if (outb->flags & BB_EXCEPTION_HANDLER)
1481                                 continue;
1482                         //printf (" %d", outb->block_num);
1483                         if (outb->in_stack) {
1484                                 found = TRUE;
1485                                 bb->out_stack = outb->in_stack;
1486                                 break;
1487                         }
1488                 }
1489                 //printf ("\n");
1490                 if (!found) {
1491                         bb->out_stack = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * count);
1492                         for (i = 0; i < count; ++i) {
1493                                 /* 
1494                                  * try to reuse temps already allocated for this purpouse, if they occupy the same
1495                                  * stack slot and if they are of the same type.
1496                                  * This won't cause conflicts since if 'local' is used to 
1497                                  * store one of the values in the in_stack of a bblock, then
1498                                  * the same variable will be used for the same outgoing stack 
1499                                  * slot as well. 
1500                                  * This doesn't work when inlining methods, since the bblocks
1501                                  * in the inlined methods do not inherit their in_stack from
1502                                  * the bblock they are inlined to. See bug #58863 for an
1503                                  * example.
1504                                  */
1505                                 if (cfg->inlined_method)
1506                                         bb->out_stack [i] = mono_compile_create_var (cfg, type_from_stack_type (sp [i]), OP_LOCAL);
1507                                 else
1508                                         bb->out_stack [i] = mono_compile_get_interface_var (cfg, i, sp [i]);
1509                         }
1510                 }
1511         }
1512
1513         for (i = 0; i < bb->out_count; ++i) {
1514                 outb = bb->out_bb [i];
1515                 /* exception handlers are linked, but they should not be considered for stack args */
1516                 if (outb->flags & BB_EXCEPTION_HANDLER)
1517                         continue;
1518                 if (outb->in_scount) {
1519                         if (outb->in_scount != bb->out_scount) {
1520                                 cfg->unverifiable = TRUE;
1521                                 return;
1522                         }
1523                         continue; /* check they are the same locals */
1524                 }
1525                 outb->in_scount = count;
1526                 outb->in_stack = bb->out_stack;
1527         }
1528
1529         locals = bb->out_stack;
1530         cfg->cbb = bb;
1531         for (i = 0; i < count; ++i) {
1532                 EMIT_NEW_TEMPSTORE (cfg, inst, locals [i]->inst_c0, sp [i]);
1533                 inst->cil_code = sp [i]->cil_code;
1534                 sp [i] = locals [i];
1535                 if (cfg->verbose_level > 3)
1536                         printf ("storing %d to temp %d\n", i, (int)locals [i]->inst_c0);
1537         }
1538
1539         /*
1540          * It is possible that the out bblocks already have in_stack assigned, and
1541          * the in_stacks differ. In this case, we will store to all the different 
1542          * in_stacks.
1543          */
1544
1545         found = TRUE;
1546         bindex = 0;
1547         while (found) {
1548                 /* Find a bblock which has a different in_stack */
1549                 found = FALSE;
1550                 while (bindex < bb->out_count) {
1551                         outb = bb->out_bb [bindex];
1552                         /* exception handlers are linked, but they should not be considered for stack args */
1553                         if (outb->flags & BB_EXCEPTION_HANDLER) {
1554                                 bindex++;
1555                                 continue;
1556                         }
1557                         if (outb->in_stack != locals) {
1558                                 for (i = 0; i < count; ++i) {
1559                                         EMIT_NEW_TEMPSTORE (cfg, inst, outb->in_stack [i]->inst_c0, sp [i]);
1560                                         inst->cil_code = sp [i]->cil_code;
1561                                         sp [i] = locals [i];
1562                                         if (cfg->verbose_level > 3)
1563                                                 printf ("storing %d to temp %d\n", i, (int)outb->in_stack [i]->inst_c0);
1564                                 }
1565                                 locals = outb->in_stack;
1566                                 found = TRUE;
1567                                 break;
1568                         }
1569                         bindex ++;
1570                 }
1571         }
1572 }
1573
1574 MonoInst*
1575 mini_emit_runtime_constant (MonoCompile *cfg, MonoJumpInfoType patch_type, gpointer data)
1576 {
1577         MonoInst *ins;
1578
1579         if (cfg->compile_aot) {
1580                 EMIT_NEW_AOTCONST (cfg, ins, patch_type, data);
1581         } else {
1582                 MonoJumpInfo ji;
1583                 gpointer target;
1584                 MonoError error;
1585
1586                 ji.type = patch_type;
1587                 ji.data.target = data;
1588                 target = mono_resolve_patch_target (NULL, cfg->domain, NULL, &ji, FALSE, &error);
1589                 mono_error_assert_ok (&error);
1590
1591                 EMIT_NEW_PCONST (cfg, ins, target);
1592         }
1593         return ins;
1594 }
1595
1596 static MonoInst*
1597 mono_create_fast_tls_getter (MonoCompile *cfg, MonoTlsKey key)
1598 {
1599         int tls_offset = mono_tls_get_tls_offset (key);
1600
1601         if (cfg->compile_aot)
1602                 return NULL;
1603
1604         if (tls_offset != -1 && mono_arch_have_fast_tls ()) {
1605                 MonoInst *ins;
1606                 MONO_INST_NEW (cfg, ins, OP_TLS_GET);
1607                 ins->dreg = mono_alloc_preg (cfg);
1608                 ins->inst_offset = tls_offset;
1609                 return ins;
1610         }
1611         return NULL;
1612 }
1613
1614 static MonoInst*
1615 mono_create_fast_tls_setter (MonoCompile *cfg, MonoInst* value, MonoTlsKey key)
1616 {
1617         int tls_offset = mono_tls_get_tls_offset (key);
1618
1619         if (cfg->compile_aot)
1620                 return NULL;
1621
1622         if (tls_offset != -1 && mono_arch_have_fast_tls ()) {
1623                 MonoInst *ins;
1624                 MONO_INST_NEW (cfg, ins, OP_TLS_SET);
1625                 ins->sreg1 = value->dreg;
1626                 ins->inst_offset = tls_offset;
1627                 return ins;
1628         }
1629         return NULL;
1630 }
1631
1632
1633 MonoInst*
1634 mono_create_tls_get (MonoCompile *cfg, MonoTlsKey key)
1635 {
1636         MonoInst *fast_tls = NULL;
1637
1638         if (!mini_get_debug_options ()->use_fallback_tls)
1639                 fast_tls = mono_create_fast_tls_getter (cfg, key);
1640
1641         if (fast_tls) {
1642                 MONO_ADD_INS (cfg->cbb, fast_tls);
1643                 return fast_tls;
1644         }
1645
1646         if (cfg->compile_aot) {
1647                 MonoInst *addr;
1648                 /*
1649                  * tls getters are critical pieces of code and we don't want to resolve them
1650                  * through the standard plt/tramp mechanism since we might expose ourselves
1651                  * to crashes and infinite recursions.
1652                  */
1653                 EMIT_NEW_AOTCONST (cfg, addr, MONO_PATCH_INFO_GET_TLS_TRAMP, (void*)key);
1654                 return mini_emit_calli (cfg, helper_sig_get_tls_tramp, NULL, addr, NULL, NULL);
1655         } else {
1656                 gpointer getter = mono_tls_get_tls_getter (key, FALSE);
1657                 return mono_emit_jit_icall (cfg, getter, NULL);
1658         }
1659 }
1660
1661 static MonoInst*
1662 mono_create_tls_set (MonoCompile *cfg, MonoInst *value, MonoTlsKey key)
1663 {
1664         MonoInst *fast_tls = NULL;
1665
1666         if (!mini_get_debug_options ()->use_fallback_tls)
1667                 fast_tls = mono_create_fast_tls_setter (cfg, value, key);
1668
1669         if (fast_tls) {
1670                 MONO_ADD_INS (cfg->cbb, fast_tls);
1671                 return fast_tls;
1672         }
1673
1674         if (cfg->compile_aot) {
1675                 MonoInst *addr;
1676                 EMIT_NEW_AOTCONST (cfg, addr, MONO_PATCH_INFO_SET_TLS_TRAMP, (void*)key);
1677                 return mini_emit_calli (cfg, helper_sig_set_tls_tramp, &value, addr, NULL, NULL);
1678         } else {
1679                 gpointer setter = mono_tls_get_tls_setter (key, FALSE);
1680                 return mono_emit_jit_icall (cfg, setter, &value);
1681         }
1682 }
1683
1684 /*
1685  * emit_push_lmf:
1686  *
1687  *   Emit IR to push the current LMF onto the LMF stack.
1688  */
1689 static void
1690 emit_push_lmf (MonoCompile *cfg)
1691 {
1692         /*
1693          * Emit IR to push the LMF:
1694          * lmf_addr = <lmf_addr from tls>
1695          * lmf->lmf_addr = lmf_addr
1696          * lmf->prev_lmf = *lmf_addr
1697          * *lmf_addr = lmf
1698          */
1699         MonoInst *ins, *lmf_ins;
1700
1701         if (!cfg->lmf_ir)
1702                 return;
1703
1704         int lmf_reg, prev_lmf_reg;
1705         /*
1706          * Store lmf_addr in a variable, so it can be allocated to a global register.
1707          */
1708         if (!cfg->lmf_addr_var)
1709                 cfg->lmf_addr_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1710
1711 #ifdef HOST_WIN32
1712         ins = mono_create_tls_get (cfg, TLS_KEY_JIT_TLS);
1713         g_assert (ins);
1714         int jit_tls_dreg = ins->dreg;
1715
1716         lmf_reg = alloc_preg (cfg);
1717         EMIT_NEW_BIALU_IMM (cfg, lmf_ins, OP_PADD_IMM, lmf_reg, jit_tls_dreg, MONO_STRUCT_OFFSET (MonoJitTlsData, lmf));
1718 #else
1719         lmf_ins = mono_create_tls_get (cfg, TLS_KEY_LMF_ADDR);
1720         g_assert (lmf_ins);
1721 #endif
1722         lmf_ins->dreg = cfg->lmf_addr_var->dreg;
1723
1724         EMIT_NEW_VARLOADA (cfg, ins, cfg->lmf_var, NULL);
1725         lmf_reg = ins->dreg;
1726
1727         prev_lmf_reg = alloc_preg (cfg);
1728         /* Save previous_lmf */
1729         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, prev_lmf_reg, cfg->lmf_addr_var->dreg, 0);
1730         EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STORE_MEMBASE_REG, lmf_reg, MONO_STRUCT_OFFSET (MonoLMF, previous_lmf), prev_lmf_reg);
1731         /* Set new lmf */
1732         EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STORE_MEMBASE_REG, cfg->lmf_addr_var->dreg, 0, lmf_reg);
1733 }
1734
1735 /*
1736  * emit_pop_lmf:
1737  *
1738  *   Emit IR to pop the current LMF from the LMF stack.
1739  */
1740 static void
1741 emit_pop_lmf (MonoCompile *cfg)
1742 {
1743         int lmf_reg, lmf_addr_reg;
1744         MonoInst *ins;
1745
1746         if (!cfg->lmf_ir)
1747                 return;
1748
1749         EMIT_NEW_VARLOADA (cfg, ins, cfg->lmf_var, NULL);
1750         lmf_reg = ins->dreg;
1751
1752         int prev_lmf_reg;
1753         /*
1754          * Emit IR to pop the LMF:
1755          * *(lmf->lmf_addr) = lmf->prev_lmf
1756          */
1757         /* This could be called before emit_push_lmf () */
1758         if (!cfg->lmf_addr_var)
1759                 cfg->lmf_addr_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1760         lmf_addr_reg = cfg->lmf_addr_var->dreg;
1761
1762         prev_lmf_reg = alloc_preg (cfg);
1763         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, prev_lmf_reg, lmf_reg, MONO_STRUCT_OFFSET (MonoLMF, previous_lmf));
1764         EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STORE_MEMBASE_REG, lmf_addr_reg, 0, prev_lmf_reg);
1765 }
1766
1767 static void
1768 emit_instrumentation_call (MonoCompile *cfg, void *func)
1769 {
1770         MonoInst *iargs [1];
1771
1772         /*
1773          * Avoid instrumenting inlined methods since it can
1774          * distort profiling results.
1775          */
1776         if (cfg->method != cfg->current_method)
1777                 return;
1778
1779         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE) {
1780                 EMIT_NEW_METHODCONST (cfg, iargs [0], cfg->method);
1781                 mono_emit_jit_icall (cfg, func, iargs);
1782         }
1783 }
1784
1785 static int
1786 ret_type_to_call_opcode (MonoCompile *cfg, MonoType *type, int calli, int virt)
1787 {
1788 handle_enum:
1789         type = mini_get_underlying_type (type);
1790         switch (type->type) {
1791         case MONO_TYPE_VOID:
1792                 return calli? OP_VOIDCALL_REG: virt? OP_VOIDCALL_MEMBASE: OP_VOIDCALL;
1793         case MONO_TYPE_I1:
1794         case MONO_TYPE_U1:
1795         case MONO_TYPE_I2:
1796         case MONO_TYPE_U2:
1797         case MONO_TYPE_I4:
1798         case MONO_TYPE_U4:
1799                 return calli? OP_CALL_REG: virt? OP_CALL_MEMBASE: OP_CALL;
1800         case MONO_TYPE_I:
1801         case MONO_TYPE_U:
1802         case MONO_TYPE_PTR:
1803         case MONO_TYPE_FNPTR:
1804                 return calli? OP_CALL_REG: virt? OP_CALL_MEMBASE: OP_CALL;
1805         case MONO_TYPE_CLASS:
1806         case MONO_TYPE_STRING:
1807         case MONO_TYPE_OBJECT:
1808         case MONO_TYPE_SZARRAY:
1809         case MONO_TYPE_ARRAY:    
1810                 return calli? OP_CALL_REG: virt? OP_CALL_MEMBASE: OP_CALL;
1811         case MONO_TYPE_I8:
1812         case MONO_TYPE_U8:
1813                 return calli? OP_LCALL_REG: virt? OP_LCALL_MEMBASE: OP_LCALL;
1814         case MONO_TYPE_R4:
1815                 if (cfg->r4fp)
1816                         return calli? OP_RCALL_REG: virt? OP_RCALL_MEMBASE: OP_RCALL;
1817                 else
1818                         return calli? OP_FCALL_REG: virt? OP_FCALL_MEMBASE: OP_FCALL;
1819         case MONO_TYPE_R8:
1820                 return calli? OP_FCALL_REG: virt? OP_FCALL_MEMBASE: OP_FCALL;
1821         case MONO_TYPE_VALUETYPE:
1822                 if (type->data.klass->enumtype) {
1823                         type = mono_class_enum_basetype (type->data.klass);
1824                         goto handle_enum;
1825                 } else
1826                         return calli? OP_VCALL_REG: virt? OP_VCALL_MEMBASE: OP_VCALL;
1827         case MONO_TYPE_TYPEDBYREF:
1828                 return calli? OP_VCALL_REG: virt? OP_VCALL_MEMBASE: OP_VCALL;
1829         case MONO_TYPE_GENERICINST:
1830                 type = &type->data.generic_class->container_class->byval_arg;
1831                 goto handle_enum;
1832         case MONO_TYPE_VAR:
1833         case MONO_TYPE_MVAR:
1834                 /* gsharedvt */
1835                 return calli? OP_VCALL_REG: virt? OP_VCALL_MEMBASE: OP_VCALL;
1836         default:
1837                 g_error ("unknown type 0x%02x in ret_type_to_call_opcode", type->type);
1838         }
1839         return -1;
1840 }
1841
1842 //XXX this ignores if t is byref
1843 #define MONO_TYPE_IS_PRIMITIVE_SCALAR(t) ((((((t)->type >= MONO_TYPE_BOOLEAN && (t)->type <= MONO_TYPE_U8) || ((t)->type >= MONO_TYPE_I && (t)->type <= MONO_TYPE_U)))))
1844
1845 /*
1846  * target_type_is_incompatible:
1847  * @cfg: MonoCompile context
1848  *
1849  * Check that the item @arg on the evaluation stack can be stored
1850  * in the target type (can be a local, or field, etc).
1851  * The cfg arg can be used to check if we need verification or just
1852  * validity checks.
1853  *
1854  * Returns: non-0 value if arg can't be stored on a target.
1855  */
1856 static int
1857 target_type_is_incompatible (MonoCompile *cfg, MonoType *target, MonoInst *arg)
1858 {
1859         MonoType *simple_type;
1860         MonoClass *klass;
1861
1862         if (target->byref) {
1863                 /* FIXME: check that the pointed to types match */
1864                 if (arg->type == STACK_MP) {
1865                         /* This is needed to handle gshared types + ldaddr. We lower the types so we can handle enums and other typedef-like types. */
1866                         MonoClass *target_class_lowered = mono_class_from_mono_type (mini_get_underlying_type (&mono_class_from_mono_type (target)->byval_arg));
1867                         MonoClass *source_class_lowered = mono_class_from_mono_type (mini_get_underlying_type (&arg->klass->byval_arg));
1868
1869                         /* if the target is native int& or same type */
1870                         if (target->type == MONO_TYPE_I || target_class_lowered == source_class_lowered)
1871                                 return 0;
1872
1873                         /* Both are primitive type byrefs and the source points to a larger type that the destination */
1874                         if (MONO_TYPE_IS_PRIMITIVE_SCALAR (&target_class_lowered->byval_arg) && MONO_TYPE_IS_PRIMITIVE_SCALAR (&source_class_lowered->byval_arg) &&
1875                                 mono_class_instance_size (target_class_lowered) <= mono_class_instance_size (source_class_lowered))
1876                                 return 0;
1877                         return 1;
1878                 }
1879                 if (arg->type == STACK_PTR)
1880                         return 0;
1881                 return 1;
1882         }
1883
1884         simple_type = mini_get_underlying_type (target);
1885         switch (simple_type->type) {
1886         case MONO_TYPE_VOID:
1887                 return 1;
1888         case MONO_TYPE_I1:
1889         case MONO_TYPE_U1:
1890         case MONO_TYPE_I2:
1891         case MONO_TYPE_U2:
1892         case MONO_TYPE_I4:
1893         case MONO_TYPE_U4:
1894                 if (arg->type != STACK_I4 && arg->type != STACK_PTR)
1895                         return 1;
1896                 return 0;
1897         case MONO_TYPE_PTR:
1898                 /* STACK_MP is needed when setting pinned locals */
1899                 if (arg->type != STACK_I4 && arg->type != STACK_PTR && arg->type != STACK_MP)
1900                         return 1;
1901                 return 0;
1902         case MONO_TYPE_I:
1903         case MONO_TYPE_U:
1904         case MONO_TYPE_FNPTR:
1905                 /* 
1906                  * Some opcodes like ldloca returns 'transient pointers' which can be stored in
1907                  * in native int. (#688008).
1908                  */
1909                 if (arg->type != STACK_I4 && arg->type != STACK_PTR && arg->type != STACK_MP)
1910                         return 1;
1911                 return 0;
1912         case MONO_TYPE_CLASS:
1913         case MONO_TYPE_STRING:
1914         case MONO_TYPE_OBJECT:
1915         case MONO_TYPE_SZARRAY:
1916         case MONO_TYPE_ARRAY:    
1917                 if (arg->type != STACK_OBJ)
1918                         return 1;
1919                 /* FIXME: check type compatibility */
1920                 return 0;
1921         case MONO_TYPE_I8:
1922         case MONO_TYPE_U8:
1923                 if (arg->type != STACK_I8)
1924                         return 1;
1925                 return 0;
1926         case MONO_TYPE_R4:
1927                 if (arg->type != cfg->r4_stack_type)
1928                         return 1;
1929                 return 0;
1930         case MONO_TYPE_R8:
1931                 if (arg->type != STACK_R8)
1932                         return 1;
1933                 return 0;
1934         case MONO_TYPE_VALUETYPE:
1935                 if (arg->type != STACK_VTYPE)
1936                         return 1;
1937                 klass = mono_class_from_mono_type (simple_type);
1938                 if (klass != arg->klass)
1939                         return 1;
1940                 return 0;
1941         case MONO_TYPE_TYPEDBYREF:
1942                 if (arg->type != STACK_VTYPE)
1943                         return 1;
1944                 klass = mono_class_from_mono_type (simple_type);
1945                 if (klass != arg->klass)
1946                         return 1;
1947                 return 0;
1948         case MONO_TYPE_GENERICINST:
1949                 if (mono_type_generic_inst_is_valuetype (simple_type)) {
1950                         MonoClass *target_class;
1951                         if (arg->type != STACK_VTYPE)
1952                                 return 1;
1953                         klass = mono_class_from_mono_type (simple_type);
1954                         target_class = mono_class_from_mono_type (target);
1955                         /* The second cases is needed when doing partial sharing */
1956                         if (klass != arg->klass && target_class != arg->klass && target_class != mono_class_from_mono_type (mini_get_underlying_type (&arg->klass->byval_arg)))
1957                                 return 1;
1958                         return 0;
1959                 } else {
1960                         if (arg->type != STACK_OBJ)
1961                                 return 1;
1962                         /* FIXME: check type compatibility */
1963                         return 0;
1964                 }
1965         case MONO_TYPE_VAR:
1966         case MONO_TYPE_MVAR:
1967                 g_assert (cfg->gshared);
1968                 if (mini_type_var_is_vt (simple_type)) {
1969                         if (arg->type != STACK_VTYPE)
1970                                 return 1;
1971                 } else {
1972                         if (arg->type != STACK_OBJ)
1973                                 return 1;
1974                 }
1975                 return 0;
1976         default:
1977                 g_error ("unknown type 0x%02x in target_type_is_incompatible", simple_type->type);
1978         }
1979         return 1;
1980 }
1981
1982 /*
1983  * Prepare arguments for passing to a function call.
1984  * Return a non-zero value if the arguments can't be passed to the given
1985  * signature.
1986  * The type checks are not yet complete and some conversions may need
1987  * casts on 32 or 64 bit architectures.
1988  *
1989  * FIXME: implement this using target_type_is_incompatible ()
1990  */
1991 static int
1992 check_call_signature (MonoCompile *cfg, MonoMethodSignature *sig, MonoInst **args)
1993 {
1994         MonoType *simple_type;
1995         int i;
1996
1997         if (sig->hasthis) {
1998                 if (args [0]->type != STACK_OBJ && args [0]->type != STACK_MP && args [0]->type != STACK_PTR)
1999                         return 1;
2000                 args++;
2001         }
2002         for (i = 0; i < sig->param_count; ++i) {
2003                 if (sig->params [i]->byref) {
2004                         if (args [i]->type != STACK_MP && args [i]->type != STACK_PTR)
2005                                 return 1;
2006                         continue;
2007                 }
2008                 simple_type = mini_get_underlying_type (sig->params [i]);
2009 handle_enum:
2010                 switch (simple_type->type) {
2011                 case MONO_TYPE_VOID:
2012                         return 1;
2013                         continue;
2014                 case MONO_TYPE_I1:
2015                 case MONO_TYPE_U1:
2016                 case MONO_TYPE_I2:
2017                 case MONO_TYPE_U2:
2018                 case MONO_TYPE_I4:
2019                 case MONO_TYPE_U4:
2020                         if (args [i]->type != STACK_I4 && args [i]->type != STACK_PTR)
2021                                 return 1;
2022                         continue;
2023                 case MONO_TYPE_I:
2024                 case MONO_TYPE_U:
2025                 case MONO_TYPE_PTR:
2026                 case MONO_TYPE_FNPTR:
2027                         if (args [i]->type != STACK_I4 && args [i]->type != STACK_PTR && args [i]->type != STACK_MP && args [i]->type != STACK_OBJ)
2028                                 return 1;
2029                         continue;
2030                 case MONO_TYPE_CLASS:
2031                 case MONO_TYPE_STRING:
2032                 case MONO_TYPE_OBJECT:
2033                 case MONO_TYPE_SZARRAY:
2034                 case MONO_TYPE_ARRAY:    
2035                         if (args [i]->type != STACK_OBJ)
2036                                 return 1;
2037                         continue;
2038                 case MONO_TYPE_I8:
2039                 case MONO_TYPE_U8:
2040                         if (args [i]->type != STACK_I8)
2041                                 return 1;
2042                         continue;
2043                 case MONO_TYPE_R4:
2044                         if (args [i]->type != cfg->r4_stack_type)
2045                                 return 1;
2046                         continue;
2047                 case MONO_TYPE_R8:
2048                         if (args [i]->type != STACK_R8)
2049                                 return 1;
2050                         continue;
2051                 case MONO_TYPE_VALUETYPE:
2052                         if (simple_type->data.klass->enumtype) {
2053                                 simple_type = mono_class_enum_basetype (simple_type->data.klass);
2054                                 goto handle_enum;
2055                         }
2056                         if (args [i]->type != STACK_VTYPE)
2057                                 return 1;
2058                         continue;
2059                 case MONO_TYPE_TYPEDBYREF:
2060                         if (args [i]->type != STACK_VTYPE)
2061                                 return 1;
2062                         continue;
2063                 case MONO_TYPE_GENERICINST:
2064                         simple_type = &simple_type->data.generic_class->container_class->byval_arg;
2065                         goto handle_enum;
2066                 case MONO_TYPE_VAR:
2067                 case MONO_TYPE_MVAR:
2068                         /* gsharedvt */
2069                         if (args [i]->type != STACK_VTYPE)
2070                                 return 1;
2071                         continue;
2072                 default:
2073                         g_error ("unknown type 0x%02x in check_call_signature",
2074                                  simple_type->type);
2075                 }
2076         }
2077         return 0;
2078 }
2079
2080 static int
2081 callvirt_to_call (int opcode)
2082 {
2083         switch (opcode) {
2084         case OP_CALL_MEMBASE:
2085                 return OP_CALL;
2086         case OP_VOIDCALL_MEMBASE:
2087                 return OP_VOIDCALL;
2088         case OP_FCALL_MEMBASE:
2089                 return OP_FCALL;
2090         case OP_RCALL_MEMBASE:
2091                 return OP_RCALL;
2092         case OP_VCALL_MEMBASE:
2093                 return OP_VCALL;
2094         case OP_LCALL_MEMBASE:
2095                 return OP_LCALL;
2096         default:
2097                 g_assert_not_reached ();
2098         }
2099
2100         return -1;
2101 }
2102
2103 static int
2104 callvirt_to_call_reg (int opcode)
2105 {
2106         switch (opcode) {
2107         case OP_CALL_MEMBASE:
2108                 return OP_CALL_REG;
2109         case OP_VOIDCALL_MEMBASE:
2110                 return OP_VOIDCALL_REG;
2111         case OP_FCALL_MEMBASE:
2112                 return OP_FCALL_REG;
2113         case OP_RCALL_MEMBASE:
2114                 return OP_RCALL_REG;
2115         case OP_VCALL_MEMBASE:
2116                 return OP_VCALL_REG;
2117         case OP_LCALL_MEMBASE:
2118                 return OP_LCALL_REG;
2119         default:
2120                 g_assert_not_reached ();
2121         }
2122
2123         return -1;
2124 }
2125
2126 /* Either METHOD or IMT_ARG needs to be set */
2127 static void
2128 emit_imt_argument (MonoCompile *cfg, MonoCallInst *call, MonoMethod *method, MonoInst *imt_arg)
2129 {
2130         int method_reg;
2131
2132         if (COMPILE_LLVM (cfg)) {
2133                 if (imt_arg) {
2134                         method_reg = alloc_preg (cfg);
2135                         MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, method_reg, imt_arg->dreg);
2136                 } else {
2137                         MonoInst *ins = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_METHODCONST, method);
2138                         method_reg = ins->dreg;
2139                 }
2140
2141 #ifdef ENABLE_LLVM
2142                 call->imt_arg_reg = method_reg;
2143 #endif
2144                 mono_call_inst_add_outarg_reg (cfg, call, method_reg, MONO_ARCH_IMT_REG, FALSE);
2145                 return;
2146         }
2147
2148         if (imt_arg) {
2149                 method_reg = alloc_preg (cfg);
2150                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, method_reg, imt_arg->dreg);
2151         } else {
2152                 MonoInst *ins = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_METHODCONST, method);
2153                 method_reg = ins->dreg;
2154         }
2155
2156         mono_call_inst_add_outarg_reg (cfg, call, method_reg, MONO_ARCH_IMT_REG, FALSE);
2157 }
2158
2159 static MonoJumpInfo *
2160 mono_patch_info_new (MonoMemPool *mp, int ip, MonoJumpInfoType type, gconstpointer target)
2161 {
2162         MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc (mp, sizeof (MonoJumpInfo));
2163
2164         ji->ip.i = ip;
2165         ji->type = type;
2166         ji->data.target = target;
2167
2168         return ji;
2169 }
2170
2171 int
2172 mini_class_check_context_used (MonoCompile *cfg, MonoClass *klass)
2173 {
2174         if (cfg->gshared)
2175                 return mono_class_check_context_used (klass);
2176         else
2177                 return 0;
2178 }
2179
2180 static int
2181 mini_method_check_context_used (MonoCompile *cfg, MonoMethod *method)
2182 {
2183         if (cfg->gshared)
2184                 return mono_method_check_context_used (method);
2185         else
2186                 return 0;
2187 }
2188
2189 /*
2190  * check_method_sharing:
2191  *
2192  *   Check whenever the vtable or an mrgctx needs to be passed when calling CMETHOD.
2193  */
2194 static void
2195 check_method_sharing (MonoCompile *cfg, MonoMethod *cmethod, gboolean *out_pass_vtable, gboolean *out_pass_mrgctx)
2196 {
2197         gboolean pass_vtable = FALSE;
2198         gboolean pass_mrgctx = FALSE;
2199
2200         if (((cmethod->flags & METHOD_ATTRIBUTE_STATIC) || cmethod->klass->valuetype) &&
2201                 (mono_class_is_ginst (cmethod->klass) || mono_class_is_gtd (cmethod->klass))) {
2202                 gboolean sharable = FALSE;
2203
2204                 if (mono_method_is_generic_sharable_full (cmethod, TRUE, TRUE, TRUE))
2205                         sharable = TRUE;
2206
2207                 /*
2208                  * Pass vtable iff target method might
2209                  * be shared, which means that sharing
2210                  * is enabled for its class and its
2211                  * context is sharable (and it's not a
2212                  * generic method).
2213                  */
2214                 if (sharable && !(mini_method_get_context (cmethod) && mini_method_get_context (cmethod)->method_inst))
2215                         pass_vtable = TRUE;
2216         }
2217
2218         if (mini_method_get_context (cmethod) &&
2219                 mini_method_get_context (cmethod)->method_inst) {
2220                 g_assert (!pass_vtable);
2221
2222                 if (mono_method_is_generic_sharable_full (cmethod, TRUE, TRUE, TRUE)) {
2223                         pass_mrgctx = TRUE;
2224                 } else {
2225                         if (cfg->gsharedvt && mini_is_gsharedvt_signature (mono_method_signature (cmethod)))
2226                                 pass_mrgctx = TRUE;
2227                 }
2228         }
2229
2230         if (out_pass_vtable)
2231                 *out_pass_vtable = pass_vtable;
2232         if (out_pass_mrgctx)
2233                 *out_pass_mrgctx = pass_mrgctx;
2234 }
2235
2236 inline static MonoCallInst *
2237 mono_emit_call_args (MonoCompile *cfg, MonoMethodSignature *sig, 
2238                                          MonoInst **args, int calli, int virtual_, int tail, int rgctx, int unbox_trampoline)
2239 {
2240         MonoType *sig_ret;
2241         MonoCallInst *call;
2242 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
2243         int i;
2244 #endif
2245
2246         if (cfg->llvm_only)
2247                 tail = FALSE;
2248
2249         if (tail) {
2250                 emit_instrumentation_call (cfg, mono_profiler_method_leave);
2251
2252                 MONO_INST_NEW_CALL (cfg, call, OP_TAILCALL);
2253         } else
2254                 MONO_INST_NEW_CALL (cfg, call, ret_type_to_call_opcode (cfg, sig->ret, calli, virtual_));
2255
2256         call->args = args;
2257         call->signature = sig;
2258         call->rgctx_reg = rgctx;
2259         sig_ret = mini_get_underlying_type (sig->ret);
2260
2261         type_to_eval_stack_type ((cfg), sig_ret, &call->inst);
2262
2263         if (tail) {
2264                 if (mini_type_is_vtype (sig_ret)) {
2265                         call->vret_var = cfg->vret_addr;
2266                         //g_assert_not_reached ();
2267                 }
2268         } else if (mini_type_is_vtype (sig_ret)) {
2269                 MonoInst *temp = mono_compile_create_var (cfg, sig_ret, OP_LOCAL);
2270                 MonoInst *loada;
2271
2272                 temp->backend.is_pinvoke = sig->pinvoke;
2273
2274                 /*
2275                  * We use a new opcode OP_OUTARG_VTRETADDR instead of LDADDR for emitting the
2276                  * address of return value to increase optimization opportunities.
2277                  * Before vtype decomposition, the dreg of the call ins itself represents the
2278                  * fact the call modifies the return value. After decomposition, the call will
2279                  * be transformed into one of the OP_VOIDCALL opcodes, and the VTRETADDR opcode
2280                  * will be transformed into an LDADDR.
2281                  */
2282                 MONO_INST_NEW (cfg, loada, OP_OUTARG_VTRETADDR);
2283                 loada->dreg = alloc_preg (cfg);
2284                 loada->inst_p0 = temp;
2285                 /* We reference the call too since call->dreg could change during optimization */
2286                 loada->inst_p1 = call;
2287                 MONO_ADD_INS (cfg->cbb, loada);
2288
2289                 call->inst.dreg = temp->dreg;
2290
2291                 call->vret_var = loada;
2292         } else if (!MONO_TYPE_IS_VOID (sig_ret))
2293                 call->inst.dreg = alloc_dreg (cfg, (MonoStackType)call->inst.type);
2294
2295 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
2296         if (COMPILE_SOFT_FLOAT (cfg)) {
2297                 /* 
2298                  * If the call has a float argument, we would need to do an r8->r4 conversion using 
2299                  * an icall, but that cannot be done during the call sequence since it would clobber
2300                  * the call registers + the stack. So we do it before emitting the call.
2301                  */
2302                 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
2303                         MonoType *t;
2304                         MonoInst *in = call->args [i];
2305
2306                         if (i >= sig->hasthis)
2307                                 t = sig->params [i - sig->hasthis];
2308                         else
2309                                 t = &mono_defaults.int_class->byval_arg;
2310                         t = mono_type_get_underlying_type (t);
2311
2312                         if (!t->byref && t->type == MONO_TYPE_R4) {
2313                                 MonoInst *iargs [1];
2314                                 MonoInst *conv;
2315
2316                                 iargs [0] = in;
2317                                 conv = mono_emit_jit_icall (cfg, mono_fload_r4_arg, iargs);
2318
2319                                 /* The result will be in an int vreg */
2320                                 call->args [i] = conv;
2321                         }
2322                 }
2323         }
2324 #endif
2325
2326         call->need_unbox_trampoline = unbox_trampoline;
2327
2328 #ifdef ENABLE_LLVM
2329         if (COMPILE_LLVM (cfg))
2330                 mono_llvm_emit_call (cfg, call);
2331         else
2332                 mono_arch_emit_call (cfg, call);
2333 #else
2334         mono_arch_emit_call (cfg, call);
2335 #endif
2336
2337         cfg->param_area = MAX (cfg->param_area, call->stack_usage);
2338         cfg->flags |= MONO_CFG_HAS_CALLS;
2339         
2340         return call;
2341 }
2342
2343 static void
2344 set_rgctx_arg (MonoCompile *cfg, MonoCallInst *call, int rgctx_reg, MonoInst *rgctx_arg)
2345 {
2346         mono_call_inst_add_outarg_reg (cfg, call, rgctx_reg, MONO_ARCH_RGCTX_REG, FALSE);
2347         cfg->uses_rgctx_reg = TRUE;
2348         call->rgctx_reg = TRUE;
2349 #ifdef ENABLE_LLVM
2350         call->rgctx_arg_reg = rgctx_reg;
2351 #endif
2352 }       
2353
2354 MonoInst*
2355 mini_emit_calli (MonoCompile *cfg, MonoMethodSignature *sig, MonoInst **args, MonoInst *addr, MonoInst *imt_arg, MonoInst *rgctx_arg)
2356 {
2357         MonoCallInst *call;
2358         MonoInst *ins;
2359         int rgctx_reg = -1;
2360         gboolean check_sp = FALSE;
2361
2362         if (cfg->check_pinvoke_callconv && cfg->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
2363                 WrapperInfo *info = mono_marshal_get_wrapper_info (cfg->method);
2364
2365                 if (info && info->subtype == WRAPPER_SUBTYPE_PINVOKE)
2366                         check_sp = TRUE;
2367         }
2368
2369         if (rgctx_arg) {
2370                 rgctx_reg = mono_alloc_preg (cfg);
2371                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, rgctx_reg, rgctx_arg->dreg);
2372         }
2373
2374         if (check_sp) {
2375                 if (!cfg->stack_inbalance_var)
2376                         cfg->stack_inbalance_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
2377
2378                 MONO_INST_NEW (cfg, ins, OP_GET_SP);
2379                 ins->dreg = cfg->stack_inbalance_var->dreg;
2380                 MONO_ADD_INS (cfg->cbb, ins);
2381         }
2382
2383         call = mono_emit_call_args (cfg, sig, args, TRUE, FALSE, FALSE, rgctx_arg ? TRUE : FALSE, FALSE);
2384
2385         call->inst.sreg1 = addr->dreg;
2386
2387         if (imt_arg)
2388                 emit_imt_argument (cfg, call, NULL, imt_arg);
2389
2390         MONO_ADD_INS (cfg->cbb, (MonoInst*)call);
2391
2392         if (check_sp) {
2393                 int sp_reg;
2394
2395                 sp_reg = mono_alloc_preg (cfg);
2396
2397                 MONO_INST_NEW (cfg, ins, OP_GET_SP);
2398                 ins->dreg = sp_reg;
2399                 MONO_ADD_INS (cfg->cbb, ins);
2400
2401                 /* Restore the stack so we don't crash when throwing the exception */
2402                 MONO_INST_NEW (cfg, ins, OP_SET_SP);
2403                 ins->sreg1 = cfg->stack_inbalance_var->dreg;
2404                 MONO_ADD_INS (cfg->cbb, ins);
2405
2406                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, cfg->stack_inbalance_var->dreg, sp_reg);
2407                 MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "ExecutionEngineException");
2408         }
2409
2410         if (rgctx_arg)
2411                 set_rgctx_arg (cfg, call, rgctx_reg, rgctx_arg);
2412
2413         return (MonoInst*)call;
2414 }
2415
2416 static MonoInst*
2417 emit_get_rgctx_method (MonoCompile *cfg, int context_used, MonoMethod *cmethod, MonoRgctxInfoType rgctx_type);
2418
2419 static MonoInst*
2420 mono_emit_method_call_full (MonoCompile *cfg, MonoMethod *method, MonoMethodSignature *sig, gboolean tail,
2421                                                         MonoInst **args, MonoInst *this_ins, MonoInst *imt_arg, MonoInst *rgctx_arg)
2422 {
2423 #ifndef DISABLE_REMOTING
2424         gboolean might_be_remote = FALSE;
2425 #endif
2426         gboolean virtual_ = this_ins != NULL;
2427         gboolean enable_for_aot = TRUE;
2428         int context_used;
2429         MonoCallInst *call;
2430         MonoInst *call_target = NULL;
2431         int rgctx_reg = 0;
2432         gboolean need_unbox_trampoline;
2433
2434         if (!sig)
2435                 sig = mono_method_signature (method);
2436
2437         if (cfg->llvm_only && (mono_class_is_interface (method->klass)))
2438                 g_assert_not_reached ();
2439
2440         if (rgctx_arg) {
2441                 rgctx_reg = mono_alloc_preg (cfg);
2442                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, rgctx_reg, rgctx_arg->dreg);
2443         }
2444
2445         if (method->string_ctor) {
2446                 /* Create the real signature */
2447                 /* FIXME: Cache these */
2448                 MonoMethodSignature *ctor_sig = mono_metadata_signature_dup_mempool (cfg->mempool, sig);
2449                 ctor_sig->ret = &mono_defaults.string_class->byval_arg;
2450
2451                 sig = ctor_sig;
2452         }
2453
2454         context_used = mini_method_check_context_used (cfg, method);
2455
2456 #ifndef DISABLE_REMOTING
2457         might_be_remote = this_ins && sig->hasthis &&
2458                 (mono_class_is_marshalbyref (method->klass) || method->klass == mono_defaults.object_class) &&
2459                 !(method->flags & METHOD_ATTRIBUTE_VIRTUAL) && (!MONO_CHECK_THIS (this_ins) || context_used);
2460
2461         if (might_be_remote && context_used) {
2462                 MonoInst *addr;
2463
2464                 g_assert (cfg->gshared);
2465
2466                 addr = emit_get_rgctx_method (cfg, context_used, method, MONO_RGCTX_INFO_REMOTING_INVOKE_WITH_CHECK);
2467
2468                 return mini_emit_calli (cfg, sig, args, addr, NULL, NULL);
2469         }
2470 #endif
2471
2472         if (cfg->llvm_only && !call_target && virtual_ && (method->flags & METHOD_ATTRIBUTE_VIRTUAL))
2473                 return emit_llvmonly_virtual_call (cfg, method, sig, 0, args);
2474
2475         need_unbox_trampoline = method->klass == mono_defaults.object_class || mono_class_is_interface (method->klass);
2476
2477         call = mono_emit_call_args (cfg, sig, args, FALSE, virtual_, tail, rgctx_arg ? TRUE : FALSE, need_unbox_trampoline);
2478
2479 #ifndef DISABLE_REMOTING
2480         if (might_be_remote)
2481                 call->method = mono_marshal_get_remoting_invoke_with_check (method);
2482         else
2483 #endif
2484                 call->method = method;
2485         call->inst.flags |= MONO_INST_HAS_METHOD;
2486         call->inst.inst_left = this_ins;
2487         call->tail_call = tail;
2488
2489         if (virtual_) {
2490                 int vtable_reg, slot_reg, this_reg;
2491                 int offset;
2492
2493                 this_reg = this_ins->dreg;
2494
2495                 if (!cfg->llvm_only && (method->klass->parent == mono_defaults.multicastdelegate_class) && !strcmp (method->name, "Invoke")) {
2496                         MonoInst *dummy_use;
2497
2498                         MONO_EMIT_NULL_CHECK (cfg, this_reg);
2499
2500                         /* Make a call to delegate->invoke_impl */
2501                         call->inst.inst_basereg = this_reg;
2502                         call->inst.inst_offset = MONO_STRUCT_OFFSET (MonoDelegate, invoke_impl);
2503                         MONO_ADD_INS (cfg->cbb, (MonoInst*)call);
2504
2505                         /* We must emit a dummy use here because the delegate trampoline will
2506                         replace the 'this' argument with the delegate target making this activation
2507                         no longer a root for the delegate.
2508                         This is an issue for delegates that target collectible code such as dynamic
2509                         methods of GC'able assemblies.
2510
2511                         For a test case look into #667921.
2512
2513                         FIXME: a dummy use is not the best way to do it as the local register allocator
2514                         will put it on a caller save register and spil it around the call. 
2515                         Ideally, we would either put it on a callee save register or only do the store part.  
2516                          */
2517                         EMIT_NEW_DUMMY_USE (cfg, dummy_use, args [0]);
2518
2519                         return (MonoInst*)call;
2520                 }
2521
2522                 if ((!cfg->compile_aot || enable_for_aot) && 
2523                         (!(method->flags & METHOD_ATTRIBUTE_VIRTUAL) || 
2524                          (MONO_METHOD_IS_FINAL (method) &&
2525                           method->wrapper_type != MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)) &&
2526                         !(mono_class_is_marshalbyref (method->klass) && context_used)) {
2527                         /* 
2528                          * the method is not virtual, we just need to ensure this is not null
2529                          * and then we can call the method directly.
2530                          */
2531 #ifndef DISABLE_REMOTING
2532                         if (mono_class_is_marshalbyref (method->klass) || method->klass == mono_defaults.object_class) {
2533                                 /* 
2534                                  * The check above ensures method is not gshared, this is needed since
2535                                  * gshared methods can't have wrappers.
2536                                  */
2537                                 method = call->method = mono_marshal_get_remoting_invoke_with_check (method);
2538                         }
2539 #endif
2540
2541                         if (!method->string_ctor)
2542                                 MONO_EMIT_NEW_CHECK_THIS (cfg, this_reg);
2543
2544                         call->inst.opcode = callvirt_to_call (call->inst.opcode);
2545                 } else if ((method->flags & METHOD_ATTRIBUTE_VIRTUAL) && MONO_METHOD_IS_FINAL (method)) {
2546                         /*
2547                          * the method is virtual, but we can statically dispatch since either
2548                          * it's class or the method itself are sealed.
2549                          * But first we need to ensure it's not a null reference.
2550                          */
2551                         MONO_EMIT_NEW_CHECK_THIS (cfg, this_reg);
2552
2553                         call->inst.opcode = callvirt_to_call (call->inst.opcode);
2554                 } else if (call_target) {
2555                         vtable_reg = alloc_preg (cfg);
2556                         MONO_EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, vtable_reg, this_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
2557
2558                         call->inst.opcode = callvirt_to_call_reg (call->inst.opcode);
2559                         call->inst.sreg1 = call_target->dreg;
2560                         call->inst.flags &= !MONO_INST_HAS_METHOD;
2561                 } else {
2562                         vtable_reg = alloc_preg (cfg);
2563                         MONO_EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, vtable_reg, this_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
2564                         if (mono_class_is_interface (method->klass)) {
2565                                 guint32 imt_slot = mono_method_get_imt_slot (method);
2566                                 emit_imt_argument (cfg, call, call->method, imt_arg);
2567                                 slot_reg = vtable_reg;
2568                                 offset = ((gint32)imt_slot - MONO_IMT_SIZE) * SIZEOF_VOID_P;
2569                         } else {
2570                                 slot_reg = vtable_reg;
2571                                 offset = MONO_STRUCT_OFFSET (MonoVTable, vtable) +
2572                                         ((mono_method_get_vtable_index (method)) * (SIZEOF_VOID_P));
2573                                 if (imt_arg) {
2574                                         g_assert (mono_method_signature (method)->generic_param_count);
2575                                         emit_imt_argument (cfg, call, call->method, imt_arg);
2576                                 }
2577                         }
2578
2579                         call->inst.sreg1 = slot_reg;
2580                         call->inst.inst_offset = offset;
2581                         call->is_virtual = TRUE;
2582                 }
2583         }
2584
2585         MONO_ADD_INS (cfg->cbb, (MonoInst*)call);
2586
2587         if (rgctx_arg)
2588                 set_rgctx_arg (cfg, call, rgctx_reg, rgctx_arg);
2589
2590         return (MonoInst*)call;
2591 }
2592
2593 MonoInst*
2594 mono_emit_method_call (MonoCompile *cfg, MonoMethod *method, MonoInst **args, MonoInst *this_ins)
2595 {
2596         return mono_emit_method_call_full (cfg, method, mono_method_signature (method), FALSE, args, this_ins, NULL, NULL);
2597 }
2598
2599 MonoInst*
2600 mono_emit_native_call (MonoCompile *cfg, gconstpointer func, MonoMethodSignature *sig,
2601                                            MonoInst **args)
2602 {
2603         MonoCallInst *call;
2604
2605         g_assert (sig);
2606
2607         call = mono_emit_call_args (cfg, sig, args, FALSE, FALSE, FALSE, FALSE, FALSE);
2608         call->fptr = func;
2609
2610         MONO_ADD_INS (cfg->cbb, (MonoInst*)call);
2611
2612         return (MonoInst*)call;
2613 }
2614
2615 MonoInst*
2616 mono_emit_jit_icall (MonoCompile *cfg, gconstpointer func, MonoInst **args)
2617 {
2618         MonoJitICallInfo *info = mono_find_jit_icall_by_addr (func);
2619
2620         g_assert (info);
2621
2622         return mono_emit_native_call (cfg, mono_icall_get_wrapper (info), info->sig, args);
2623 }
2624
2625 /*
2626  * mono_emit_abs_call:
2627  *
2628  *   Emit a call to the runtime function described by PATCH_TYPE and DATA.
2629  */
2630 inline static MonoInst*
2631 mono_emit_abs_call (MonoCompile *cfg, MonoJumpInfoType patch_type, gconstpointer data, 
2632                                         MonoMethodSignature *sig, MonoInst **args)
2633 {
2634         MonoJumpInfo *ji = mono_patch_info_new (cfg->mempool, 0, patch_type, data);
2635         MonoInst *ins;
2636
2637         /* 
2638          * We pass ji as the call address, the PATCH_INFO_ABS resolving code will
2639          * handle it.
2640          */
2641         if (cfg->abs_patches == NULL)
2642                 cfg->abs_patches = g_hash_table_new (NULL, NULL);
2643         g_hash_table_insert (cfg->abs_patches, ji, ji);
2644         ins = mono_emit_native_call (cfg, ji, sig, args);
2645         ((MonoCallInst*)ins)->fptr_is_patch = TRUE;
2646         return ins;
2647 }
2648
2649 static MonoMethodSignature*
2650 sig_to_rgctx_sig (MonoMethodSignature *sig)
2651 {
2652         // FIXME: memory allocation
2653         MonoMethodSignature *res;
2654         int i;
2655
2656         res = (MonoMethodSignature *)g_malloc (MONO_SIZEOF_METHOD_SIGNATURE + (sig->param_count + 1) * sizeof (MonoType*));
2657         memcpy (res, sig, MONO_SIZEOF_METHOD_SIGNATURE);
2658         res->param_count = sig->param_count + 1;
2659         for (i = 0; i < sig->param_count; ++i)
2660                 res->params [i] = sig->params [i];
2661         res->params [sig->param_count] = &mono_defaults.int_class->this_arg;
2662         return res;
2663 }
2664
2665 /* Make an indirect call to FSIG passing an additional argument */
2666 static MonoInst*
2667 emit_extra_arg_calli (MonoCompile *cfg, MonoMethodSignature *fsig, MonoInst **orig_args, int arg_reg, MonoInst *call_target)
2668 {
2669         MonoMethodSignature *csig;
2670         MonoInst *args_buf [16];
2671         MonoInst **args;
2672         int i, pindex, tmp_reg;
2673
2674         /* Make a call with an rgctx/extra arg */
2675         if (fsig->param_count + 2 < 16)
2676                 args = args_buf;
2677         else
2678                 args = (MonoInst **)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst*) * (fsig->param_count + 2));
2679         pindex = 0;
2680         if (fsig->hasthis)
2681                 args [pindex ++] = orig_args [0];
2682         for (i = 0; i < fsig->param_count; ++i)
2683                 args [pindex ++] = orig_args [fsig->hasthis + i];
2684         tmp_reg = alloc_preg (cfg);
2685         EMIT_NEW_UNALU (cfg, args [pindex], OP_MOVE, tmp_reg, arg_reg);
2686         csig = sig_to_rgctx_sig (fsig);
2687         return mini_emit_calli (cfg, csig, args, call_target, NULL, NULL);
2688 }
2689
2690 /* Emit an indirect call to the function descriptor ADDR */
2691 static MonoInst*
2692 emit_llvmonly_calli (MonoCompile *cfg, MonoMethodSignature *fsig, MonoInst **args, MonoInst *addr)
2693 {
2694         int addr_reg, arg_reg;
2695         MonoInst *call_target;
2696
2697         g_assert (cfg->llvm_only);
2698
2699         /*
2700          * addr points to a <addr, arg> pair, load both of them, and
2701          * make a call to addr, passing arg as an extra arg.
2702          */
2703         addr_reg = alloc_preg (cfg);
2704         EMIT_NEW_LOAD_MEMBASE (cfg, call_target, OP_LOAD_MEMBASE, addr_reg, addr->dreg, 0);
2705         arg_reg = alloc_preg (cfg);
2706         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, arg_reg, addr->dreg, sizeof (gpointer));
2707
2708         return emit_extra_arg_calli (cfg, fsig, args, arg_reg, call_target);
2709 }
2710
2711 static gboolean
2712 direct_icalls_enabled (MonoCompile *cfg)
2713 {
2714         return FALSE;
2715
2716         /* LLVM on amd64 can't handle calls to non-32 bit addresses */
2717 #ifdef TARGET_AMD64
2718         if (cfg->compile_llvm && !cfg->llvm_only)
2719                 return FALSE;
2720 #endif
2721         if (cfg->gen_sdb_seq_points || cfg->disable_direct_icalls)
2722                 return FALSE;
2723         return TRUE;
2724 }
2725
2726 MonoInst*
2727 mono_emit_jit_icall_by_info (MonoCompile *cfg, int il_offset, MonoJitICallInfo *info, MonoInst **args)
2728 {
2729         /*
2730          * Call the jit icall without a wrapper if possible.
2731          * The wrapper is needed for the following reasons:
2732          * - to handle exceptions thrown using mono_raise_exceptions () from the
2733          *   icall function. The EH code needs the lmf frame pushed by the
2734          *   wrapper to be able to unwind back to managed code.
2735          * - to be able to do stack walks for asynchronously suspended
2736          *   threads when debugging.
2737          */
2738         if (info->no_raise && direct_icalls_enabled (cfg)) {
2739                 char *name;
2740                 int costs;
2741
2742                 if (!info->wrapper_method) {
2743                         name = g_strdup_printf ("__icall_wrapper_%s", info->name);
2744                         info->wrapper_method = mono_marshal_get_icall_wrapper (info->sig, name, info->func, TRUE);
2745                         g_free (name);
2746                         mono_memory_barrier ();
2747                 }
2748
2749                 /*
2750                  * Inline the wrapper method, which is basically a call to the C icall, and
2751                  * an exception check.
2752                  */
2753                 costs = inline_method (cfg, info->wrapper_method, NULL,
2754                                                            args, NULL, il_offset, TRUE);
2755                 g_assert (costs > 0);
2756                 g_assert (!MONO_TYPE_IS_VOID (info->sig->ret));
2757
2758                 return args [0];
2759         } else {
2760                 return mono_emit_native_call (cfg, mono_icall_get_wrapper (info), info->sig, args);
2761         }
2762 }
2763  
2764 static MonoInst*
2765 mono_emit_widen_call_res (MonoCompile *cfg, MonoInst *ins, MonoMethodSignature *fsig)
2766 {
2767         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
2768                 if ((fsig->pinvoke || LLVM_ENABLED) && !fsig->ret->byref) {
2769                         int widen_op = -1;
2770
2771                         /* 
2772                          * Native code might return non register sized integers 
2773                          * without initializing the upper bits.
2774                          */
2775                         switch (mono_type_to_load_membase (cfg, fsig->ret)) {
2776                         case OP_LOADI1_MEMBASE:
2777                                 widen_op = OP_ICONV_TO_I1;
2778                                 break;
2779                         case OP_LOADU1_MEMBASE:
2780                                 widen_op = OP_ICONV_TO_U1;
2781                                 break;
2782                         case OP_LOADI2_MEMBASE:
2783                                 widen_op = OP_ICONV_TO_I2;
2784                                 break;
2785                         case OP_LOADU2_MEMBASE:
2786                                 widen_op = OP_ICONV_TO_U2;
2787                                 break;
2788                         default:
2789                                 break;
2790                         }
2791
2792                         if (widen_op != -1) {
2793                                 int dreg = alloc_preg (cfg);
2794                                 MonoInst *widen;
2795
2796                                 EMIT_NEW_UNALU (cfg, widen, widen_op, dreg, ins->dreg);
2797                                 widen->type = ins->type;
2798                                 ins = widen;
2799                         }
2800                 }
2801         }
2802
2803         return ins;
2804 }
2805
2806
2807 static void
2808 emit_method_access_failure (MonoCompile *cfg, MonoMethod *caller, MonoMethod *callee)
2809 {
2810         MonoInst *args [16];
2811
2812         args [0] = emit_get_rgctx_method (cfg, mono_method_check_context_used (caller), caller, MONO_RGCTX_INFO_METHOD);
2813         args [1] = emit_get_rgctx_method (cfg, mono_method_check_context_used (callee), callee, MONO_RGCTX_INFO_METHOD);
2814
2815         mono_emit_jit_icall (cfg, mono_throw_method_access, args);
2816 }
2817
2818 MonoMethod*
2819 mini_get_memcpy_method (void)
2820 {
2821         static MonoMethod *memcpy_method = NULL;
2822         if (!memcpy_method) {
2823                 memcpy_method = mono_class_get_method_from_name (mono_defaults.string_class, "memcpy", 3);
2824                 if (!memcpy_method)
2825                         g_error ("Old corlib found. Install a new one");
2826         }
2827         return memcpy_method;
2828 }
2829
2830 static void
2831 create_write_barrier_bitmap (MonoCompile *cfg, MonoClass *klass, unsigned *wb_bitmap, int offset)
2832 {
2833         MonoClassField *field;
2834         gpointer iter = NULL;
2835
2836         while ((field = mono_class_get_fields (klass, &iter))) {
2837                 int foffset;
2838
2839                 if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
2840                         continue;
2841                 foffset = klass->valuetype ? field->offset - sizeof (MonoObject): field->offset;
2842                 if (mini_type_is_reference (mono_field_get_type (field))) {
2843                         g_assert ((foffset % SIZEOF_VOID_P) == 0);
2844                         *wb_bitmap |= 1 << ((offset + foffset) / SIZEOF_VOID_P);
2845                 } else {
2846                         MonoClass *field_class = mono_class_from_mono_type (field->type);
2847                         if (field_class->has_references)
2848                                 create_write_barrier_bitmap (cfg, field_class, wb_bitmap, offset + foffset);
2849                 }
2850         }
2851 }
2852
2853 void
2854 mini_emit_write_barrier (MonoCompile *cfg, MonoInst *ptr, MonoInst *value)
2855 {
2856         int card_table_shift_bits;
2857         gpointer card_table_mask;
2858         guint8 *card_table;
2859         MonoInst *dummy_use;
2860         int nursery_shift_bits;
2861         size_t nursery_size;
2862
2863         if (!cfg->gen_write_barriers)
2864                 return;
2865
2866         card_table = mono_gc_get_card_table (&card_table_shift_bits, &card_table_mask);
2867
2868         mono_gc_get_nursery (&nursery_shift_bits, &nursery_size);
2869
2870         if (cfg->backend->have_card_table_wb && !cfg->compile_aot && card_table && nursery_shift_bits > 0 && !COMPILE_LLVM (cfg)) {
2871                 MonoInst *wbarrier;
2872
2873                 MONO_INST_NEW (cfg, wbarrier, OP_CARD_TABLE_WBARRIER);
2874                 wbarrier->sreg1 = ptr->dreg;
2875                 wbarrier->sreg2 = value->dreg;
2876                 MONO_ADD_INS (cfg->cbb, wbarrier);
2877         } else if (card_table) {
2878                 int offset_reg = alloc_preg (cfg);
2879                 int card_reg;
2880                 MonoInst *ins;
2881
2882                 /*
2883                  * We emit a fast light weight write barrier. This always marks cards as in the concurrent
2884                  * collector case, so, for the serial collector, it might slightly slow down nursery
2885                  * collections. We also expect that the host system and the target system have the same card
2886                  * table configuration, which is the case if they have the same pointer size.
2887                  */
2888
2889                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHR_UN_IMM, offset_reg, ptr->dreg, card_table_shift_bits);
2890                 if (card_table_mask)
2891                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PAND_IMM, offset_reg, offset_reg, card_table_mask);
2892
2893                 /*We can't use PADD_IMM since the cardtable might end up in high addresses and amd64 doesn't support
2894                  * IMM's larger than 32bits.
2895                  */
2896                 ins = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_GC_CARD_TABLE_ADDR, NULL);
2897                 card_reg = ins->dreg;
2898
2899                 MONO_EMIT_NEW_BIALU (cfg, OP_PADD, offset_reg, offset_reg, card_reg);
2900                 MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STOREI1_MEMBASE_IMM, offset_reg, 0, 1);
2901         } else {
2902                 MonoMethod *write_barrier = mono_gc_get_write_barrier ();
2903                 mono_emit_method_call (cfg, write_barrier, &ptr, NULL);
2904         }
2905
2906         EMIT_NEW_DUMMY_USE (cfg, dummy_use, value);
2907 }
2908
2909 gboolean
2910 mini_emit_wb_aware_memcpy (MonoCompile *cfg, MonoClass *klass, MonoInst *iargs[4], int size, int align)
2911 {
2912         int dest_ptr_reg, tmp_reg, destreg, srcreg, offset;
2913         unsigned need_wb = 0;
2914
2915         if (align == 0)
2916                 align = 4;
2917
2918         /*types with references can't have alignment smaller than sizeof(void*) */
2919         if (align < SIZEOF_VOID_P)
2920                 return FALSE;
2921
2922         if (size > 5 * SIZEOF_VOID_P)
2923                 return FALSE;
2924
2925         create_write_barrier_bitmap (cfg, klass, &need_wb, 0);
2926
2927         destreg = iargs [0]->dreg;
2928         srcreg = iargs [1]->dreg;
2929         offset = 0;
2930
2931         dest_ptr_reg = alloc_preg (cfg);
2932         tmp_reg = alloc_preg (cfg);
2933
2934         /*tmp = dreg*/
2935         EMIT_NEW_UNALU (cfg, iargs [0], OP_MOVE, dest_ptr_reg, destreg);
2936
2937         while (size >= SIZEOF_VOID_P) {
2938                 MonoInst *load_inst;
2939                 MONO_INST_NEW (cfg, load_inst, OP_LOAD_MEMBASE);
2940                 load_inst->dreg = tmp_reg;
2941                 load_inst->inst_basereg = srcreg;
2942                 load_inst->inst_offset = offset;
2943                 MONO_ADD_INS (cfg->cbb, load_inst);
2944
2945                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, dest_ptr_reg, 0, tmp_reg);
2946
2947                 if (need_wb & 0x1)
2948                         mini_emit_write_barrier (cfg, iargs [0], load_inst);
2949
2950                 offset += SIZEOF_VOID_P;
2951                 size -= SIZEOF_VOID_P;
2952                 need_wb >>= 1;
2953
2954                 /*tmp += sizeof (void*)*/
2955                 if (size >= SIZEOF_VOID_P) {
2956                         NEW_BIALU_IMM (cfg, iargs [0], OP_PADD_IMM, dest_ptr_reg, dest_ptr_reg, SIZEOF_VOID_P);
2957                         MONO_ADD_INS (cfg->cbb, iargs [0]);
2958                 }
2959         }
2960
2961         /* Those cannot be references since size < sizeof (void*) */
2962         while (size >= 4) {
2963                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, tmp_reg, srcreg, offset);
2964                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI4_MEMBASE_REG, destreg, offset, tmp_reg);
2965                 offset += 4;
2966                 size -= 4;
2967         }
2968
2969         while (size >= 2) {
2970                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI2_MEMBASE, tmp_reg, srcreg, offset);
2971                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI2_MEMBASE_REG, destreg, offset, tmp_reg);
2972                 offset += 2;
2973                 size -= 2;
2974         }
2975
2976         while (size >= 1) {
2977                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI1_MEMBASE, tmp_reg, srcreg, offset);
2978                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI1_MEMBASE_REG, destreg, offset, tmp_reg);
2979                 offset += 1;
2980                 size -= 1;
2981         }
2982
2983         return TRUE;
2984 }
2985
2986 /*
2987  * Emit code to copy a valuetype of type @klass whose address is stored in
2988  * @src->dreg to memory whose address is stored at @dest->dreg.
2989  */
2990 void
2991 mini_emit_stobj (MonoCompile *cfg, MonoInst *dest, MonoInst *src, MonoClass *klass, gboolean native)
2992 {
2993         MonoInst *iargs [4];
2994         int n;
2995         guint32 align = 0;
2996         MonoMethod *memcpy_method;
2997         MonoInst *size_ins = NULL;
2998         MonoInst *memcpy_ins = NULL;
2999
3000         g_assert (klass);
3001         if (cfg->gshared)
3002                 klass = mono_class_from_mono_type (mini_get_underlying_type (&klass->byval_arg));
3003
3004         /*
3005          * This check breaks with spilled vars... need to handle it during verification anyway.
3006          * g_assert (klass && klass == src->klass && klass == dest->klass);
3007          */
3008
3009         if (mini_is_gsharedvt_klass (klass)) {
3010                 g_assert (!native);
3011                 size_ins = mini_emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_VALUE_SIZE);
3012                 memcpy_ins = mini_emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_MEMCPY);
3013         }
3014
3015         if (native)
3016                 n = mono_class_native_size (klass, &align);
3017         else
3018                 n = mono_class_value_size (klass, &align);
3019
3020         if (!align)
3021                 align = SIZEOF_VOID_P;
3022         /* if native is true there should be no references in the struct */
3023         if (cfg->gen_write_barriers && (klass->has_references || size_ins) && !native) {
3024                 /* Avoid barriers when storing to the stack */
3025                 if (!((dest->opcode == OP_ADD_IMM && dest->sreg1 == cfg->frame_reg) ||
3026                           (dest->opcode == OP_LDADDR))) {
3027                         int context_used;
3028
3029                         iargs [0] = dest;
3030                         iargs [1] = src;
3031
3032                         context_used = mini_class_check_context_used (cfg, klass);
3033
3034                         /* It's ok to intrinsify under gsharing since shared code types are layout stable. */
3035                         if (!size_ins && (cfg->opt & MONO_OPT_INTRINS) && mini_emit_wb_aware_memcpy (cfg, klass, iargs, n, align)) {
3036                                 return;
3037                         } else if (size_ins || align < SIZEOF_VOID_P) {
3038                                 if (context_used) {
3039                                         iargs [2] = mini_emit_get_rgctx_klass (cfg, context_used, klass, MONO_RGCTX_INFO_KLASS);
3040                                 }  else {
3041                                         iargs [2] = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_CLASS, klass);
3042                                         if (!cfg->compile_aot)
3043                                                 mono_class_compute_gc_descriptor (klass);
3044                                 }
3045                                 if (size_ins)
3046                                         mono_emit_jit_icall (cfg, mono_gsharedvt_value_copy, iargs);
3047                                 else
3048                                         mono_emit_jit_icall (cfg, mono_value_copy, iargs);
3049                         } else {
3050                                 /* We don't unroll more than 5 stores to avoid code bloat. */
3051                                 /*This is harmless and simplify mono_gc_get_range_copy_func */
3052                                 n += (SIZEOF_VOID_P - 1);
3053                                 n &= ~(SIZEOF_VOID_P - 1);
3054
3055                                 EMIT_NEW_ICONST (cfg, iargs [2], n);
3056                                 mono_emit_jit_icall (cfg, mono_gc_get_range_copy_func (), iargs);
3057                         }
3058                 }
3059         }
3060
3061         if (!size_ins && (cfg->opt & MONO_OPT_INTRINS) && n <= sizeof (gpointer) * 8) {
3062                 /* FIXME: Optimize the case when src/dest is OP_LDADDR */
3063                 mini_emit_memcpy (cfg, dest->dreg, 0, src->dreg, 0, n, align);
3064         } else {
3065                 iargs [0] = dest;
3066                 iargs [1] = src;
3067                 if (size_ins)
3068                         iargs [2] = size_ins;
3069                 else
3070                         EMIT_NEW_ICONST (cfg, iargs [2], n);
3071                 
3072                 memcpy_method = mini_get_memcpy_method ();
3073                 if (memcpy_ins)
3074                         mini_emit_calli (cfg, mono_method_signature (memcpy_method), iargs, memcpy_ins, NULL, NULL);
3075                 else
3076                         mono_emit_method_call (cfg, memcpy_method, iargs, NULL);
3077         }
3078 }
3079
3080 MonoMethod*
3081 mini_get_memset_method (void)
3082 {
3083         static MonoMethod *memset_method = NULL;
3084         if (!memset_method) {
3085                 memset_method = mono_class_get_method_from_name (mono_defaults.string_class, "memset", 3);
3086                 if (!memset_method)
3087                         g_error ("Old corlib found. Install a new one");
3088         }
3089         return memset_method;
3090 }
3091
3092 void
3093 mini_emit_initobj (MonoCompile *cfg, MonoInst *dest, const guchar *ip, MonoClass *klass)
3094 {
3095         MonoInst *iargs [3];
3096         int n;
3097         guint32 align;
3098         MonoMethod *memset_method;
3099         MonoInst *size_ins = NULL;
3100         MonoInst *bzero_ins = NULL;
3101         static MonoMethod *bzero_method;
3102
3103         /* FIXME: Optimize this for the case when dest is an LDADDR */
3104         mono_class_init (klass);
3105         if (mini_is_gsharedvt_klass (klass)) {
3106                 size_ins = mini_emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_VALUE_SIZE);
3107                 bzero_ins = mini_emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_BZERO);
3108                 if (!bzero_method)
3109                         bzero_method = mono_class_get_method_from_name (mono_defaults.string_class, "bzero_aligned_1", 2);
3110                 g_assert (bzero_method);
3111                 iargs [0] = dest;
3112                 iargs [1] = size_ins;
3113                 mini_emit_calli (cfg, mono_method_signature (bzero_method), iargs, bzero_ins, NULL, NULL);
3114                 return;
3115         }
3116
3117         klass = mono_class_from_mono_type (mini_get_underlying_type (&klass->byval_arg));
3118
3119         n = mono_class_value_size (klass, &align);
3120
3121         if (n <= sizeof (gpointer) * 8) {
3122                 mini_emit_memset (cfg, dest->dreg, 0, n, 0, align);
3123         }
3124         else {
3125                 memset_method = mini_get_memset_method ();
3126                 iargs [0] = dest;
3127                 EMIT_NEW_ICONST (cfg, iargs [1], 0);
3128                 EMIT_NEW_ICONST (cfg, iargs [2], n);
3129                 mono_emit_method_call (cfg, memset_method, iargs, NULL);
3130         }
3131 }
3132
3133 /*
3134  * emit_get_rgctx:
3135  *
3136  *   Emit IR to return either the this pointer for instance method,
3137  * or the mrgctx for static methods.
3138  */
3139 static MonoInst*
3140 emit_get_rgctx (MonoCompile *cfg, MonoMethod *method, int context_used)
3141 {
3142         MonoInst *this_ins = NULL;
3143
3144         g_assert (cfg->gshared);
3145
3146         if (!(method->flags & METHOD_ATTRIBUTE_STATIC) &&
3147                         !(context_used & MONO_GENERIC_CONTEXT_USED_METHOD) &&
3148                 !method->klass->valuetype)
3149                 EMIT_NEW_VARLOAD (cfg, this_ins, cfg->this_arg, &mono_defaults.object_class->byval_arg);
3150
3151         if (context_used & MONO_GENERIC_CONTEXT_USED_METHOD) {
3152                 MonoInst *mrgctx_loc, *mrgctx_var;
3153
3154                 g_assert (!this_ins);
3155                 g_assert (method->is_inflated && mono_method_get_context (method)->method_inst);
3156
3157                 mrgctx_loc = mono_get_vtable_var (cfg);
3158                 EMIT_NEW_TEMPLOAD (cfg, mrgctx_var, mrgctx_loc->inst_c0);
3159
3160                 return mrgctx_var;
3161         } else if (MONO_CLASS_IS_INTERFACE (cfg->method->klass)) {
3162                 MonoInst *mrgctx_loc, *mrgctx_var;
3163
3164                 /* Default interface methods need an mrgctx since the vtabke at runtime points at an implementing class */
3165                 mrgctx_loc = mono_get_vtable_var (cfg);
3166                 EMIT_NEW_TEMPLOAD (cfg, mrgctx_var, mrgctx_loc->inst_c0);
3167
3168                 g_assert (mono_method_needs_static_rgctx_invoke (cfg->method, TRUE));
3169
3170                 return mrgctx_var;
3171         } else if (method->flags & METHOD_ATTRIBUTE_STATIC || method->klass->valuetype) {
3172                 MonoInst *vtable_loc, *vtable_var;
3173
3174                 g_assert (!this_ins);
3175
3176                 vtable_loc = mono_get_vtable_var (cfg);
3177                 EMIT_NEW_TEMPLOAD (cfg, vtable_var, vtable_loc->inst_c0);
3178
3179                 if (method->is_inflated && mono_method_get_context (method)->method_inst) {
3180                         MonoInst *mrgctx_var = vtable_var;
3181                         int vtable_reg;
3182
3183                         vtable_reg = alloc_preg (cfg);
3184                         EMIT_NEW_LOAD_MEMBASE (cfg, vtable_var, OP_LOAD_MEMBASE, vtable_reg, mrgctx_var->dreg, MONO_STRUCT_OFFSET (MonoMethodRuntimeGenericContext, class_vtable));
3185                         vtable_var->type = STACK_PTR;
3186                 }
3187
3188                 return vtable_var;
3189         } else {
3190                 MonoInst *ins;
3191                 int vtable_reg;
3192         
3193                 vtable_reg = alloc_preg (cfg);
3194                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, vtable_reg, this_ins->dreg, MONO_STRUCT_OFFSET (MonoObject, vtable));
3195                 return ins;
3196         }
3197 }
3198
3199 static MonoJumpInfoRgctxEntry *
3200 mono_patch_info_rgctx_entry_new (MonoMemPool *mp, MonoMethod *method, gboolean in_mrgctx, MonoJumpInfoType patch_type, gconstpointer patch_data, MonoRgctxInfoType info_type)
3201 {
3202         MonoJumpInfoRgctxEntry *res = (MonoJumpInfoRgctxEntry *)mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoRgctxEntry));
3203         res->method = method;
3204         res->in_mrgctx = in_mrgctx;
3205         res->data = (MonoJumpInfo *)mono_mempool_alloc0 (mp, sizeof (MonoJumpInfo));
3206         res->data->type = patch_type;
3207         res->data->data.target = patch_data;
3208         res->info_type = info_type;
3209
3210         return res;
3211 }
3212
3213 static inline MonoInst*
3214 emit_rgctx_fetch_inline (MonoCompile *cfg, MonoInst *rgctx, MonoJumpInfoRgctxEntry *entry)
3215 {
3216         MonoInst *args [16];
3217         MonoInst *call;
3218
3219         // FIXME: No fastpath since the slot is not a compile time constant
3220         args [0] = rgctx;
3221         EMIT_NEW_AOTCONST (cfg, args [1], MONO_PATCH_INFO_RGCTX_SLOT_INDEX, entry);
3222         if (entry->in_mrgctx)
3223                 call = mono_emit_jit_icall (cfg, mono_fill_method_rgctx, args);
3224         else
3225                 call = mono_emit_jit_icall (cfg, mono_fill_class_rgctx, args);
3226         return call;
3227 #if 0
3228         /*
3229          * FIXME: This can be called during decompose, which is a problem since it creates
3230          * new bblocks.
3231          * Also, the fastpath doesn't work since the slot number is dynamically allocated.
3232          */
3233         int i, slot, depth, index, rgctx_reg, val_reg, res_reg;
3234         gboolean mrgctx;
3235         MonoBasicBlock *is_null_bb, *end_bb;
3236         MonoInst *res, *ins, *call;
3237         MonoInst *args[16];
3238
3239         slot = mini_get_rgctx_entry_slot (entry);
3240
3241         mrgctx = MONO_RGCTX_SLOT_IS_MRGCTX (slot);
3242         index = MONO_RGCTX_SLOT_INDEX (slot);
3243         if (mrgctx)
3244                 index += MONO_SIZEOF_METHOD_RUNTIME_GENERIC_CONTEXT / sizeof (gpointer);
3245         for (depth = 0; ; ++depth) {
3246                 int size = mono_class_rgctx_get_array_size (depth, mrgctx);
3247
3248                 if (index < size - 1)
3249                         break;
3250                 index -= size - 1;
3251         }
3252
3253         NEW_BBLOCK (cfg, end_bb);
3254         NEW_BBLOCK (cfg, is_null_bb);
3255
3256         if (mrgctx) {
3257                 rgctx_reg = rgctx->dreg;
3258         } else {
3259                 rgctx_reg = alloc_preg (cfg);
3260
3261                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, rgctx_reg, rgctx->dreg, MONO_STRUCT_OFFSET (MonoVTable, runtime_generic_context));
3262                 // FIXME: Avoid this check by allocating the table when the vtable is created etc.
3263                 NEW_BBLOCK (cfg, is_null_bb);
3264
3265                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, rgctx_reg, 0);
3266                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, is_null_bb);
3267         }
3268
3269         for (i = 0; i < depth; ++i) {
3270                 int array_reg = alloc_preg (cfg);
3271
3272                 /* load ptr to next array */
3273                 if (mrgctx && i == 0)
3274                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, array_reg, rgctx_reg, MONO_SIZEOF_METHOD_RUNTIME_GENERIC_CONTEXT);
3275                 else
3276                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, array_reg, rgctx_reg, 0);
3277                 rgctx_reg = array_reg;
3278                 /* is the ptr null? */
3279                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, rgctx_reg, 0);
3280                 /* if yes, jump to actual trampoline */
3281                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, is_null_bb);
3282         }
3283
3284         /* fetch slot */
3285         val_reg = alloc_preg (cfg);
3286         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, val_reg, rgctx_reg, (index + 1) * sizeof (gpointer));
3287         /* is the slot null? */
3288         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, val_reg, 0);
3289         /* if yes, jump to actual trampoline */
3290         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, is_null_bb);
3291
3292         /* Fastpath */
3293         res_reg = alloc_preg (cfg);
3294         MONO_INST_NEW (cfg, ins, OP_MOVE);
3295         ins->dreg = res_reg;
3296         ins->sreg1 = val_reg;
3297         MONO_ADD_INS (cfg->cbb, ins);
3298         res = ins;
3299         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
3300
3301         /* Slowpath */
3302         MONO_START_BB (cfg, is_null_bb);
3303         args [0] = rgctx;
3304         EMIT_NEW_ICONST (cfg, args [1], index);
3305         if (mrgctx)
3306                 call = mono_emit_jit_icall (cfg, mono_fill_method_rgctx, args);
3307         else
3308                 call = mono_emit_jit_icall (cfg, mono_fill_class_rgctx, args);
3309         MONO_INST_NEW (cfg, ins, OP_MOVE);
3310         ins->dreg = res_reg;
3311         ins->sreg1 = call->dreg;
3312         MONO_ADD_INS (cfg->cbb, ins);
3313         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
3314
3315         MONO_START_BB (cfg, end_bb);
3316
3317         return res;
3318 #endif
3319 }
3320
3321 /*
3322  * emit_rgctx_fetch:
3323  *
3324  *   Emit IR to load the value of the rgctx entry ENTRY from the rgctx
3325  * given by RGCTX.
3326  */
3327 static inline MonoInst*
3328 emit_rgctx_fetch (MonoCompile *cfg, MonoInst *rgctx, MonoJumpInfoRgctxEntry *entry)
3329 {
3330         if (cfg->llvm_only)
3331                 return emit_rgctx_fetch_inline (cfg, rgctx, entry);
3332         else
3333                 return mono_emit_abs_call (cfg, MONO_PATCH_INFO_RGCTX_FETCH, entry, helper_sig_rgctx_lazy_fetch_trampoline, &rgctx);
3334 }
3335
3336 MonoInst*
3337 mini_emit_get_rgctx_klass (MonoCompile *cfg, int context_used,
3338                                           MonoClass *klass, MonoRgctxInfoType rgctx_type)
3339 {
3340         MonoJumpInfoRgctxEntry *entry = mono_patch_info_rgctx_entry_new (cfg->mempool, cfg->method, context_used & MONO_GENERIC_CONTEXT_USED_METHOD, MONO_PATCH_INFO_CLASS, klass, rgctx_type);
3341         MonoInst *rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3342
3343         return emit_rgctx_fetch (cfg, rgctx, entry);
3344 }
3345
3346 static MonoInst*
3347 emit_get_rgctx_sig (MonoCompile *cfg, int context_used,
3348                                         MonoMethodSignature *sig, MonoRgctxInfoType rgctx_type)
3349 {
3350         MonoJumpInfoRgctxEntry *entry = mono_patch_info_rgctx_entry_new (cfg->mempool, cfg->method, context_used & MONO_GENERIC_CONTEXT_USED_METHOD, MONO_PATCH_INFO_SIGNATURE, sig, rgctx_type);
3351         MonoInst *rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3352
3353         return emit_rgctx_fetch (cfg, rgctx, entry);
3354 }
3355
3356 static MonoInst*
3357 emit_get_rgctx_gsharedvt_call (MonoCompile *cfg, int context_used,
3358                                                            MonoMethodSignature *sig, MonoMethod *cmethod, MonoRgctxInfoType rgctx_type)
3359 {
3360         MonoJumpInfoGSharedVtCall *call_info;
3361         MonoJumpInfoRgctxEntry *entry;
3362         MonoInst *rgctx;
3363
3364         call_info = (MonoJumpInfoGSharedVtCall *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoJumpInfoGSharedVtCall));
3365         call_info->sig = sig;
3366         call_info->method = cmethod;
3367
3368         entry = mono_patch_info_rgctx_entry_new (cfg->mempool, cfg->method, context_used & MONO_GENERIC_CONTEXT_USED_METHOD, MONO_PATCH_INFO_GSHAREDVT_CALL, call_info, rgctx_type);
3369         rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3370
3371         return emit_rgctx_fetch (cfg, rgctx, entry);
3372 }
3373
3374 /*
3375  * emit_get_rgctx_virt_method:
3376  *
3377  *   Return data for method VIRT_METHOD for a receiver of type KLASS.
3378  */
3379 static MonoInst*
3380 emit_get_rgctx_virt_method (MonoCompile *cfg, int context_used,
3381                                                         MonoClass *klass, MonoMethod *virt_method, MonoRgctxInfoType rgctx_type)
3382 {
3383         MonoJumpInfoVirtMethod *info;
3384         MonoJumpInfoRgctxEntry *entry;
3385         MonoInst *rgctx;
3386
3387         info = (MonoJumpInfoVirtMethod *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoJumpInfoVirtMethod));
3388         info->klass = klass;
3389         info->method = virt_method;
3390
3391         entry = mono_patch_info_rgctx_entry_new (cfg->mempool, cfg->method, context_used & MONO_GENERIC_CONTEXT_USED_METHOD, MONO_PATCH_INFO_VIRT_METHOD, info, rgctx_type);
3392         rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3393
3394         return emit_rgctx_fetch (cfg, rgctx, entry);
3395 }
3396
3397 static MonoInst*
3398 emit_get_rgctx_gsharedvt_method (MonoCompile *cfg, int context_used,
3399                                                                  MonoMethod *cmethod, MonoGSharedVtMethodInfo *info)
3400 {
3401         MonoJumpInfoRgctxEntry *entry;
3402         MonoInst *rgctx;
3403
3404         entry = mono_patch_info_rgctx_entry_new (cfg->mempool, cfg->method, context_used & MONO_GENERIC_CONTEXT_USED_METHOD, MONO_PATCH_INFO_GSHAREDVT_METHOD, info, MONO_RGCTX_INFO_METHOD_GSHAREDVT_INFO);
3405         rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3406
3407         return emit_rgctx_fetch (cfg, rgctx, entry);
3408 }
3409
3410 /*
3411  * emit_get_rgctx_method:
3412  *
3413  *   Emit IR to load the property RGCTX_TYPE of CMETHOD. If context_used is 0, emit
3414  * normal constants, else emit a load from the rgctx.
3415  */
3416 static MonoInst*
3417 emit_get_rgctx_method (MonoCompile *cfg, int context_used,
3418                                            MonoMethod *cmethod, MonoRgctxInfoType rgctx_type)
3419 {
3420         if (!context_used) {
3421                 MonoInst *ins;
3422
3423                 switch (rgctx_type) {
3424                 case MONO_RGCTX_INFO_METHOD:
3425                         EMIT_NEW_METHODCONST (cfg, ins, cmethod);
3426                         return ins;
3427                 case MONO_RGCTX_INFO_METHOD_RGCTX:
3428                         EMIT_NEW_METHOD_RGCTX_CONST (cfg, ins, cmethod);
3429                         return ins;
3430                 default:
3431                         g_assert_not_reached ();
3432                 }
3433         } else {
3434                 MonoJumpInfoRgctxEntry *entry = mono_patch_info_rgctx_entry_new (cfg->mempool, cfg->method, context_used & MONO_GENERIC_CONTEXT_USED_METHOD, MONO_PATCH_INFO_METHODCONST, cmethod, rgctx_type);
3435                 MonoInst *rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3436
3437                 return emit_rgctx_fetch (cfg, rgctx, entry);
3438         }
3439 }
3440
3441 static MonoInst*
3442 emit_get_rgctx_field (MonoCompile *cfg, int context_used,
3443                                           MonoClassField *field, MonoRgctxInfoType rgctx_type)
3444 {
3445         MonoJumpInfoRgctxEntry *entry = mono_patch_info_rgctx_entry_new (cfg->mempool, cfg->method, context_used & MONO_GENERIC_CONTEXT_USED_METHOD, MONO_PATCH_INFO_FIELD, field, rgctx_type);
3446         MonoInst *rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3447
3448         return emit_rgctx_fetch (cfg, rgctx, entry);
3449 }
3450
3451 static int
3452 get_gsharedvt_info_slot (MonoCompile *cfg, gpointer data, MonoRgctxInfoType rgctx_type)
3453 {
3454         MonoGSharedVtMethodInfo *info = cfg->gsharedvt_info;
3455         MonoRuntimeGenericContextInfoTemplate *template_;
3456         int i, idx;
3457
3458         g_assert (info);
3459
3460         for (i = 0; i < info->num_entries; ++i) {
3461                 MonoRuntimeGenericContextInfoTemplate *otemplate = &info->entries [i];
3462
3463                 if (otemplate->info_type == rgctx_type && otemplate->data == data && rgctx_type != MONO_RGCTX_INFO_LOCAL_OFFSET)
3464                         return i;
3465         }
3466
3467         if (info->num_entries == info->count_entries) {
3468                 MonoRuntimeGenericContextInfoTemplate *new_entries;
3469                 int new_count_entries = info->count_entries ? info->count_entries * 2 : 16;
3470
3471                 new_entries = (MonoRuntimeGenericContextInfoTemplate *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoRuntimeGenericContextInfoTemplate) * new_count_entries);
3472
3473                 memcpy (new_entries, info->entries, sizeof (MonoRuntimeGenericContextInfoTemplate) * info->count_entries);
3474                 info->entries = new_entries;
3475                 info->count_entries = new_count_entries;
3476         }
3477
3478         idx = info->num_entries;
3479         template_ = &info->entries [idx];
3480         template_->info_type = rgctx_type;
3481         template_->data = data;
3482
3483         info->num_entries ++;
3484
3485         return idx;
3486 }
3487
3488 /*
3489  * emit_get_gsharedvt_info:
3490  *
3491  *   This is similar to emit_get_rgctx_.., but loads the data from the gsharedvt info var instead of calling an rgctx fetch trampoline.
3492  */
3493 static MonoInst*
3494 emit_get_gsharedvt_info (MonoCompile *cfg, gpointer data, MonoRgctxInfoType rgctx_type)
3495 {
3496         MonoInst *ins;
3497         int idx, dreg;
3498
3499         idx = get_gsharedvt_info_slot (cfg, data, rgctx_type);
3500         /* Load info->entries [idx] */
3501         dreg = alloc_preg (cfg);
3502         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, dreg, cfg->gsharedvt_info_var->dreg, MONO_STRUCT_OFFSET (MonoGSharedVtMethodRuntimeInfo, entries) + (idx * sizeof (gpointer)));
3503
3504         return ins;
3505 }
3506
3507 MonoInst*
3508 mini_emit_get_gsharedvt_info_klass (MonoCompile *cfg, MonoClass *klass, MonoRgctxInfoType rgctx_type)
3509 {
3510         return emit_get_gsharedvt_info (cfg, &klass->byval_arg, rgctx_type);
3511 }
3512
3513 /*
3514  * On return the caller must check @klass for load errors.
3515  */
3516 static void
3517 emit_class_init (MonoCompile *cfg, MonoClass *klass)
3518 {
3519         MonoInst *vtable_arg;
3520         int context_used;
3521
3522         context_used = mini_class_check_context_used (cfg, klass);
3523
3524         if (context_used) {
3525                 vtable_arg = mini_emit_get_rgctx_klass (cfg, context_used,
3526                                                                                    klass, MONO_RGCTX_INFO_VTABLE);
3527         } else {
3528                 MonoVTable *vtable = mono_class_vtable (cfg->domain, klass);
3529
3530                 if (!vtable)
3531                         return;
3532                 EMIT_NEW_VTABLECONST (cfg, vtable_arg, vtable);
3533         }
3534
3535         if (!COMPILE_LLVM (cfg) && cfg->backend->have_op_generic_class_init) {
3536                 MonoInst *ins;
3537
3538                 /*
3539                  * Using an opcode instead of emitting IR here allows the hiding of the call inside the opcode,
3540                  * so this doesn't have to clobber any regs and it doesn't break basic blocks.
3541                  */
3542                 MONO_INST_NEW (cfg, ins, OP_GENERIC_CLASS_INIT);
3543                 ins->sreg1 = vtable_arg->dreg;
3544                 MONO_ADD_INS (cfg->cbb, ins);
3545         } else {
3546                 int inited_reg;
3547                 MonoBasicBlock *inited_bb;
3548                 MonoInst *args [16];
3549
3550                 inited_reg = alloc_ireg (cfg);
3551
3552                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADU1_MEMBASE, inited_reg, vtable_arg->dreg, MONO_STRUCT_OFFSET (MonoVTable, initialized));
3553
3554                 NEW_BBLOCK (cfg, inited_bb);
3555
3556                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, inited_reg, 0);
3557                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBNE_UN, inited_bb);
3558
3559                 args [0] = vtable_arg;
3560                 mono_emit_jit_icall (cfg, mono_generic_class_init, args);
3561
3562                 MONO_START_BB (cfg, inited_bb);
3563         }
3564 }
3565
3566 static void
3567 emit_seq_point (MonoCompile *cfg, MonoMethod *method, guint8* ip, gboolean intr_loc, gboolean nonempty_stack)
3568 {
3569         MonoInst *ins;
3570
3571         if (cfg->gen_seq_points && cfg->method == method) {
3572                 NEW_SEQ_POINT (cfg, ins, ip - cfg->header->code, intr_loc);
3573                 if (nonempty_stack)
3574                         ins->flags |= MONO_INST_NONEMPTY_STACK;
3575                 MONO_ADD_INS (cfg->cbb, ins);
3576         }
3577 }
3578
3579 void
3580 mini_save_cast_details (MonoCompile *cfg, MonoClass *klass, int obj_reg, gboolean null_check)
3581 {
3582         if (mini_get_debug_options ()->better_cast_details) {
3583                 int vtable_reg = alloc_preg (cfg);
3584                 int klass_reg = alloc_preg (cfg);
3585                 MonoBasicBlock *is_null_bb = NULL;
3586                 MonoInst *tls_get;
3587                 int to_klass_reg, context_used;
3588
3589                 if (null_check) {
3590                         NEW_BBLOCK (cfg, is_null_bb);
3591
3592                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, obj_reg, 0);
3593                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, is_null_bb);
3594                 }
3595
3596                 tls_get = mono_create_tls_get (cfg, TLS_KEY_JIT_TLS);
3597                 if (!tls_get) {
3598                         fprintf (stderr, "error: --debug=casts not supported on this platform.\n.");
3599                         exit (1);
3600                 }
3601
3602                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, vtable_reg, obj_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
3603                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, klass));
3604
3605                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, tls_get->dreg, MONO_STRUCT_OFFSET (MonoJitTlsData, class_cast_from), klass_reg);
3606
3607                 context_used = mini_class_check_context_used (cfg, klass);
3608                 if (context_used) {
3609                         MonoInst *class_ins;
3610
3611                         class_ins = mini_emit_get_rgctx_klass (cfg, context_used, klass, MONO_RGCTX_INFO_KLASS);
3612                         to_klass_reg = class_ins->dreg;
3613                 } else {
3614                         to_klass_reg = alloc_preg (cfg);
3615                         MONO_EMIT_NEW_CLASSCONST (cfg, to_klass_reg, klass);
3616                 }
3617                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, tls_get->dreg, MONO_STRUCT_OFFSET (MonoJitTlsData, class_cast_to), to_klass_reg);
3618
3619                 if (null_check)
3620                         MONO_START_BB (cfg, is_null_bb);
3621         }
3622 }
3623
3624 void
3625 mini_reset_cast_details (MonoCompile *cfg)
3626 {
3627         /* Reset the variables holding the cast details */
3628         if (mini_get_debug_options ()->better_cast_details) {
3629                 MonoInst *tls_get = mono_create_tls_get (cfg, TLS_KEY_JIT_TLS);
3630                 /* It is enough to reset the from field */
3631                 MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STORE_MEMBASE_IMM, tls_get->dreg, MONO_STRUCT_OFFSET (MonoJitTlsData, class_cast_from), 0);
3632         }
3633 }
3634
3635 /*
3636  * On return the caller must check @array_class for load errors
3637  */
3638 static void
3639 mini_emit_check_array_type (MonoCompile *cfg, MonoInst *obj, MonoClass *array_class)
3640 {
3641         int vtable_reg = alloc_preg (cfg);
3642         int context_used;
3643
3644         context_used = mini_class_check_context_used (cfg, array_class);
3645
3646         mini_save_cast_details (cfg, array_class, obj->dreg, FALSE);
3647
3648         MONO_EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, vtable_reg, obj->dreg, MONO_STRUCT_OFFSET (MonoObject, vtable));
3649
3650         if (cfg->opt & MONO_OPT_SHARED) {
3651                 int class_reg = alloc_preg (cfg);
3652                 MonoInst *ins;
3653
3654                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, class_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, klass));
3655                 ins = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_CLASS, array_class);
3656                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, class_reg, ins->dreg);
3657         } else if (context_used) {
3658                 MonoInst *vtable_ins;
3659
3660                 vtable_ins = mini_emit_get_rgctx_klass (cfg, context_used, array_class, MONO_RGCTX_INFO_VTABLE);
3661                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, vtable_reg, vtable_ins->dreg);
3662         } else {
3663                 if (cfg->compile_aot) {
3664                         int vt_reg;
3665                         MonoVTable *vtable;
3666
3667                         if (!(vtable = mono_class_vtable (cfg->domain, array_class)))
3668                                 return;
3669                         vt_reg = alloc_preg (cfg);
3670                         MONO_EMIT_NEW_VTABLECONST (cfg, vt_reg, vtable);
3671                         MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, vtable_reg, vt_reg);
3672                 } else {
3673                         MonoVTable *vtable;
3674                         if (!(vtable = mono_class_vtable (cfg->domain, array_class)))
3675                                 return;
3676                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, vtable_reg, vtable);
3677                 }
3678         }
3679         
3680         MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "ArrayTypeMismatchException");
3681
3682         mini_reset_cast_details (cfg);
3683 }
3684
3685 /**
3686  * Handles unbox of a Nullable<T>. If context_used is non zero, then shared 
3687  * generic code is generated.
3688  */
3689 static MonoInst*
3690 handle_unbox_nullable (MonoCompile* cfg, MonoInst* val, MonoClass* klass, int context_used)
3691 {
3692         MonoMethod* method = mono_class_get_method_from_name (klass, "Unbox", 1);
3693
3694         if (context_used) {
3695                 MonoInst *rgctx, *addr;
3696
3697                 /* FIXME: What if the class is shared?  We might not
3698                    have to get the address of the method from the
3699                    RGCTX. */
3700                 addr = emit_get_rgctx_method (cfg, context_used, method,
3701                                                                           MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
3702                 if (cfg->llvm_only) {
3703                         cfg->signatures = g_slist_prepend_mempool (cfg->mempool, cfg->signatures, mono_method_signature (method));
3704                         return emit_llvmonly_calli (cfg, mono_method_signature (method), &val, addr);
3705                 } else {
3706                         rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3707
3708                         return mini_emit_calli (cfg, mono_method_signature (method), &val, addr, NULL, rgctx);
3709                 }
3710         } else {
3711                 gboolean pass_vtable, pass_mrgctx;
3712                 MonoInst *rgctx_arg = NULL;
3713
3714                 check_method_sharing (cfg, method, &pass_vtable, &pass_mrgctx);
3715                 g_assert (!pass_mrgctx);
3716
3717                 if (pass_vtable) {
3718                         MonoVTable *vtable = mono_class_vtable (cfg->domain, method->klass);
3719
3720                         g_assert (vtable);
3721                         EMIT_NEW_VTABLECONST (cfg, rgctx_arg, vtable);
3722                 }
3723
3724                 return mono_emit_method_call_full (cfg, method, NULL, FALSE, &val, NULL, NULL, rgctx_arg);
3725         }
3726 }
3727
3728 static MonoInst*
3729 handle_unbox (MonoCompile *cfg, MonoClass *klass, MonoInst **sp, int context_used)
3730 {
3731         MonoInst *add;
3732         int obj_reg;
3733         int vtable_reg = alloc_dreg (cfg ,STACK_PTR);
3734         int klass_reg = alloc_dreg (cfg ,STACK_PTR);
3735         int eclass_reg = alloc_dreg (cfg ,STACK_PTR);
3736         int rank_reg = alloc_dreg (cfg ,STACK_I4);
3737
3738         obj_reg = sp [0]->dreg;
3739         MONO_EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, vtable_reg, obj_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
3740         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADU1_MEMBASE, rank_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, rank));
3741
3742         /* FIXME: generics */
3743         g_assert (klass->rank == 0);
3744                         
3745         // Check rank == 0
3746         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, rank_reg, 0);
3747         MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "InvalidCastException");
3748
3749         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, klass));
3750         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, eclass_reg, klass_reg, MONO_STRUCT_OFFSET (MonoClass, element_class));
3751
3752         if (context_used) {
3753                 MonoInst *element_class;
3754
3755                 /* This assertion is from the unboxcast insn */
3756                 g_assert (klass->rank == 0);
3757
3758                 element_class = mini_emit_get_rgctx_klass (cfg, context_used,
3759                                 klass, MONO_RGCTX_INFO_ELEMENT_KLASS);
3760
3761                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, eclass_reg, element_class->dreg);
3762                 MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "InvalidCastException");
3763         } else {
3764                 mini_save_cast_details (cfg, klass->element_class, obj_reg, FALSE);
3765                 mini_emit_class_check (cfg, eclass_reg, klass->element_class);
3766                 mini_reset_cast_details (cfg);
3767         }
3768
3769         NEW_BIALU_IMM (cfg, add, OP_ADD_IMM, alloc_dreg (cfg, STACK_MP), obj_reg, sizeof (MonoObject));
3770         MONO_ADD_INS (cfg->cbb, add);
3771         add->type = STACK_MP;
3772         add->klass = klass;
3773
3774         return add;
3775 }
3776
3777 static MonoInst*
3778 handle_unbox_gsharedvt (MonoCompile *cfg, MonoClass *klass, MonoInst *obj)
3779 {
3780         MonoInst *addr, *klass_inst, *is_ref, *args[16];
3781         MonoBasicBlock *is_ref_bb, *is_nullable_bb, *end_bb;
3782         MonoInst *ins;
3783         int dreg, addr_reg;
3784
3785         klass_inst = mini_emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_KLASS);
3786
3787         /* obj */
3788         args [0] = obj;
3789
3790         /* klass */
3791         args [1] = klass_inst;
3792
3793         /* CASTCLASS */
3794         obj = mono_emit_jit_icall (cfg, mono_object_castclass_unbox, args);
3795
3796         NEW_BBLOCK (cfg, is_ref_bb);
3797         NEW_BBLOCK (cfg, is_nullable_bb);
3798         NEW_BBLOCK (cfg, end_bb);
3799         is_ref = mini_emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_CLASS_BOX_TYPE);
3800         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, is_ref->dreg, MONO_GSHAREDVT_BOX_TYPE_REF);
3801         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, is_ref_bb);
3802
3803         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, is_ref->dreg, MONO_GSHAREDVT_BOX_TYPE_NULLABLE);
3804         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, is_nullable_bb);
3805
3806         /* This will contain either the address of the unboxed vtype, or an address of the temporary where the ref is stored */
3807         addr_reg = alloc_dreg (cfg, STACK_MP);
3808
3809         /* Non-ref case */
3810         /* UNBOX */
3811         NEW_BIALU_IMM (cfg, addr, OP_ADD_IMM, addr_reg, obj->dreg, sizeof (MonoObject));
3812         MONO_ADD_INS (cfg->cbb, addr);
3813
3814         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
3815
3816         /* Ref case */
3817         MONO_START_BB (cfg, is_ref_bb);
3818
3819         /* Save the ref to a temporary */
3820         dreg = alloc_ireg (cfg);
3821         EMIT_NEW_VARLOADA_VREG (cfg, addr, dreg, &klass->byval_arg);
3822         addr->dreg = addr_reg;
3823         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, addr->dreg, 0, obj->dreg);
3824         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
3825
3826         /* Nullable case */
3827         MONO_START_BB (cfg, is_nullable_bb);
3828
3829         {
3830                 MonoInst *addr = mini_emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_NULLABLE_CLASS_UNBOX);
3831                 MonoInst *unbox_call;
3832                 MonoMethodSignature *unbox_sig;
3833
3834                 unbox_sig = (MonoMethodSignature *)mono_mempool_alloc0 (cfg->mempool, MONO_SIZEOF_METHOD_SIGNATURE + (1 * sizeof (MonoType *)));
3835                 unbox_sig->ret = &klass->byval_arg;
3836                 unbox_sig->param_count = 1;
3837                 unbox_sig->params [0] = &mono_defaults.object_class->byval_arg;
3838
3839                 if (cfg->llvm_only)
3840                         unbox_call = emit_llvmonly_calli (cfg, unbox_sig, &obj, addr);
3841                 else
3842                         unbox_call = mini_emit_calli (cfg, unbox_sig, &obj, addr, NULL, NULL);
3843
3844                 EMIT_NEW_VARLOADA_VREG (cfg, addr, unbox_call->dreg, &klass->byval_arg);
3845                 addr->dreg = addr_reg;
3846         }
3847
3848         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
3849
3850         /* End */
3851         MONO_START_BB (cfg, end_bb);
3852
3853         /* LDOBJ */
3854         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr_reg, 0);
3855
3856         return ins;
3857 }
3858
3859 /*
3860  * Returns NULL and set the cfg exception on error.
3861  */
3862 static MonoInst*
3863 handle_alloc (MonoCompile *cfg, MonoClass *klass, gboolean for_box, int context_used)
3864 {
3865         MonoInst *iargs [2];
3866         void *alloc_ftn;
3867
3868         if (context_used) {
3869                 MonoInst *data;
3870                 MonoRgctxInfoType rgctx_info;
3871                 MonoInst *iargs [2];
3872                 gboolean known_instance_size = !mini_is_gsharedvt_klass (klass);
3873
3874                 MonoMethod *managed_alloc = mono_gc_get_managed_allocator (klass, for_box, known_instance_size);
3875
3876                 if (cfg->opt & MONO_OPT_SHARED)
3877                         rgctx_info = MONO_RGCTX_INFO_KLASS;
3878                 else
3879                         rgctx_info = MONO_RGCTX_INFO_VTABLE;
3880                 data = mini_emit_get_rgctx_klass (cfg, context_used, klass, rgctx_info);
3881
3882                 if (cfg->opt & MONO_OPT_SHARED) {
3883                         EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
3884                         iargs [1] = data;
3885                         alloc_ftn = ves_icall_object_new;
3886                 } else {
3887                         iargs [0] = data;
3888                         alloc_ftn = ves_icall_object_new_specific;
3889                 }
3890
3891                 if (managed_alloc && !(cfg->opt & MONO_OPT_SHARED)) {
3892                         if (known_instance_size) {
3893                                 int size = mono_class_instance_size (klass);
3894                                 if (size < sizeof (MonoObject))
3895                                         g_error ("Invalid size %d for class %s", size, mono_type_get_full_name (klass));
3896
3897                                 EMIT_NEW_ICONST (cfg, iargs [1], size);
3898                         }
3899                         return mono_emit_method_call (cfg, managed_alloc, iargs, NULL);
3900                 }
3901
3902                 return mono_emit_jit_icall (cfg, alloc_ftn, iargs);
3903         }
3904
3905         if (cfg->opt & MONO_OPT_SHARED) {
3906                 EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
3907                 EMIT_NEW_CLASSCONST (cfg, iargs [1], klass);
3908
3909                 alloc_ftn = ves_icall_object_new;
3910         } else if (cfg->compile_aot && cfg->cbb->out_of_line && klass->type_token && klass->image == mono_defaults.corlib && !mono_class_is_ginst (klass)) {
3911                 /* This happens often in argument checking code, eg. throw new FooException... */
3912                 /* Avoid relocations and save some space by calling a helper function specialized to mscorlib */
3913                 EMIT_NEW_ICONST (cfg, iargs [0], mono_metadata_token_index (klass->type_token));
3914                 return mono_emit_jit_icall (cfg, mono_helper_newobj_mscorlib, iargs);
3915         } else {
3916                 MonoVTable *vtable = mono_class_vtable (cfg->domain, klass);
3917                 MonoMethod *managed_alloc = NULL;
3918                 gboolean pass_lw;
3919
3920                 if (!vtable) {
3921                         mono_cfg_set_exception (cfg, MONO_EXCEPTION_TYPE_LOAD);
3922                         cfg->exception_ptr = klass;
3923                         return NULL;
3924                 }
3925
3926                 managed_alloc = mono_gc_get_managed_allocator (klass, for_box, TRUE);
3927
3928                 if (managed_alloc) {
3929                         int size = mono_class_instance_size (klass);
3930                         if (size < sizeof (MonoObject))
3931                                 g_error ("Invalid size %d for class %s", size, mono_type_get_full_name (klass));
3932
3933                         EMIT_NEW_VTABLECONST (cfg, iargs [0], vtable);
3934                         EMIT_NEW_ICONST (cfg, iargs [1], size);
3935                         return mono_emit_method_call (cfg, managed_alloc, iargs, NULL);
3936                 }
3937                 alloc_ftn = mono_class_get_allocation_ftn (vtable, for_box, &pass_lw);
3938                 if (pass_lw) {
3939                         guint32 lw = vtable->klass->instance_size;
3940                         lw = ((lw + (sizeof (gpointer) - 1)) & ~(sizeof (gpointer) - 1)) / sizeof (gpointer);
3941                         EMIT_NEW_ICONST (cfg, iargs [0], lw);
3942                         EMIT_NEW_VTABLECONST (cfg, iargs [1], vtable);
3943                 }
3944                 else {
3945                         EMIT_NEW_VTABLECONST (cfg, iargs [0], vtable);
3946                 }
3947         }
3948
3949         return mono_emit_jit_icall (cfg, alloc_ftn, iargs);
3950 }
3951         
3952 /*
3953  * Returns NULL and set the cfg exception on error.
3954  */     
3955 static MonoInst*
3956 handle_box (MonoCompile *cfg, MonoInst *val, MonoClass *klass, int context_used)
3957 {
3958         MonoInst *alloc, *ins;
3959
3960         if (mono_class_is_nullable (klass)) {
3961                 MonoMethod* method = mono_class_get_method_from_name (klass, "Box", 1);
3962
3963                 if (context_used) {
3964                         if (cfg->llvm_only && cfg->gsharedvt) {
3965                                 MonoInst *addr = emit_get_rgctx_method (cfg, context_used, method,
3966                                                                                                                 MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
3967                                 return emit_llvmonly_calli (cfg, mono_method_signature (method), &val, addr);
3968                         } else {
3969                                 /* FIXME: What if the class is shared?  We might not
3970                                    have to get the method address from the RGCTX. */
3971                                 MonoInst *addr = emit_get_rgctx_method (cfg, context_used, method,
3972                                                                                                                 MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
3973                                 MonoInst *rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3974
3975                                 return mini_emit_calli (cfg, mono_method_signature (method), &val, addr, NULL, rgctx);
3976                         }
3977                 } else {
3978                         gboolean pass_vtable, pass_mrgctx;
3979                         MonoInst *rgctx_arg = NULL;
3980
3981                         check_method_sharing (cfg, method, &pass_vtable, &pass_mrgctx);
3982                         g_assert (!pass_mrgctx);
3983
3984                         if (pass_vtable) {
3985                                 MonoVTable *vtable = mono_class_vtable (cfg->domain, method->klass);
3986
3987                                 g_assert (vtable);
3988                                 EMIT_NEW_VTABLECONST (cfg, rgctx_arg, vtable);
3989                         }
3990
3991                         return mono_emit_method_call_full (cfg, method, NULL, FALSE, &val, NULL, NULL, rgctx_arg);
3992                 }
3993         }
3994
3995         if (mini_is_gsharedvt_klass (klass)) {
3996                 MonoBasicBlock *is_ref_bb, *is_nullable_bb, *end_bb;
3997                 MonoInst *res, *is_ref, *src_var, *addr;
3998                 int dreg;
3999
4000                 dreg = alloc_ireg (cfg);
4001
4002                 NEW_BBLOCK (cfg, is_ref_bb);
4003                 NEW_BBLOCK (cfg, is_nullable_bb);
4004                 NEW_BBLOCK (cfg, end_bb);
4005                 is_ref = mini_emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_CLASS_BOX_TYPE);
4006                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, is_ref->dreg, MONO_GSHAREDVT_BOX_TYPE_REF);
4007                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, is_ref_bb);
4008
4009                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, is_ref->dreg, MONO_GSHAREDVT_BOX_TYPE_NULLABLE);
4010                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, is_nullable_bb);
4011
4012                 /* Non-ref case */
4013                 alloc = handle_alloc (cfg, klass, TRUE, context_used);
4014                 if (!alloc)
4015                         return NULL;
4016                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, alloc->dreg, sizeof (MonoObject), val->dreg);
4017                 ins->opcode = OP_STOREV_MEMBASE;
4018
4019                 EMIT_NEW_UNALU (cfg, res, OP_MOVE, dreg, alloc->dreg);
4020                 res->type = STACK_OBJ;
4021                 res->klass = klass;
4022                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
4023                 
4024                 /* Ref case */
4025                 MONO_START_BB (cfg, is_ref_bb);
4026
4027                 /* val is a vtype, so has to load the value manually */
4028                 src_var = get_vreg_to_inst (cfg, val->dreg);
4029                 if (!src_var)
4030                         src_var = mono_compile_create_var_for_vreg (cfg, &klass->byval_arg, OP_LOCAL, val->dreg);
4031                 EMIT_NEW_VARLOADA (cfg, addr, src_var, src_var->inst_vtype);
4032                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, dreg, addr->dreg, 0);
4033                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
4034
4035                 /* Nullable case */
4036                 MONO_START_BB (cfg, is_nullable_bb);
4037
4038                 {
4039                         MonoInst *addr = mini_emit_get_gsharedvt_info_klass (cfg, klass,
4040                                                                                                         MONO_RGCTX_INFO_NULLABLE_CLASS_BOX);
4041                         MonoInst *box_call;
4042                         MonoMethodSignature *box_sig;
4043
4044                         /*
4045                          * klass is Nullable<T>, need to call Nullable<T>.Box () using a gsharedvt signature, but we cannot
4046                          * construct that method at JIT time, so have to do things by hand.
4047                          */
4048                         box_sig = (MonoMethodSignature *)mono_mempool_alloc0 (cfg->mempool, MONO_SIZEOF_METHOD_SIGNATURE + (1 * sizeof (MonoType *)));
4049                         box_sig->ret = &mono_defaults.object_class->byval_arg;
4050                         box_sig->param_count = 1;
4051                         box_sig->params [0] = &klass->byval_arg;
4052
4053                         if (cfg->llvm_only)
4054                                 box_call = emit_llvmonly_calli (cfg, box_sig, &val, addr);
4055                         else
4056                                 box_call = mini_emit_calli (cfg, box_sig, &val, addr, NULL, NULL);
4057                         EMIT_NEW_UNALU (cfg, res, OP_MOVE, dreg, box_call->dreg);
4058                         res->type = STACK_OBJ;
4059                         res->klass = klass;
4060                 }
4061
4062                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
4063
4064                 MONO_START_BB (cfg, end_bb);
4065
4066                 return res;
4067         } else {
4068                 alloc = handle_alloc (cfg, klass, TRUE, context_used);
4069                 if (!alloc)
4070                         return NULL;
4071
4072                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, alloc->dreg, sizeof (MonoObject), val->dreg);
4073                 return alloc;
4074         }
4075 }
4076
4077 static GHashTable* direct_icall_type_hash;
4078
4079 static gboolean
4080 icall_is_direct_callable (MonoCompile *cfg, MonoMethod *cmethod)
4081 {
4082         /* LLVM on amd64 can't handle calls to non-32 bit addresses */
4083         if (!direct_icalls_enabled (cfg))
4084                 return FALSE;
4085
4086         /*
4087          * An icall is directly callable if it doesn't directly or indirectly call mono_raise_exception ().
4088          * Whitelist a few icalls for now.
4089          */
4090         if (!direct_icall_type_hash) {
4091                 GHashTable *h = g_hash_table_new (g_str_hash, g_str_equal);
4092
4093                 g_hash_table_insert (h, (char*)"Decimal", GUINT_TO_POINTER (1));
4094                 g_hash_table_insert (h, (char*)"Number", GUINT_TO_POINTER (1));
4095                 g_hash_table_insert (h, (char*)"Buffer", GUINT_TO_POINTER (1));
4096                 g_hash_table_insert (h, (char*)"Monitor", GUINT_TO_POINTER (1));
4097                 mono_memory_barrier ();
4098                 direct_icall_type_hash = h;
4099         }
4100
4101         if (cmethod->klass == mono_defaults.math_class)
4102                 return TRUE;
4103         /* No locking needed */
4104         if (cmethod->klass->image == mono_defaults.corlib && g_hash_table_lookup (direct_icall_type_hash, cmethod->klass->name))
4105                 return TRUE;
4106         return FALSE;
4107 }
4108
4109 static gboolean
4110 method_needs_stack_walk (MonoCompile *cfg, MonoMethod *cmethod)
4111 {
4112         if (cmethod->klass == mono_defaults.systemtype_class) {
4113                 if (!strcmp (cmethod->name, "GetType"))
4114                         return TRUE;
4115         }
4116         return FALSE;
4117 }
4118
4119 static G_GNUC_UNUSED MonoInst*
4120 handle_enum_has_flag (MonoCompile *cfg, MonoClass *klass, MonoInst *enum_this, MonoInst *enum_flag)
4121 {
4122         MonoType *enum_type = mono_type_get_underlying_type (&klass->byval_arg);
4123         guint32 load_opc = mono_type_to_load_membase (cfg, enum_type);
4124         gboolean is_i4;
4125
4126         switch (enum_type->type) {
4127         case MONO_TYPE_I8:
4128         case MONO_TYPE_U8:
4129 #if SIZEOF_REGISTER == 8
4130         case MONO_TYPE_I:
4131         case MONO_TYPE_U:
4132 #endif
4133                 is_i4 = FALSE;
4134                 break;
4135         default:
4136                 is_i4 = TRUE;
4137                 break;
4138         }
4139
4140         {
4141                 MonoInst *load, *and_, *cmp, *ceq;
4142                 int enum_reg = is_i4 ? alloc_ireg (cfg) : alloc_lreg (cfg);
4143                 int and_reg = is_i4 ? alloc_ireg (cfg) : alloc_lreg (cfg);
4144                 int dest_reg = alloc_ireg (cfg);
4145
4146                 EMIT_NEW_LOAD_MEMBASE (cfg, load, load_opc, enum_reg, enum_this->dreg, 0);
4147                 EMIT_NEW_BIALU (cfg, and_, is_i4 ? OP_IAND : OP_LAND, and_reg, enum_reg, enum_flag->dreg);
4148                 EMIT_NEW_BIALU (cfg, cmp, is_i4 ? OP_ICOMPARE : OP_LCOMPARE, -1, and_reg, enum_flag->dreg);
4149                 EMIT_NEW_UNALU (cfg, ceq, is_i4 ? OP_ICEQ : OP_LCEQ, dest_reg, -1);
4150
4151                 ceq->type = STACK_I4;
4152
4153                 if (!is_i4) {
4154                         load = mono_decompose_opcode (cfg, load);
4155                         and_ = mono_decompose_opcode (cfg, and_);
4156                         cmp = mono_decompose_opcode (cfg, cmp);
4157                         ceq = mono_decompose_opcode (cfg, ceq);
4158                 }
4159
4160                 return ceq;
4161         }
4162 }
4163
4164 /*
4165  * Returns NULL and set the cfg exception on error.
4166  */
4167 static G_GNUC_UNUSED MonoInst*
4168 handle_delegate_ctor (MonoCompile *cfg, MonoClass *klass, MonoInst *target, MonoMethod *method, int context_used, gboolean virtual_)
4169 {
4170         MonoInst *ptr;
4171         int dreg;
4172         gpointer trampoline;
4173         MonoInst *obj, *method_ins, *tramp_ins;
4174         MonoDomain *domain;
4175         guint8 **code_slot;
4176
4177         if (virtual_ && !cfg->llvm_only) {
4178                 MonoMethod *invoke = mono_get_delegate_invoke (klass);
4179                 g_assert (invoke);
4180
4181                 if (!mono_get_delegate_virtual_invoke_impl (mono_method_signature (invoke), context_used ? NULL : method))
4182                         return NULL;
4183         }
4184
4185         obj = handle_alloc (cfg, klass, FALSE, mono_class_check_context_used (klass));
4186         if (!obj)
4187                 return NULL;
4188
4189         /* Inline the contents of mono_delegate_ctor */
4190
4191         /* Set target field */
4192         /* Optimize away setting of NULL target */
4193         if (!MONO_INS_IS_PCONST_NULL (target)) {
4194                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, target), target->dreg);
4195                 if (cfg->gen_write_barriers) {
4196                         dreg = alloc_preg (cfg);
4197                         EMIT_NEW_BIALU_IMM (cfg, ptr, OP_PADD_IMM, dreg, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, target));
4198                         mini_emit_write_barrier (cfg, ptr, target);
4199                 }
4200         }
4201
4202         /* Set method field */
4203         method_ins = emit_get_rgctx_method (cfg, context_used, method, MONO_RGCTX_INFO_METHOD);
4204         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, method), method_ins->dreg);
4205
4206         /* 
4207          * To avoid looking up the compiled code belonging to the target method
4208          * in mono_delegate_trampoline (), we allocate a per-domain memory slot to
4209          * store it, and we fill it after the method has been compiled.
4210          */
4211         if (!method->dynamic && !(cfg->opt & MONO_OPT_SHARED)) {
4212                 MonoInst *code_slot_ins;
4213
4214                 if (context_used) {
4215                         code_slot_ins = emit_get_rgctx_method (cfg, context_used, method, MONO_RGCTX_INFO_METHOD_DELEGATE_CODE);
4216                 } else {
4217                         domain = mono_domain_get ();
4218                         mono_domain_lock (domain);
4219                         if (!domain_jit_info (domain)->method_code_hash)
4220                                 domain_jit_info (domain)->method_code_hash = g_hash_table_new (NULL, NULL);
4221                         code_slot = (guint8 **)g_hash_table_lookup (domain_jit_info (domain)->method_code_hash, method);
4222                         if (!code_slot) {
4223                                 code_slot = (guint8 **)mono_domain_alloc0 (domain, sizeof (gpointer));
4224                                 g_hash_table_insert (domain_jit_info (domain)->method_code_hash, method, code_slot);
4225                         }
4226                         mono_domain_unlock (domain);
4227
4228                         code_slot_ins = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_METHOD_CODE_SLOT, method);
4229                 }
4230                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, method_code), code_slot_ins->dreg);                
4231         }
4232
4233         if (cfg->llvm_only) {
4234                 MonoInst *args [16];
4235
4236                 if (virtual_) {
4237                         args [0] = obj;
4238                         args [1] = target;
4239                         args [2] = emit_get_rgctx_method (cfg, context_used, method, MONO_RGCTX_INFO_METHOD);
4240                         mono_emit_jit_icall (cfg, mono_llvmonly_init_delegate_virtual, args);
4241                 } else {
4242                         args [0] = obj;
4243                         mono_emit_jit_icall (cfg, mono_llvmonly_init_delegate, args);
4244                 }
4245
4246                 return obj;
4247         }
4248
4249         if (cfg->compile_aot) {
4250                 MonoDelegateClassMethodPair *del_tramp;
4251
4252                 del_tramp = (MonoDelegateClassMethodPair *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoDelegateClassMethodPair));
4253                 del_tramp->klass = klass;
4254                 del_tramp->method = context_used ? NULL : method;
4255                 del_tramp->is_virtual = virtual_;
4256                 EMIT_NEW_AOTCONST (cfg, tramp_ins, MONO_PATCH_INFO_DELEGATE_TRAMPOLINE, del_tramp);
4257         } else {
4258                 if (virtual_)
4259                         trampoline = mono_create_delegate_virtual_trampoline (cfg->domain, klass, context_used ? NULL : method);
4260                 else
4261                         trampoline = mono_create_delegate_trampoline_info (cfg->domain, klass, context_used ? NULL : method);
4262                 EMIT_NEW_PCONST (cfg, tramp_ins, trampoline);
4263         }
4264
4265         /* Set invoke_impl field */
4266         if (virtual_) {
4267                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, invoke_impl), tramp_ins->dreg);
4268         } else {
4269                 dreg = alloc_preg (cfg);
4270                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, dreg, tramp_ins->dreg, MONO_STRUCT_OFFSET (MonoDelegateTrampInfo, invoke_impl));
4271                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, invoke_impl), dreg);
4272
4273                 dreg = alloc_preg (cfg);
4274                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, dreg, tramp_ins->dreg, MONO_STRUCT_OFFSET (MonoDelegateTrampInfo, method_ptr));
4275                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, method_ptr), dreg);
4276         }
4277
4278         dreg = alloc_preg (cfg);
4279         MONO_EMIT_NEW_ICONST (cfg, dreg, virtual_ ? 1 : 0);
4280         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI1_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, method_is_virtual), dreg);
4281
4282         /* All the checks which are in mono_delegate_ctor () are done by the delegate trampoline */
4283
4284         return obj;
4285 }
4286
4287 static MonoInst*
4288 handle_array_new (MonoCompile *cfg, int rank, MonoInst **sp, unsigned char *ip)
4289 {
4290         MonoJitICallInfo *info;
4291
4292         /* Need to register the icall so it gets an icall wrapper */
4293         info = mono_get_array_new_va_icall (rank);
4294
4295         cfg->flags |= MONO_CFG_HAS_VARARGS;
4296
4297         /* mono_array_new_va () needs a vararg calling convention */
4298         cfg->exception_message = g_strdup ("array-new");
4299         cfg->disable_llvm = TRUE;
4300
4301         /* FIXME: This uses info->sig, but it should use the signature of the wrapper */
4302         return mono_emit_native_call (cfg, mono_icall_get_wrapper (info), info->sig, sp);
4303 }
4304
4305 /*
4306  * handle_constrained_gsharedvt_call:
4307  *
4308  *   Handle constrained calls where the receiver is a gsharedvt type.
4309  * Return the instruction representing the call. Set the cfg exception on failure.
4310  */
4311 static MonoInst*
4312 handle_constrained_gsharedvt_call (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **sp, MonoClass *constrained_class,
4313                                                                    gboolean *ref_emit_widen)
4314 {
4315         MonoInst *ins = NULL;
4316         gboolean emit_widen = *ref_emit_widen;
4317
4318         /*
4319          * Constrained calls need to behave differently at runtime dependending on whenever the receiver is instantiated as ref type or as a vtype.
4320          * This is hard to do with the current call code, since we would have to emit a branch and two different calls. So instead, we
4321          * pack the arguments into an array, and do the rest of the work in in an icall.
4322          */
4323         if (((cmethod->klass == mono_defaults.object_class) || mono_class_is_interface (cmethod->klass) || (!cmethod->klass->valuetype && cmethod->klass->image != mono_defaults.corlib)) &&
4324                 (MONO_TYPE_IS_VOID (fsig->ret) || MONO_TYPE_IS_PRIMITIVE (fsig->ret) || MONO_TYPE_IS_REFERENCE (fsig->ret) || MONO_TYPE_ISSTRUCT (fsig->ret) || mono_class_is_enum (mono_class_from_mono_type (fsig->ret)) || mini_is_gsharedvt_type (fsig->ret)) &&
4325                 (fsig->param_count == 0 || (!fsig->hasthis && fsig->param_count == 1) || (fsig->param_count == 1 && (MONO_TYPE_IS_REFERENCE (fsig->params [0]) || fsig->params [0]->byref || mini_is_gsharedvt_type (fsig->params [0]))))) {
4326                 MonoInst *args [16];
4327
4328                 /*
4329                  * This case handles calls to
4330                  * - object:ToString()/Equals()/GetHashCode(),
4331                  * - System.IComparable<T>:CompareTo()
4332                  * - System.IEquatable<T>:Equals ()
4333                  * plus some simple interface calls enough to support AsyncTaskMethodBuilder.
4334                  */
4335
4336                 args [0] = sp [0];
4337                 if (mono_method_check_context_used (cmethod))
4338                         args [1] = emit_get_rgctx_method (cfg, mono_method_check_context_used (cmethod), cmethod, MONO_RGCTX_INFO_METHOD);
4339                 else
4340                         EMIT_NEW_METHODCONST (cfg, args [1], cmethod);
4341                 args [2] = mini_emit_get_rgctx_klass (cfg, mono_class_check_context_used (constrained_class), constrained_class, MONO_RGCTX_INFO_KLASS);
4342
4343                 /* !fsig->hasthis is for the wrapper for the Object.GetType () icall */
4344                 if (fsig->hasthis && fsig->param_count) {
4345                         /* Pass the arguments using a localloc-ed array using the format expected by runtime_invoke () */
4346                         MONO_INST_NEW (cfg, ins, OP_LOCALLOC_IMM);
4347                         ins->dreg = alloc_preg (cfg);
4348                         ins->inst_imm = fsig->param_count * sizeof (mgreg_t);
4349                         MONO_ADD_INS (cfg->cbb, ins);
4350                         args [4] = ins;
4351
4352                         if (mini_is_gsharedvt_type (fsig->params [0])) {
4353                                 int addr_reg, deref_arg_reg;
4354
4355                                 ins = mini_emit_get_gsharedvt_info_klass (cfg, mono_class_from_mono_type (fsig->params [0]), MONO_RGCTX_INFO_CLASS_BOX_TYPE);
4356                                 deref_arg_reg = alloc_preg (cfg);
4357                                 /* deref_arg = BOX_TYPE != MONO_GSHAREDVT_BOX_TYPE_VTYPE */
4358                                 EMIT_NEW_BIALU_IMM (cfg, args [3], OP_ISUB_IMM, deref_arg_reg, ins->dreg, 1);
4359
4360                                 EMIT_NEW_VARLOADA_VREG (cfg, ins, sp [1]->dreg, fsig->params [0]);
4361                                 addr_reg = ins->dreg;
4362                                 EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STORE_MEMBASE_REG, args [4]->dreg, 0, addr_reg);
4363                         } else {
4364                                 EMIT_NEW_ICONST (cfg, args [3], 0);
4365                                 EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STORE_MEMBASE_REG, args [4]->dreg, 0, sp [1]->dreg);
4366                         }
4367                 } else {
4368                         EMIT_NEW_ICONST (cfg, args [3], 0);
4369                         EMIT_NEW_ICONST (cfg, args [4], 0);
4370                 }
4371                 ins = mono_emit_jit_icall (cfg, mono_gsharedvt_constrained_call, args);
4372                 emit_widen = FALSE;
4373
4374                 if (mini_is_gsharedvt_type (fsig->ret)) {
4375                         ins = handle_unbox_gsharedvt (cfg, mono_class_from_mono_type (fsig->ret), ins);
4376                 } else if (MONO_TYPE_IS_PRIMITIVE (fsig->ret) || MONO_TYPE_ISSTRUCT (fsig->ret) || mono_class_is_enum (mono_class_from_mono_type (fsig->ret))) {
4377                         MonoInst *add;
4378
4379                         /* Unbox */
4380                         NEW_BIALU_IMM (cfg, add, OP_ADD_IMM, alloc_dreg (cfg, STACK_MP), ins->dreg, sizeof (MonoObject));
4381                         MONO_ADD_INS (cfg->cbb, add);
4382                         /* Load value */
4383                         NEW_LOAD_MEMBASE_TYPE (cfg, ins, fsig->ret, add->dreg, 0);
4384                         MONO_ADD_INS (cfg->cbb, ins);
4385                         /* ins represents the call result */
4386                 }
4387         } else {
4388                 GSHAREDVT_FAILURE (CEE_CALLVIRT);
4389         }
4390
4391         *ref_emit_widen = emit_widen;
4392
4393         return ins;
4394
4395  exception_exit:
4396         return NULL;
4397 }
4398
4399 static void
4400 mono_emit_load_got_addr (MonoCompile *cfg)
4401 {
4402         MonoInst *getaddr, *dummy_use;
4403
4404         if (!cfg->got_var || cfg->got_var_allocated)
4405                 return;
4406
4407         MONO_INST_NEW (cfg, getaddr, OP_LOAD_GOTADDR);
4408         getaddr->cil_code = cfg->header->code;
4409         getaddr->dreg = cfg->got_var->dreg;
4410
4411         /* Add it to the start of the first bblock */
4412         if (cfg->bb_entry->code) {
4413                 getaddr->next = cfg->bb_entry->code;
4414                 cfg->bb_entry->code = getaddr;
4415         }
4416         else
4417                 MONO_ADD_INS (cfg->bb_entry, getaddr);
4418
4419         cfg->got_var_allocated = TRUE;
4420
4421         /* 
4422          * Add a dummy use to keep the got_var alive, since real uses might
4423          * only be generated by the back ends.
4424          * Add it to end_bblock, so the variable's lifetime covers the whole
4425          * method.
4426          * It would be better to make the usage of the got var explicit in all
4427          * cases when the backend needs it (i.e. calls, throw etc.), so this
4428          * wouldn't be needed.
4429          */
4430         NEW_DUMMY_USE (cfg, dummy_use, cfg->got_var);
4431         MONO_ADD_INS (cfg->bb_exit, dummy_use);
4432 }
4433
4434 static int inline_limit;
4435 static gboolean inline_limit_inited;
4436
4437 static gboolean
4438 mono_method_check_inlining (MonoCompile *cfg, MonoMethod *method)
4439 {
4440         MonoMethodHeaderSummary header;
4441         MonoVTable *vtable;
4442 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
4443         MonoMethodSignature *sig = mono_method_signature (method);
4444         int i;
4445 #endif
4446
4447         if (cfg->disable_inline)
4448                 return FALSE;
4449         if (cfg->gsharedvt)
4450                 return FALSE;
4451
4452         if (cfg->inline_depth > 10)
4453                 return FALSE;
4454
4455         if (!mono_method_get_header_summary (method, &header))
4456                 return FALSE;
4457
4458         /*runtime, icall and pinvoke are checked by summary call*/
4459         if ((method->iflags & METHOD_IMPL_ATTRIBUTE_NOINLINING) ||
4460             (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) ||
4461             (mono_class_is_marshalbyref (method->klass)) ||
4462             header.has_clauses)
4463                 return FALSE;
4464
4465         /* also consider num_locals? */
4466         /* Do the size check early to avoid creating vtables */
4467         if (!inline_limit_inited) {
4468                 char *inlinelimit;
4469                 if ((inlinelimit = g_getenv ("MONO_INLINELIMIT"))) {
4470                         inline_limit = atoi (inlinelimit);
4471                         g_free (inlinelimit);
4472                 } else
4473                         inline_limit = INLINE_LENGTH_LIMIT;
4474                 inline_limit_inited = TRUE;
4475         }
4476         if (header.code_size >= inline_limit && !(method->iflags & METHOD_IMPL_ATTRIBUTE_AGGRESSIVE_INLINING))
4477                 return FALSE;
4478
4479         /*
4480          * if we can initialize the class of the method right away, we do,
4481          * otherwise we don't allow inlining if the class needs initialization,
4482          * since it would mean inserting a call to mono_runtime_class_init()
4483          * inside the inlined code
4484          */
4485         if (cfg->gshared && method->klass->has_cctor && mini_class_check_context_used (cfg, method->klass))
4486                 return FALSE;
4487
4488         if (!(cfg->opt & MONO_OPT_SHARED)) {
4489                 /* The AggressiveInlining hint is a good excuse to force that cctor to run. */
4490                 if (method->iflags & METHOD_IMPL_ATTRIBUTE_AGGRESSIVE_INLINING) {
4491                         if (method->klass->has_cctor) {
4492                                 vtable = mono_class_vtable (cfg->domain, method->klass);
4493                                 if (!vtable)
4494                                         return FALSE;
4495                                 if (!cfg->compile_aot) {
4496                                         MonoError error;
4497                                         if (!mono_runtime_class_init_full (vtable, &error)) {
4498                                                 mono_error_cleanup (&error);
4499                                                 return FALSE;
4500                                         }
4501                                 }
4502                         }
4503                 } else if (mono_class_is_before_field_init (method->klass)) {
4504                         if (cfg->run_cctors && method->klass->has_cctor) {
4505                                 /*FIXME it would easier and lazier to just use mono_class_try_get_vtable */
4506                                 if (!method->klass->runtime_info)
4507                                         /* No vtable created yet */
4508                                         return FALSE;
4509                                 vtable = mono_class_vtable (cfg->domain, method->klass);
4510                                 if (!vtable)
4511                                         return FALSE;
4512                                 /* This makes so that inline cannot trigger */
4513                                 /* .cctors: too many apps depend on them */
4514                                 /* running with a specific order... */
4515                                 if (! vtable->initialized)
4516                                         return FALSE;
4517                                 MonoError error;
4518                                 if (!mono_runtime_class_init_full (vtable, &error)) {
4519                                         mono_error_cleanup (&error);
4520                                         return FALSE;
4521                                 }
4522                         }
4523                 } else if (mono_class_needs_cctor_run (method->klass, NULL)) {
4524                         if (!method->klass->runtime_info)
4525                                 /* No vtable created yet */
4526                                 return FALSE;
4527                         vtable = mono_class_vtable (cfg->domain, method->klass);
4528                         if (!vtable)
4529                                 return FALSE;
4530                         if (!vtable->initialized)
4531                                 return FALSE;
4532                 }
4533         } else {
4534                 /* 
4535                  * If we're compiling for shared code
4536                  * the cctor will need to be run at aot method load time, for example,
4537                  * or at the end of the compilation of the inlining method.
4538                  */
4539                 if (mono_class_needs_cctor_run (method->klass, NULL) && !mono_class_is_before_field_init (method->klass))
4540                         return FALSE;
4541         }
4542
4543 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
4544         if (mono_arch_is_soft_float ()) {
4545                 /* FIXME: */
4546                 if (sig->ret && sig->ret->type == MONO_TYPE_R4)
4547                         return FALSE;
4548                 for (i = 0; i < sig->param_count; ++i)
4549                         if (!sig->params [i]->byref && sig->params [i]->type == MONO_TYPE_R4)
4550                                 return FALSE;
4551         }
4552 #endif
4553
4554         if (g_list_find (cfg->dont_inline, method))
4555                 return FALSE;
4556
4557         return TRUE;
4558 }
4559
4560 static gboolean
4561 mini_field_access_needs_cctor_run (MonoCompile *cfg, MonoMethod *method, MonoClass *klass, MonoVTable *vtable)
4562 {
4563         if (!cfg->compile_aot) {
4564                 g_assert (vtable);
4565                 if (vtable->initialized)
4566                         return FALSE;
4567         }
4568
4569         if (mono_class_is_before_field_init (klass)) {
4570                 if (cfg->method == method)
4571                         return FALSE;
4572         }
4573
4574         if (!mono_class_needs_cctor_run (klass, method))
4575                 return FALSE;
4576
4577         if (! (method->flags & METHOD_ATTRIBUTE_STATIC) && (klass == method->klass))
4578                 /* The initialization is already done before the method is called */
4579                 return FALSE;
4580
4581         return TRUE;
4582 }
4583
4584 MonoInst*
4585 mini_emit_ldelema_1_ins (MonoCompile *cfg, MonoClass *klass, MonoInst *arr, MonoInst *index, gboolean bcheck)
4586 {
4587         MonoInst *ins;
4588         guint32 size;
4589         int mult_reg, add_reg, array_reg, index_reg, index2_reg;
4590         int context_used;
4591
4592         if (mini_is_gsharedvt_variable_klass (klass)) {
4593                 size = -1;
4594         } else {
4595                 mono_class_init (klass);
4596                 size = mono_class_array_element_size (klass);
4597         }
4598
4599         mult_reg = alloc_preg (cfg);
4600         array_reg = arr->dreg;
4601         index_reg = index->dreg;
4602
4603 #if SIZEOF_REGISTER == 8
4604         /* The array reg is 64 bits but the index reg is only 32 */
4605         if (COMPILE_LLVM (cfg)) {
4606                 /*
4607                  * abcrem can't handle the OP_SEXT_I4, so add this after abcrem,
4608                  * during OP_BOUNDS_CHECK decomposition, and in the implementation
4609                  * of OP_X86_LEA for llvm.
4610                  */
4611                 index2_reg = index_reg;
4612         } else {
4613                 index2_reg = alloc_preg (cfg);
4614                 MONO_EMIT_NEW_UNALU (cfg, OP_SEXT_I4, index2_reg, index_reg);
4615         }
4616 #else
4617         if (index->type == STACK_I8) {
4618                 index2_reg = alloc_preg (cfg);
4619                 MONO_EMIT_NEW_UNALU (cfg, OP_LCONV_TO_I4, index2_reg, index_reg);
4620         } else {
4621                 index2_reg = index_reg;
4622         }
4623 #endif
4624
4625         if (bcheck)
4626                 MONO_EMIT_BOUNDS_CHECK (cfg, array_reg, MonoArray, max_length, index2_reg);
4627
4628 #if defined(TARGET_X86) || defined(TARGET_AMD64)
4629         if (size == 1 || size == 2 || size == 4 || size == 8) {
4630                 static const int fast_log2 [] = { 1, 0, 1, -1, 2, -1, -1, -1, 3 };
4631
4632                 EMIT_NEW_X86_LEA (cfg, ins, array_reg, index2_reg, fast_log2 [size], MONO_STRUCT_OFFSET (MonoArray, vector));
4633                 ins->klass = mono_class_get_element_class (klass);
4634                 ins->type = STACK_MP;
4635
4636                 return ins;
4637         }
4638 #endif          
4639
4640         add_reg = alloc_ireg_mp (cfg);
4641
4642         if (size == -1) {
4643                 MonoInst *rgctx_ins;
4644
4645                 /* gsharedvt */
4646                 g_assert (cfg->gshared);
4647                 context_used = mini_class_check_context_used (cfg, klass);
4648                 g_assert (context_used);
4649                 rgctx_ins = mini_emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_ARRAY_ELEMENT_SIZE);
4650                 MONO_EMIT_NEW_BIALU (cfg, OP_IMUL, mult_reg, index2_reg, rgctx_ins->dreg);
4651         } else {
4652                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_MUL_IMM, mult_reg, index2_reg, size);
4653         }
4654         MONO_EMIT_NEW_BIALU (cfg, OP_PADD, add_reg, array_reg, mult_reg);
4655         NEW_BIALU_IMM (cfg, ins, OP_PADD_IMM, add_reg, add_reg, MONO_STRUCT_OFFSET (MonoArray, vector));
4656         ins->klass = mono_class_get_element_class (klass);
4657         ins->type = STACK_MP;
4658         MONO_ADD_INS (cfg->cbb, ins);
4659
4660         return ins;
4661 }
4662
4663 static MonoInst*
4664 mini_emit_ldelema_2_ins (MonoCompile *cfg, MonoClass *klass, MonoInst *arr, MonoInst *index_ins1, MonoInst *index_ins2)
4665 {
4666         int bounds_reg = alloc_preg (cfg);
4667         int add_reg = alloc_ireg_mp (cfg);
4668         int mult_reg = alloc_preg (cfg);
4669         int mult2_reg = alloc_preg (cfg);
4670         int low1_reg = alloc_preg (cfg);
4671         int low2_reg = alloc_preg (cfg);
4672         int high1_reg = alloc_preg (cfg);
4673         int high2_reg = alloc_preg (cfg);
4674         int realidx1_reg = alloc_preg (cfg);
4675         int realidx2_reg = alloc_preg (cfg);
4676         int sum_reg = alloc_preg (cfg);
4677         int index1, index2, tmpreg;
4678         MonoInst *ins;
4679         guint32 size;
4680
4681         mono_class_init (klass);
4682         size = mono_class_array_element_size (klass);
4683
4684         index1 = index_ins1->dreg;
4685         index2 = index_ins2->dreg;
4686
4687 #if SIZEOF_REGISTER == 8
4688         /* The array reg is 64 bits but the index reg is only 32 */
4689         if (COMPILE_LLVM (cfg)) {
4690                 /* Not needed */
4691         } else {
4692                 tmpreg = alloc_preg (cfg);
4693                 MONO_EMIT_NEW_UNALU (cfg, OP_SEXT_I4, tmpreg, index1);
4694                 index1 = tmpreg;
4695                 tmpreg = alloc_preg (cfg);
4696                 MONO_EMIT_NEW_UNALU (cfg, OP_SEXT_I4, tmpreg, index2);
4697                 index2 = tmpreg;
4698         }
4699 #else
4700         // FIXME: Do we need to do something here for i8 indexes, like in ldelema_1_ins ?
4701         tmpreg = -1;
4702 #endif
4703
4704         /* range checking */
4705         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, bounds_reg, 
4706                                        arr->dreg, MONO_STRUCT_OFFSET (MonoArray, bounds));
4707
4708         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, low1_reg, 
4709                                        bounds_reg, MONO_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
4710         MONO_EMIT_NEW_BIALU (cfg, OP_PSUB, realidx1_reg, index1, low1_reg);
4711         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, high1_reg, 
4712                                        bounds_reg, MONO_STRUCT_OFFSET (MonoArrayBounds, length));
4713         MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, high1_reg, realidx1_reg);
4714         MONO_EMIT_NEW_COND_EXC (cfg, LE_UN, "IndexOutOfRangeException");
4715
4716         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, low2_reg, 
4717                                        bounds_reg, sizeof (MonoArrayBounds) + MONO_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
4718         MONO_EMIT_NEW_BIALU (cfg, OP_PSUB, realidx2_reg, index2, low2_reg);
4719         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, high2_reg, 
4720                                        bounds_reg, sizeof (MonoArrayBounds) + MONO_STRUCT_OFFSET (MonoArrayBounds, length));
4721         MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, high2_reg, realidx2_reg);
4722         MONO_EMIT_NEW_COND_EXC (cfg, LE_UN, "IndexOutOfRangeException");
4723
4724         MONO_EMIT_NEW_BIALU (cfg, OP_PMUL, mult_reg, high2_reg, realidx1_reg);
4725         MONO_EMIT_NEW_BIALU (cfg, OP_PADD, sum_reg, mult_reg, realidx2_reg);
4726         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PMUL_IMM, mult2_reg, sum_reg, size);
4727         MONO_EMIT_NEW_BIALU (cfg, OP_PADD, add_reg, mult2_reg, arr->dreg);
4728         NEW_BIALU_IMM (cfg, ins, OP_PADD_IMM, add_reg, add_reg, MONO_STRUCT_OFFSET (MonoArray, vector));
4729
4730         ins->type = STACK_MP;
4731         ins->klass = klass;
4732         MONO_ADD_INS (cfg->cbb, ins);
4733
4734         return ins;
4735 }
4736
4737 static MonoInst*
4738 mini_emit_ldelema_ins (MonoCompile *cfg, MonoMethod *cmethod, MonoInst **sp, unsigned char *ip, gboolean is_set)
4739 {
4740         int rank;
4741         MonoInst *addr;
4742         MonoMethod *addr_method;
4743         int element_size;
4744         MonoClass *eclass = cmethod->klass->element_class;
4745
4746         rank = mono_method_signature (cmethod)->param_count - (is_set? 1: 0);
4747
4748         if (rank == 1)
4749                 return mini_emit_ldelema_1_ins (cfg, eclass, sp [0], sp [1], TRUE);
4750
4751         /* emit_ldelema_2 depends on OP_LMUL */
4752         if (!cfg->backend->emulate_mul_div && rank == 2 && (cfg->opt & MONO_OPT_INTRINS) && !mini_is_gsharedvt_variable_klass (eclass)) {
4753                 return mini_emit_ldelema_2_ins (cfg, eclass, sp [0], sp [1], sp [2]);
4754         }
4755
4756         if (mini_is_gsharedvt_variable_klass (eclass))
4757                 element_size = 0;
4758         else
4759                 element_size = mono_class_array_element_size (eclass);
4760         addr_method = mono_marshal_get_array_address (rank, element_size);
4761         addr = mono_emit_method_call (cfg, addr_method, sp, NULL);
4762
4763         return addr;
4764 }
4765
4766 static MonoBreakPolicy
4767 always_insert_breakpoint (MonoMethod *method)
4768 {
4769         return MONO_BREAK_POLICY_ALWAYS;
4770 }
4771
4772 static MonoBreakPolicyFunc break_policy_func = always_insert_breakpoint;
4773
4774 /**
4775  * mono_set_break_policy:
4776  * \param policy_callback the new callback function
4777  *
4778  * Allow embedders to decide wherther to actually obey breakpoint instructions
4779  * (both break IL instructions and \c Debugger.Break method calls), for example
4780  * to not allow an app to be aborted by a perfectly valid IL opcode when executing
4781  * untrusted or semi-trusted code.
4782  *
4783  * \p policy_callback will be called every time a break point instruction needs to
4784  * be inserted with the method argument being the method that calls \c Debugger.Break
4785  * or has the IL \c break instruction. The callback should return \c MONO_BREAK_POLICY_NEVER
4786  * if it wants the breakpoint to not be effective in the given method.
4787  * \c MONO_BREAK_POLICY_ALWAYS is the default.
4788  */
4789 void
4790 mono_set_break_policy (MonoBreakPolicyFunc policy_callback)
4791 {
4792         if (policy_callback)
4793                 break_policy_func = policy_callback;
4794         else
4795                 break_policy_func = always_insert_breakpoint;
4796 }
4797
4798 static gboolean
4799 should_insert_brekpoint (MonoMethod *method) {
4800         switch (break_policy_func (method)) {
4801         case MONO_BREAK_POLICY_ALWAYS:
4802                 return TRUE;
4803         case MONO_BREAK_POLICY_NEVER:
4804                 return FALSE;
4805         case MONO_BREAK_POLICY_ON_DBG:
4806                 g_warning ("mdb no longer supported");
4807                 return FALSE;
4808         default:
4809                 g_warning ("Incorrect value returned from break policy callback");
4810                 return FALSE;
4811         }
4812 }
4813
4814 /* optimize the simple GetGenericValueImpl/SetGenericValueImpl generic icalls */
4815 static MonoInst*
4816 emit_array_generic_access (MonoCompile *cfg, MonoMethodSignature *fsig, MonoInst **args, int is_set)
4817 {
4818         MonoInst *addr, *store, *load;
4819         MonoClass *eklass = mono_class_from_mono_type (fsig->params [2]);
4820
4821         /* the bounds check is already done by the callers */
4822         addr = mini_emit_ldelema_1_ins (cfg, eklass, args [0], args [1], FALSE);
4823         if (is_set) {
4824                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, load, &eklass->byval_arg, args [2]->dreg, 0);
4825                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, store, &eklass->byval_arg, addr->dreg, 0, load->dreg);
4826                 if (mini_type_is_reference (&eklass->byval_arg))
4827                         mini_emit_write_barrier (cfg, addr, load);
4828         } else {
4829                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, load, &eklass->byval_arg, addr->dreg, 0);
4830                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, store, &eklass->byval_arg, args [2]->dreg, 0, load->dreg);
4831         }
4832         return store;
4833 }
4834
4835
4836 static gboolean
4837 generic_class_is_reference_type (MonoCompile *cfg, MonoClass *klass)
4838 {
4839         return mini_type_is_reference (&klass->byval_arg);
4840 }
4841
4842 static MonoInst*
4843 emit_array_store (MonoCompile *cfg, MonoClass *klass, MonoInst **sp, gboolean safety_checks)
4844 {
4845         if (safety_checks && generic_class_is_reference_type (cfg, klass) &&
4846                 !(MONO_INS_IS_PCONST_NULL (sp [2]))) {
4847                 MonoClass *obj_array = mono_array_class_get_cached (mono_defaults.object_class, 1);
4848                 MonoMethod *helper = mono_marshal_get_virtual_stelemref (obj_array);
4849                 MonoInst *iargs [3];
4850
4851                 if (!helper->slot)
4852                         mono_class_setup_vtable (obj_array);
4853                 g_assert (helper->slot);
4854
4855                 if (sp [0]->type != STACK_OBJ)
4856                         return NULL;
4857                 if (sp [2]->type != STACK_OBJ)
4858                         return NULL;
4859
4860                 iargs [2] = sp [2];
4861                 iargs [1] = sp [1];
4862                 iargs [0] = sp [0];
4863
4864                 return mono_emit_method_call (cfg, helper, iargs, sp [0]);
4865         } else {
4866                 MonoInst *ins;
4867
4868                 if (mini_is_gsharedvt_variable_klass (klass)) {
4869                         MonoInst *addr;
4870
4871                         // FIXME-VT: OP_ICONST optimization
4872                         addr = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1], TRUE);
4873                         EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr->dreg, 0, sp [2]->dreg);
4874                         ins->opcode = OP_STOREV_MEMBASE;
4875                 } else if (sp [1]->opcode == OP_ICONST) {
4876                         int array_reg = sp [0]->dreg;
4877                         int index_reg = sp [1]->dreg;
4878                         int offset = (mono_class_array_element_size (klass) * sp [1]->inst_c0) + MONO_STRUCT_OFFSET (MonoArray, vector);
4879
4880                         if (SIZEOF_REGISTER == 8 && COMPILE_LLVM (cfg))
4881                                 MONO_EMIT_NEW_UNALU (cfg, OP_ZEXT_I4, index_reg, index_reg);
4882
4883                         if (safety_checks)
4884                                 MONO_EMIT_BOUNDS_CHECK (cfg, array_reg, MonoArray, max_length, index_reg);
4885                         EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, array_reg, offset, sp [2]->dreg);
4886                 } else {
4887                         MonoInst *addr = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1], safety_checks);
4888                         EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr->dreg, 0, sp [2]->dreg);
4889                         if (generic_class_is_reference_type (cfg, klass))
4890                                 mini_emit_write_barrier (cfg, addr, sp [2]);
4891                 }
4892                 return ins;
4893         }
4894 }
4895
4896 static MonoInst*
4897 emit_array_unsafe_access (MonoCompile *cfg, MonoMethodSignature *fsig, MonoInst **args, int is_set)
4898 {
4899         MonoClass *eklass;
4900         
4901         if (is_set)
4902                 eklass = mono_class_from_mono_type (fsig->params [2]);
4903         else
4904                 eklass = mono_class_from_mono_type (fsig->ret);
4905
4906         if (is_set) {
4907                 return emit_array_store (cfg, eklass, args, FALSE);
4908         } else {
4909                 MonoInst *ins, *addr = mini_emit_ldelema_1_ins (cfg, eklass, args [0], args [1], FALSE);
4910                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &eklass->byval_arg, addr->dreg, 0);
4911                 return ins;
4912         }
4913 }
4914
4915 static gboolean
4916 is_unsafe_mov_compatible (MonoCompile *cfg, MonoClass *param_klass, MonoClass *return_klass)
4917 {
4918         uint32_t align;
4919         int param_size, return_size;
4920
4921         param_klass = mono_class_from_mono_type (mini_get_underlying_type (&param_klass->byval_arg));
4922         return_klass = mono_class_from_mono_type (mini_get_underlying_type (&return_klass->byval_arg));
4923
4924         if (cfg->verbose_level > 3)
4925                 printf ("[UNSAFE-MOV-INTRISIC] %s <- %s\n", return_klass->name, param_klass->name);
4926
4927         //Don't allow mixing reference types with value types
4928         if (param_klass->valuetype != return_klass->valuetype) {
4929                 if (cfg->verbose_level > 3)
4930                         printf ("[UNSAFE-MOV-INTRISIC]\tone of the args is a valuetype and the other is not\n");
4931                 return FALSE;
4932         }
4933
4934         if (!param_klass->valuetype) {
4935                 if (cfg->verbose_level > 3)
4936                         printf ("[UNSAFE-MOV-INTRISIC]\targs are reference types\n");
4937                 return TRUE;
4938         }
4939
4940         //That are blitable
4941         if (param_klass->has_references || return_klass->has_references)
4942                 return FALSE;
4943
4944         /* Avoid mixing structs and primitive types/enums, they need to be handled differently in the JIT */
4945         if ((MONO_TYPE_ISSTRUCT (&param_klass->byval_arg) && !MONO_TYPE_ISSTRUCT (&return_klass->byval_arg)) ||
4946                 (!MONO_TYPE_ISSTRUCT (&param_klass->byval_arg) && MONO_TYPE_ISSTRUCT (&return_klass->byval_arg))) {
4947                         if (cfg->verbose_level > 3)
4948                                 printf ("[UNSAFE-MOV-INTRISIC]\tmixing structs and scalars\n");
4949                 return FALSE;
4950         }
4951
4952         if (param_klass->byval_arg.type == MONO_TYPE_R4 || param_klass->byval_arg.type == MONO_TYPE_R8 ||
4953                 return_klass->byval_arg.type == MONO_TYPE_R4 || return_klass->byval_arg.type == MONO_TYPE_R8) {
4954                 if (cfg->verbose_level > 3)
4955                         printf ("[UNSAFE-MOV-INTRISIC]\tfloat or double are not supported\n");
4956                 return FALSE;
4957         }
4958
4959         param_size = mono_class_value_size (param_klass, &align);
4960         return_size = mono_class_value_size (return_klass, &align);
4961
4962         //We can do it if sizes match
4963         if (param_size == return_size) {
4964                 if (cfg->verbose_level > 3)
4965                         printf ("[UNSAFE-MOV-INTRISIC]\tsame size\n");
4966                 return TRUE;
4967         }
4968
4969         //No simple way to handle struct if sizes don't match
4970         if (MONO_TYPE_ISSTRUCT (&param_klass->byval_arg)) {
4971                 if (cfg->verbose_level > 3)
4972                         printf ("[UNSAFE-MOV-INTRISIC]\tsize mismatch and type is a struct\n");
4973                 return FALSE;
4974         }
4975
4976         /*
4977          * Same reg size category.
4978          * A quick note on why we don't require widening here.
4979          * The intrinsic is "R Array.UnsafeMov<S,R> (S s)".
4980          *
4981          * Since the source value comes from a function argument, the JIT will already have
4982          * the value in a VREG and performed any widening needed before (say, when loading from a field).
4983          */
4984         if (param_size <= 4 && return_size <= 4) {
4985                 if (cfg->verbose_level > 3)
4986                         printf ("[UNSAFE-MOV-INTRISIC]\tsize mismatch but both are of the same reg class\n");
4987                 return TRUE;
4988         }
4989
4990         return FALSE;
4991 }
4992
4993 static MonoInst*
4994 emit_array_unsafe_mov (MonoCompile *cfg, MonoMethodSignature *fsig, MonoInst **args)
4995 {
4996         MonoClass *param_klass = mono_class_from_mono_type (fsig->params [0]);
4997         MonoClass *return_klass = mono_class_from_mono_type (fsig->ret);
4998
4999         if (mini_is_gsharedvt_variable_type (fsig->ret))
5000                 return NULL;
5001
5002         //Valuetypes that are semantically equivalent or numbers than can be widened to
5003         if (is_unsafe_mov_compatible (cfg, param_klass, return_klass))
5004                 return args [0];
5005
5006         //Arrays of valuetypes that are semantically equivalent
5007         if (param_klass->rank == 1 && return_klass->rank == 1 && is_unsafe_mov_compatible (cfg, param_klass->element_class, return_klass->element_class))
5008                 return args [0];
5009
5010         return NULL;
5011 }
5012
5013 static MonoInst*
5014 mini_emit_inst_for_ctor (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
5015 {
5016 #ifdef MONO_ARCH_SIMD_INTRINSICS
5017         MonoInst *ins = NULL;
5018
5019         if (cfg->opt & MONO_OPT_SIMD) {
5020                 ins = mono_emit_simd_intrinsics (cfg, cmethod, fsig, args);
5021                 if (ins)
5022                         return ins;
5023         }
5024 #endif
5025
5026         return mono_emit_native_types_intrinsics (cfg, cmethod, fsig, args);
5027 }
5028
5029 MonoInst*
5030 mini_emit_memory_barrier (MonoCompile *cfg, int kind)
5031 {
5032         MonoInst *ins = NULL;
5033         MONO_INST_NEW (cfg, ins, OP_MEMORY_BARRIER);
5034         MONO_ADD_INS (cfg->cbb, ins);
5035         ins->backend.memory_barrier_kind = kind;
5036
5037         return ins;
5038 }
5039
5040 static MonoInst*
5041 llvm_emit_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
5042 {
5043         MonoInst *ins = NULL;
5044         int opcode = 0;
5045
5046         /* The LLVM backend supports these intrinsics */
5047         if (cmethod->klass == mono_defaults.math_class) {
5048                 if (strcmp (cmethod->name, "Sin") == 0) {
5049                         opcode = OP_SIN;
5050                 } else if (strcmp (cmethod->name, "Cos") == 0) {
5051                         opcode = OP_COS;
5052                 } else if (strcmp (cmethod->name, "Sqrt") == 0) {
5053                         opcode = OP_SQRT;
5054                 } else if (strcmp (cmethod->name, "Abs") == 0 && fsig->params [0]->type == MONO_TYPE_R8) {
5055                         opcode = OP_ABS;
5056                 }
5057
5058                 if (opcode && fsig->param_count == 1) {
5059                         MONO_INST_NEW (cfg, ins, opcode);
5060                         ins->type = STACK_R8;
5061                         ins->dreg = mono_alloc_dreg (cfg, ins->type);
5062                         ins->sreg1 = args [0]->dreg;
5063                         MONO_ADD_INS (cfg->cbb, ins);
5064                 }
5065
5066                 opcode = 0;
5067                 if (cfg->opt & MONO_OPT_CMOV) {
5068                         if (strcmp (cmethod->name, "Min") == 0) {
5069                                 if (fsig->params [0]->type == MONO_TYPE_I4)
5070                                         opcode = OP_IMIN;
5071                                 if (fsig->params [0]->type == MONO_TYPE_U4)
5072                                         opcode = OP_IMIN_UN;
5073                                 else if (fsig->params [0]->type == MONO_TYPE_I8)
5074                                         opcode = OP_LMIN;
5075                                 else if (fsig->params [0]->type == MONO_TYPE_U8)
5076                                         opcode = OP_LMIN_UN;
5077                         } else if (strcmp (cmethod->name, "Max") == 0) {
5078                                 if (fsig->params [0]->type == MONO_TYPE_I4)
5079                                         opcode = OP_IMAX;
5080                                 if (fsig->params [0]->type == MONO_TYPE_U4)
5081                                         opcode = OP_IMAX_UN;
5082                                 else if (fsig->params [0]->type == MONO_TYPE_I8)
5083                                         opcode = OP_LMAX;
5084                                 else if (fsig->params [0]->type == MONO_TYPE_U8)
5085                                         opcode = OP_LMAX_UN;
5086                         }
5087                 }
5088
5089                 if (opcode && fsig->param_count == 2) {
5090                         MONO_INST_NEW (cfg, ins, opcode);
5091                         ins->type = fsig->params [0]->type == MONO_TYPE_I4 ? STACK_I4 : STACK_I8;
5092                         ins->dreg = mono_alloc_dreg (cfg, ins->type);
5093                         ins->sreg1 = args [0]->dreg;
5094                         ins->sreg2 = args [1]->dreg;
5095                         MONO_ADD_INS (cfg->cbb, ins);
5096                 }
5097         }
5098
5099         return ins;
5100 }
5101
5102 static MonoInst*
5103 mini_emit_inst_for_sharable_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
5104 {
5105         if (cmethod->klass == mono_defaults.array_class) {
5106                 if (strcmp (cmethod->name, "UnsafeStore") == 0)
5107                         return emit_array_unsafe_access (cfg, fsig, args, TRUE);
5108                 else if (strcmp (cmethod->name, "UnsafeLoad") == 0)
5109                         return emit_array_unsafe_access (cfg, fsig, args, FALSE);
5110                 else if (strcmp (cmethod->name, "UnsafeMov") == 0)
5111                         return emit_array_unsafe_mov (cfg, fsig, args);
5112         }
5113
5114         return NULL;
5115 }
5116
5117
5118 static gboolean
5119 mono_type_is_native_blittable (MonoType *t)
5120 {
5121         if (MONO_TYPE_IS_REFERENCE (t))
5122                 return FALSE;
5123
5124         if (MONO_TYPE_IS_PRIMITIVE_SCALAR (t))
5125                 return TRUE;
5126
5127         MonoClass *klass = mono_class_from_mono_type (t);
5128
5129         //MonoClass::blitable depends on mono_class_setup_fields being done.
5130         mono_class_setup_fields (klass);
5131         if (!klass->blittable)
5132                 return FALSE;
5133
5134         // If the native marshal size is different we can't convert PtrToStructure to a type load
5135         if (mono_class_native_size (klass, NULL) != mono_class_value_size (klass, NULL))
5136                 return FALSE;
5137
5138         return TRUE;
5139 }
5140
5141
5142 static MonoInst*
5143 mini_emit_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
5144 {
5145         MonoInst *ins = NULL;
5146         MonoClass *runtime_helpers_class = mono_class_get_runtime_helpers_class ();
5147
5148         if (cmethod->klass == mono_defaults.string_class) {
5149                 if (strcmp (cmethod->name, "get_Chars") == 0 && fsig->param_count + fsig->hasthis == 2) {
5150                         int dreg = alloc_ireg (cfg);
5151                         int index_reg = alloc_preg (cfg);
5152                         int add_reg = alloc_preg (cfg);
5153
5154 #if SIZEOF_REGISTER == 8
5155                         if (COMPILE_LLVM (cfg)) {
5156                                 MONO_EMIT_NEW_UNALU (cfg, OP_ZEXT_I4, index_reg, args [1]->dreg);
5157                         } else {
5158                                 /* The array reg is 64 bits but the index reg is only 32 */
5159                                 MONO_EMIT_NEW_UNALU (cfg, OP_SEXT_I4, index_reg, args [1]->dreg);
5160                         }
5161 #else
5162                         index_reg = args [1]->dreg;
5163 #endif  
5164                         MONO_EMIT_BOUNDS_CHECK (cfg, args [0]->dreg, MonoString, length, index_reg);
5165
5166 #if defined(TARGET_X86) || defined(TARGET_AMD64)
5167                         EMIT_NEW_X86_LEA (cfg, ins, args [0]->dreg, index_reg, 1, MONO_STRUCT_OFFSET (MonoString, chars));
5168                         add_reg = ins->dreg;
5169                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADU2_MEMBASE, dreg, 
5170                                                                    add_reg, 0);
5171 #else
5172                         int mult_reg = alloc_preg (cfg);
5173                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHL_IMM, mult_reg, index_reg, 1);
5174                         MONO_EMIT_NEW_BIALU (cfg, OP_PADD, add_reg, mult_reg, args [0]->dreg);
5175                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADU2_MEMBASE, dreg, 
5176                                                                    add_reg, MONO_STRUCT_OFFSET (MonoString, chars));
5177 #endif
5178                         type_from_op (cfg, ins, NULL, NULL);
5179                         return ins;
5180                 } else if (strcmp (cmethod->name, "get_Length") == 0 && fsig->param_count + fsig->hasthis == 1) {
5181                         int dreg = alloc_ireg (cfg);
5182                         /* Decompose later to allow more optimizations */
5183                         EMIT_NEW_UNALU (cfg, ins, OP_STRLEN, dreg, args [0]->dreg);
5184                         ins->type = STACK_I4;
5185                         ins->flags |= MONO_INST_FAULT;
5186                         cfg->cbb->has_array_access = TRUE;
5187                         cfg->flags |= MONO_CFG_HAS_ARRAY_ACCESS;
5188
5189                         return ins;
5190                 } else 
5191                         return NULL;
5192         } else if (cmethod->klass == mono_defaults.object_class) {
5193                 if (strcmp (cmethod->name, "GetType") == 0 && fsig->param_count + fsig->hasthis == 1) {
5194                         int dreg = alloc_ireg_ref (cfg);
5195                         int vt_reg = alloc_preg (cfg);
5196                         MONO_EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, vt_reg, args [0]->dreg, MONO_STRUCT_OFFSET (MonoObject, vtable));
5197                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, dreg, vt_reg, MONO_STRUCT_OFFSET (MonoVTable, type));
5198                         type_from_op (cfg, ins, NULL, NULL);
5199
5200                         return ins;
5201                 } else if (!cfg->backend->emulate_mul_div && strcmp (cmethod->name, "InternalGetHashCode") == 0 && fsig->param_count == 1 && !mono_gc_is_moving ()) {
5202                         int dreg = alloc_ireg (cfg);
5203                         int t1 = alloc_ireg (cfg);
5204         
5205                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHL_IMM, t1, args [0]->dreg, 3);
5206                         EMIT_NEW_BIALU_IMM (cfg, ins, OP_MUL_IMM, dreg, t1, 2654435761u);
5207                         ins->type = STACK_I4;
5208
5209                         return ins;
5210                 } else if (strcmp (cmethod->name, ".ctor") == 0 && fsig->param_count == 0) {
5211                         MONO_INST_NEW (cfg, ins, OP_NOP);
5212                         MONO_ADD_INS (cfg->cbb, ins);
5213                         return ins;
5214                 } else
5215                         return NULL;
5216         } else if (cmethod->klass == mono_defaults.array_class) {
5217                 if (strcmp (cmethod->name, "GetGenericValueImpl") == 0 && fsig->param_count + fsig->hasthis == 3 && !cfg->gsharedvt)
5218                         return emit_array_generic_access (cfg, fsig, args, FALSE);
5219                 else if (strcmp (cmethod->name, "SetGenericValueImpl") == 0 && fsig->param_count + fsig->hasthis == 3 && !cfg->gsharedvt)
5220                         return emit_array_generic_access (cfg, fsig, args, TRUE);
5221
5222 #ifndef MONO_BIG_ARRAYS
5223                 /*
5224                  * This is an inline version of GetLength/GetLowerBound(0) used frequently in
5225                  * Array methods.
5226                  */
5227                 else if (((strcmp (cmethod->name, "GetLength") == 0 && fsig->param_count + fsig->hasthis == 2) ||
5228                          (strcmp (cmethod->name, "GetLowerBound") == 0 && fsig->param_count + fsig->hasthis == 2)) &&
5229                          args [1]->opcode == OP_ICONST && args [1]->inst_c0 == 0) {
5230                         int dreg = alloc_ireg (cfg);
5231                         int bounds_reg = alloc_ireg_mp (cfg);
5232                         MonoBasicBlock *end_bb, *szarray_bb;
5233                         gboolean get_length = strcmp (cmethod->name, "GetLength") == 0;
5234
5235                         NEW_BBLOCK (cfg, end_bb);
5236                         NEW_BBLOCK (cfg, szarray_bb);
5237
5238                         EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, ins, OP_LOAD_MEMBASE, bounds_reg,
5239                                                                                  args [0]->dreg, MONO_STRUCT_OFFSET (MonoArray, bounds));
5240                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, bounds_reg, 0);
5241                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, szarray_bb);
5242                         /* Non-szarray case */
5243                         if (get_length)
5244                                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADI4_MEMBASE, dreg,
5245                                                                            bounds_reg, MONO_STRUCT_OFFSET (MonoArrayBounds, length));
5246                         else
5247                                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADI4_MEMBASE, dreg,
5248                                                                            bounds_reg, MONO_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
5249                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
5250                         MONO_START_BB (cfg, szarray_bb);
5251                         /* Szarray case */
5252                         if (get_length)
5253                                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADI4_MEMBASE, dreg,
5254                                                                            args [0]->dreg, MONO_STRUCT_OFFSET (MonoArray, max_length));
5255                         else
5256                                 MONO_EMIT_NEW_ICONST (cfg, dreg, 0);
5257                         MONO_START_BB (cfg, end_bb);
5258
5259                         EMIT_NEW_UNALU (cfg, ins, OP_MOVE, dreg, dreg);
5260                         ins->type = STACK_I4;
5261                         
5262                         return ins;
5263                 }
5264 #endif
5265
5266                 if (cmethod->name [0] != 'g')
5267                         return NULL;
5268
5269                 if (strcmp (cmethod->name, "get_Rank") == 0 && fsig->param_count + fsig->hasthis == 1) {
5270                         int dreg = alloc_ireg (cfg);
5271                         int vtable_reg = alloc_preg (cfg);
5272                         MONO_EMIT_NEW_LOAD_MEMBASE_OP_FAULT (cfg, OP_LOAD_MEMBASE, vtable_reg, 
5273                                                                                                  args [0]->dreg, MONO_STRUCT_OFFSET (MonoObject, vtable));
5274                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADU1_MEMBASE, dreg,
5275                                                                    vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, rank));
5276                         type_from_op (cfg, ins, NULL, NULL);
5277
5278                         return ins;
5279                 } else if (strcmp (cmethod->name, "get_Length") == 0 && fsig->param_count + fsig->hasthis == 1) {
5280                         int dreg = alloc_ireg (cfg);
5281
5282                         EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, ins, OP_LOADI4_MEMBASE, dreg, 
5283                                                                                  args [0]->dreg, MONO_STRUCT_OFFSET (MonoArray, max_length));
5284                         type_from_op (cfg, ins, NULL, NULL);
5285
5286                         return ins;
5287                 } else
5288                         return NULL;
5289         } else if (cmethod->klass == runtime_helpers_class) {
5290                 if (strcmp (cmethod->name, "get_OffsetToStringData") == 0 && fsig->param_count == 0) {
5291                         EMIT_NEW_ICONST (cfg, ins, MONO_STRUCT_OFFSET (MonoString, chars));
5292                         return ins;
5293                 } else if (strcmp (cmethod->name, "IsReferenceOrContainsReferences") == 0 && fsig->param_count == 0) {
5294                         MonoGenericContext *ctx = mono_method_get_context (cmethod);
5295                         g_assert (ctx);
5296                         g_assert (ctx->method_inst);
5297                         g_assert (ctx->method_inst->type_argc == 1);
5298                         MonoType *t = mini_get_underlying_type (ctx->method_inst->type_argv [0]);
5299                         MonoClass *klass = mono_class_from_mono_type (t);
5300
5301                         ins = NULL;
5302
5303                         mono_class_init (klass);
5304                         if (MONO_TYPE_IS_REFERENCE (t))
5305                                 EMIT_NEW_ICONST (cfg, ins, 1);
5306                         else if (MONO_TYPE_IS_PRIMITIVE (t))
5307                                 EMIT_NEW_ICONST (cfg, ins, 0);
5308                         else if (cfg->gshared && (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR) && !mini_type_var_is_vt (t))
5309                                 EMIT_NEW_ICONST (cfg, ins, 1);
5310                         else if (!cfg->gshared || !mini_class_check_context_used (cfg, klass))
5311                                 EMIT_NEW_ICONST (cfg, ins, klass->has_references ? 1 : 0);
5312                         else {
5313                                 g_assert (cfg->gshared);
5314
5315                                 int context_used = mini_class_check_context_used (cfg, klass);
5316
5317                                 /* This returns 1 or 2 */
5318                                 MonoInst *info = mini_emit_get_rgctx_klass (cfg, context_used, klass,   MONO_RGCTX_INFO_CLASS_IS_REF_OR_CONTAINS_REFS);
5319                                 int dreg = alloc_ireg (cfg);
5320                                 EMIT_NEW_BIALU_IMM (cfg, ins, OP_ISUB_IMM, dreg, info->dreg, 1);
5321                         }
5322
5323                         return ins;
5324                 } else
5325                         return NULL;
5326         } else if (cmethod->klass == mono_defaults.monitor_class) {
5327                 gboolean is_enter = FALSE;
5328                 gboolean is_v4 = FALSE;
5329
5330                 if (!strcmp (cmethod->name, "Enter") && fsig->param_count == 2 && fsig->params [1]->byref) {
5331                         is_enter = TRUE;
5332                         is_v4 = TRUE;
5333                 }
5334                 if (!strcmp (cmethod->name, "Enter") && fsig->param_count == 1)
5335                         is_enter = TRUE;
5336
5337                 if (is_enter) {
5338                         /*
5339                          * To make async stack traces work, icalls which can block should have a wrapper.
5340                          * For Monitor.Enter, emit two calls: a fastpath which doesn't have a wrapper, and a slowpath, which does.
5341                          */
5342                         MonoBasicBlock *end_bb;
5343
5344                         NEW_BBLOCK (cfg, end_bb);
5345
5346                         ins = mono_emit_jit_icall (cfg, is_v4 ? (gpointer)mono_monitor_enter_v4_fast : (gpointer)mono_monitor_enter_fast, args);
5347                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ICOMPARE_IMM, -1, ins->dreg, 0);
5348                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBNE_UN, end_bb);
5349                         ins = mono_emit_jit_icall (cfg, is_v4 ? (gpointer)mono_monitor_enter_v4_internal : (gpointer)mono_monitor_enter_internal, args);
5350                         MONO_START_BB (cfg, end_bb);
5351                         return ins;
5352                 }
5353         } else if (cmethod->klass == mono_defaults.thread_class) {
5354                 if (strcmp (cmethod->name, "SpinWait_nop") == 0 && fsig->param_count == 0) {
5355                         MONO_INST_NEW (cfg, ins, OP_RELAXED_NOP);
5356                         MONO_ADD_INS (cfg->cbb, ins);
5357                         return ins;
5358                 } else if (strcmp (cmethod->name, "MemoryBarrier") == 0 && fsig->param_count == 0) {
5359                         return mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
5360                 } else if (!strcmp (cmethod->name, "VolatileRead") && fsig->param_count == 1) {
5361                         guint32 opcode = 0;
5362                         gboolean is_ref = mini_type_is_reference (fsig->params [0]);
5363
5364                         if (fsig->params [0]->type == MONO_TYPE_I1)
5365                                 opcode = OP_LOADI1_MEMBASE;
5366                         else if (fsig->params [0]->type == MONO_TYPE_U1)
5367                                 opcode = OP_LOADU1_MEMBASE;
5368                         else if (fsig->params [0]->type == MONO_TYPE_I2)
5369                                 opcode = OP_LOADI2_MEMBASE;
5370                         else if (fsig->params [0]->type == MONO_TYPE_U2)
5371                                 opcode = OP_LOADU2_MEMBASE;
5372                         else if (fsig->params [0]->type == MONO_TYPE_I4)
5373                                 opcode = OP_LOADI4_MEMBASE;
5374                         else if (fsig->params [0]->type == MONO_TYPE_U4)
5375                                 opcode = OP_LOADU4_MEMBASE;
5376                         else if (fsig->params [0]->type == MONO_TYPE_I8 || fsig->params [0]->type == MONO_TYPE_U8)
5377                                 opcode = OP_LOADI8_MEMBASE;
5378                         else if (fsig->params [0]->type == MONO_TYPE_R4)
5379                                 opcode = OP_LOADR4_MEMBASE;
5380                         else if (fsig->params [0]->type == MONO_TYPE_R8)
5381                                 opcode = OP_LOADR8_MEMBASE;
5382                         else if (is_ref || fsig->params [0]->type == MONO_TYPE_I || fsig->params [0]->type == MONO_TYPE_U)
5383                                 opcode = OP_LOAD_MEMBASE;
5384
5385                         if (opcode) {
5386                                 MONO_INST_NEW (cfg, ins, opcode);
5387                                 ins->inst_basereg = args [0]->dreg;
5388                                 ins->inst_offset = 0;
5389                                 MONO_ADD_INS (cfg->cbb, ins);
5390
5391                                 switch (fsig->params [0]->type) {
5392                                 case MONO_TYPE_I1:
5393                                 case MONO_TYPE_U1:
5394                                 case MONO_TYPE_I2:
5395                                 case MONO_TYPE_U2:
5396                                 case MONO_TYPE_I4:
5397                                 case MONO_TYPE_U4:
5398                                         ins->dreg = mono_alloc_ireg (cfg);
5399                                         ins->type = STACK_I4;
5400                                         break;
5401                                 case MONO_TYPE_I8:
5402                                 case MONO_TYPE_U8:
5403                                         ins->dreg = mono_alloc_lreg (cfg);
5404                                         ins->type = STACK_I8;
5405                                         break;
5406                                 case MONO_TYPE_I:
5407                                 case MONO_TYPE_U:
5408                                         ins->dreg = mono_alloc_ireg (cfg);
5409 #if SIZEOF_REGISTER == 8
5410                                         ins->type = STACK_I8;
5411 #else
5412                                         ins->type = STACK_I4;
5413 #endif
5414                                         break;
5415                                 case MONO_TYPE_R4:
5416                                 case MONO_TYPE_R8:
5417                                         ins->dreg = mono_alloc_freg (cfg);
5418                                         ins->type = STACK_R8;
5419                                         break;
5420                                 default:
5421                                         g_assert (mini_type_is_reference (fsig->params [0]));
5422                                         ins->dreg = mono_alloc_ireg_ref (cfg);
5423                                         ins->type = STACK_OBJ;
5424                                         break;
5425                                 }
5426
5427                                 if (opcode == OP_LOADI8_MEMBASE)
5428                                         ins = mono_decompose_opcode (cfg, ins);
5429
5430                                 mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
5431
5432                                 return ins;
5433                         }
5434                 } else if (!strcmp (cmethod->name, "VolatileWrite") && fsig->param_count == 2) {
5435                         guint32 opcode = 0;
5436                         gboolean is_ref = mini_type_is_reference (fsig->params [0]);
5437
5438                         if (fsig->params [0]->type == MONO_TYPE_I1 || fsig->params [0]->type == MONO_TYPE_U1)
5439                                 opcode = OP_STOREI1_MEMBASE_REG;
5440                         else if (fsig->params [0]->type == MONO_TYPE_I2 || fsig->params [0]->type == MONO_TYPE_U2)
5441                                 opcode = OP_STOREI2_MEMBASE_REG;
5442                         else if (fsig->params [0]->type == MONO_TYPE_I4 || fsig->params [0]->type == MONO_TYPE_U4)
5443                                 opcode = OP_STOREI4_MEMBASE_REG;
5444                         else if (fsig->params [0]->type == MONO_TYPE_I8 || fsig->params [0]->type == MONO_TYPE_U8)
5445                                 opcode = OP_STOREI8_MEMBASE_REG;
5446                         else if (fsig->params [0]->type == MONO_TYPE_R4)
5447                                 opcode = OP_STORER4_MEMBASE_REG;
5448                         else if (fsig->params [0]->type == MONO_TYPE_R8)
5449                                 opcode = OP_STORER8_MEMBASE_REG;
5450                         else if (is_ref || fsig->params [0]->type == MONO_TYPE_I || fsig->params [0]->type == MONO_TYPE_U)
5451                                 opcode = OP_STORE_MEMBASE_REG;
5452
5453                         if (opcode) {
5454                                 mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
5455
5456                                 MONO_INST_NEW (cfg, ins, opcode);
5457                                 ins->sreg1 = args [1]->dreg;
5458                                 ins->inst_destbasereg = args [0]->dreg;
5459                                 ins->inst_offset = 0;
5460                                 MONO_ADD_INS (cfg->cbb, ins);
5461
5462                                 if (opcode == OP_STOREI8_MEMBASE_REG)
5463                                         ins = mono_decompose_opcode (cfg, ins);
5464
5465                                 return ins;
5466                         }
5467                 }
5468         } else if (cmethod->klass->image == mono_defaults.corlib &&
5469                            (strcmp (cmethod->klass->name_space, "System.Threading") == 0) &&
5470                            (strcmp (cmethod->klass->name, "Interlocked") == 0)) {
5471                 ins = NULL;
5472
5473 #if SIZEOF_REGISTER == 8
5474                 if (!cfg->llvm_only && strcmp (cmethod->name, "Read") == 0 && fsig->param_count == 1 && (fsig->params [0]->type == MONO_TYPE_I8)) {
5475                         if (!cfg->llvm_only && mono_arch_opcode_supported (OP_ATOMIC_LOAD_I8)) {
5476                                 MONO_INST_NEW (cfg, ins, OP_ATOMIC_LOAD_I8);
5477                                 ins->dreg = mono_alloc_preg (cfg);
5478                                 ins->sreg1 = args [0]->dreg;
5479                                 ins->type = STACK_I8;
5480                                 ins->backend.memory_barrier_kind = MONO_MEMORY_BARRIER_SEQ;
5481                                 MONO_ADD_INS (cfg->cbb, ins);
5482                         } else {
5483                                 MonoInst *load_ins;
5484
5485                                 mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
5486
5487                                 /* 64 bit reads are already atomic */
5488                                 MONO_INST_NEW (cfg, load_ins, OP_LOADI8_MEMBASE);
5489                                 load_ins->dreg = mono_alloc_preg (cfg);
5490                                 load_ins->inst_basereg = args [0]->dreg;
5491                                 load_ins->inst_offset = 0;
5492                                 load_ins->type = STACK_I8;
5493                                 MONO_ADD_INS (cfg->cbb, load_ins);
5494
5495                                 mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
5496
5497                                 ins = load_ins;
5498                         }
5499                 }
5500 #endif
5501
5502                 if (strcmp (cmethod->name, "Increment") == 0 && fsig->param_count == 1) {
5503                         MonoInst *ins_iconst;
5504                         guint32 opcode = 0;
5505
5506                         if (fsig->params [0]->type == MONO_TYPE_I4) {
5507                                 opcode = OP_ATOMIC_ADD_I4;
5508                                 cfg->has_atomic_add_i4 = TRUE;
5509                         }
5510 #if SIZEOF_REGISTER == 8
5511                         else if (fsig->params [0]->type == MONO_TYPE_I8)
5512                                 opcode = OP_ATOMIC_ADD_I8;
5513 #endif
5514                         if (opcode) {
5515                                 if (!mono_arch_opcode_supported (opcode))
5516                                         return NULL;
5517                                 MONO_INST_NEW (cfg, ins_iconst, OP_ICONST);
5518                                 ins_iconst->inst_c0 = 1;
5519                                 ins_iconst->dreg = mono_alloc_ireg (cfg);
5520                                 MONO_ADD_INS (cfg->cbb, ins_iconst);
5521
5522                                 MONO_INST_NEW (cfg, ins, opcode);
5523                                 ins->dreg = mono_alloc_ireg (cfg);
5524                                 ins->inst_basereg = args [0]->dreg;
5525                                 ins->inst_offset = 0;
5526                                 ins->sreg2 = ins_iconst->dreg;
5527                                 ins->type = (opcode == OP_ATOMIC_ADD_I4) ? STACK_I4 : STACK_I8;
5528                                 MONO_ADD_INS (cfg->cbb, ins);
5529                         }
5530                 } else if (strcmp (cmethod->name, "Decrement") == 0 && fsig->param_count == 1) {
5531                         MonoInst *ins_iconst;
5532                         guint32 opcode = 0;
5533
5534                         if (fsig->params [0]->type == MONO_TYPE_I4) {
5535                                 opcode = OP_ATOMIC_ADD_I4;
5536                                 cfg->has_atomic_add_i4 = TRUE;
5537                         }
5538 #if SIZEOF_REGISTER == 8
5539                         else if (fsig->params [0]->type == MONO_TYPE_I8)
5540                                 opcode = OP_ATOMIC_ADD_I8;
5541 #endif
5542                         if (opcode) {
5543                                 if (!mono_arch_opcode_supported (opcode))
5544                                         return NULL;
5545                                 MONO_INST_NEW (cfg, ins_iconst, OP_ICONST);
5546                                 ins_iconst->inst_c0 = -1;
5547                                 ins_iconst->dreg = mono_alloc_ireg (cfg);
5548                                 MONO_ADD_INS (cfg->cbb, ins_iconst);
5549
5550                                 MONO_INST_NEW (cfg, ins, opcode);
5551                                 ins->dreg = mono_alloc_ireg (cfg);
5552                                 ins->inst_basereg = args [0]->dreg;
5553                                 ins->inst_offset = 0;
5554                                 ins->sreg2 = ins_iconst->dreg;
5555                                 ins->type = (opcode == OP_ATOMIC_ADD_I4) ? STACK_I4 : STACK_I8;
5556                                 MONO_ADD_INS (cfg->cbb, ins);
5557                         }
5558                 } else if (strcmp (cmethod->name, "Add") == 0 && fsig->param_count == 2) {
5559                         guint32 opcode = 0;
5560
5561                         if (fsig->params [0]->type == MONO_TYPE_I4) {
5562                                 opcode = OP_ATOMIC_ADD_I4;
5563                                 cfg->has_atomic_add_i4 = TRUE;
5564                         }
5565 #if SIZEOF_REGISTER == 8
5566                         else if (fsig->params [0]->type == MONO_TYPE_I8)
5567                                 opcode = OP_ATOMIC_ADD_I8;
5568 #endif
5569                         if (opcode) {
5570                                 if (!mono_arch_opcode_supported (opcode))
5571                                         return NULL;
5572                                 MONO_INST_NEW (cfg, ins, opcode);
5573                                 ins->dreg = mono_alloc_ireg (cfg);
5574                                 ins->inst_basereg = args [0]->dreg;
5575                                 ins->inst_offset = 0;
5576                                 ins->sreg2 = args [1]->dreg;
5577                                 ins->type = (opcode == OP_ATOMIC_ADD_I4) ? STACK_I4 : STACK_I8;
5578                                 MONO_ADD_INS (cfg->cbb, ins);
5579                         }
5580                 }
5581                 else if (strcmp (cmethod->name, "Exchange") == 0 && fsig->param_count == 2) {
5582                         MonoInst *f2i = NULL, *i2f;
5583                         guint32 opcode, f2i_opcode, i2f_opcode;
5584                         gboolean is_ref = mini_type_is_reference (fsig->params [0]);
5585                         gboolean is_float = fsig->params [0]->type == MONO_TYPE_R4 || fsig->params [0]->type == MONO_TYPE_R8;
5586
5587                         if (fsig->params [0]->type == MONO_TYPE_I4 ||
5588                             fsig->params [0]->type == MONO_TYPE_R4) {
5589                                 opcode = OP_ATOMIC_EXCHANGE_I4;
5590                                 f2i_opcode = OP_MOVE_F_TO_I4;
5591                                 i2f_opcode = OP_MOVE_I4_TO_F;
5592                                 cfg->has_atomic_exchange_i4 = TRUE;
5593                         }
5594 #if SIZEOF_REGISTER == 8
5595                         else if (is_ref ||
5596                                  fsig->params [0]->type == MONO_TYPE_I8 ||
5597                                  fsig->params [0]->type == MONO_TYPE_R8 ||
5598                                  fsig->params [0]->type == MONO_TYPE_I) {
5599                                 opcode = OP_ATOMIC_EXCHANGE_I8;
5600                                 f2i_opcode = OP_MOVE_F_TO_I8;
5601                                 i2f_opcode = OP_MOVE_I8_TO_F;
5602                         }
5603 #else
5604                         else if (is_ref || fsig->params [0]->type == MONO_TYPE_I) {
5605                                 opcode = OP_ATOMIC_EXCHANGE_I4;
5606                                 cfg->has_atomic_exchange_i4 = TRUE;
5607                         }
5608 #endif
5609                         else
5610                                 return NULL;
5611
5612                         if (!mono_arch_opcode_supported (opcode))
5613                                 return NULL;
5614
5615                         if (is_float) {
5616                                 /* TODO: Decompose these opcodes instead of bailing here. */
5617                                 if (COMPILE_SOFT_FLOAT (cfg))
5618                                         return NULL;
5619
5620                                 MONO_INST_NEW (cfg, f2i, f2i_opcode);
5621                                 f2i->dreg = mono_alloc_ireg (cfg);
5622                                 f2i->sreg1 = args [1]->dreg;
5623                                 if (f2i_opcode == OP_MOVE_F_TO_I4)
5624                                         f2i->backend.spill_var = mini_get_int_to_float_spill_area (cfg);
5625                                 MONO_ADD_INS (cfg->cbb, f2i);
5626                         }
5627
5628                         MONO_INST_NEW (cfg, ins, opcode);
5629                         ins->dreg = is_ref ? mono_alloc_ireg_ref (cfg) : mono_alloc_ireg (cfg);
5630                         ins->inst_basereg = args [0]->dreg;
5631                         ins->inst_offset = 0;
5632                         ins->sreg2 = is_float ? f2i->dreg : args [1]->dreg;
5633                         MONO_ADD_INS (cfg->cbb, ins);
5634
5635                         switch (fsig->params [0]->type) {
5636                         case MONO_TYPE_I4:
5637                                 ins->type = STACK_I4;
5638                                 break;
5639                         case MONO_TYPE_I8:
5640                                 ins->type = STACK_I8;
5641                                 break;
5642                         case MONO_TYPE_I:
5643 #if SIZEOF_REGISTER == 8
5644                                 ins->type = STACK_I8;
5645 #else
5646                                 ins->type = STACK_I4;
5647 #endif
5648                                 break;
5649                         case MONO_TYPE_R4:
5650                         case MONO_TYPE_R8:
5651                                 ins->type = STACK_R8;
5652                                 break;
5653                         default:
5654                                 g_assert (mini_type_is_reference (fsig->params [0]));
5655                                 ins->type = STACK_OBJ;
5656                                 break;
5657                         }
5658
5659                         if (is_float) {
5660                                 MONO_INST_NEW (cfg, i2f, i2f_opcode);
5661                                 i2f->dreg = mono_alloc_freg (cfg);
5662                                 i2f->sreg1 = ins->dreg;
5663                                 i2f->type = STACK_R8;
5664                                 if (i2f_opcode == OP_MOVE_I4_TO_F)
5665                                         i2f->backend.spill_var = mini_get_int_to_float_spill_area (cfg);
5666                                 MONO_ADD_INS (cfg->cbb, i2f);
5667
5668                                 ins = i2f;
5669                         }
5670
5671                         if (cfg->gen_write_barriers && is_ref)
5672                                 mini_emit_write_barrier (cfg, args [0], args [1]);
5673                 }
5674                 else if ((strcmp (cmethod->name, "CompareExchange") == 0) && fsig->param_count == 3) {
5675                         MonoInst *f2i_new = NULL, *f2i_cmp = NULL, *i2f;
5676                         guint32 opcode, f2i_opcode, i2f_opcode;
5677                         gboolean is_ref = mini_type_is_reference (fsig->params [1]);
5678                         gboolean is_float = fsig->params [1]->type == MONO_TYPE_R4 || fsig->params [1]->type == MONO_TYPE_R8;
5679
5680                         if (fsig->params [1]->type == MONO_TYPE_I4 ||
5681                             fsig->params [1]->type == MONO_TYPE_R4) {
5682                                 opcode = OP_ATOMIC_CAS_I4;
5683                                 f2i_opcode = OP_MOVE_F_TO_I4;
5684                                 i2f_opcode = OP_MOVE_I4_TO_F;
5685                                 cfg->has_atomic_cas_i4 = TRUE;
5686                         }
5687 #if SIZEOF_REGISTER == 8
5688                         else if (is_ref ||
5689                                  fsig->params [1]->type == MONO_TYPE_I8 ||
5690                                  fsig->params [1]->type == MONO_TYPE_R8 ||
5691                                  fsig->params [1]->type == MONO_TYPE_I) {
5692                                 opcode = OP_ATOMIC_CAS_I8;
5693                                 f2i_opcode = OP_MOVE_F_TO_I8;
5694                                 i2f_opcode = OP_MOVE_I8_TO_F;
5695                         }
5696 #else
5697                         else if (is_ref || fsig->params [1]->type == MONO_TYPE_I) {
5698                                 opcode = OP_ATOMIC_CAS_I4;
5699                                 cfg->has_atomic_cas_i4 = TRUE;
5700                         }
5701 #endif
5702                         else
5703                                 return NULL;
5704
5705                         if (!mono_arch_opcode_supported (opcode))
5706                                 return NULL;
5707
5708                         if (is_float) {
5709                                 /* TODO: Decompose these opcodes instead of bailing here. */
5710                                 if (COMPILE_SOFT_FLOAT (cfg))
5711                                         return NULL;
5712
5713                                 MONO_INST_NEW (cfg, f2i_new, f2i_opcode);
5714                                 f2i_new->dreg = mono_alloc_ireg (cfg);
5715                                 f2i_new->sreg1 = args [1]->dreg;
5716                                 if (f2i_opcode == OP_MOVE_F_TO_I4)
5717                                         f2i_new->backend.spill_var = mini_get_int_to_float_spill_area (cfg);
5718                                 MONO_ADD_INS (cfg->cbb, f2i_new);
5719
5720                                 MONO_INST_NEW (cfg, f2i_cmp, f2i_opcode);
5721                                 f2i_cmp->dreg = mono_alloc_ireg (cfg);
5722                                 f2i_cmp->sreg1 = args [2]->dreg;
5723                                 if (f2i_opcode == OP_MOVE_F_TO_I4)
5724                                         f2i_cmp->backend.spill_var = mini_get_int_to_float_spill_area (cfg);
5725                                 MONO_ADD_INS (cfg->cbb, f2i_cmp);
5726                         }
5727
5728                         MONO_INST_NEW (cfg, ins, opcode);
5729                         ins->dreg = is_ref ? alloc_ireg_ref (cfg) : alloc_ireg (cfg);
5730                         ins->sreg1 = args [0]->dreg;
5731                         ins->sreg2 = is_float ? f2i_new->dreg : args [1]->dreg;
5732                         ins->sreg3 = is_float ? f2i_cmp->dreg : args [2]->dreg;
5733                         MONO_ADD_INS (cfg->cbb, ins);
5734
5735                         switch (fsig->params [1]->type) {
5736                         case MONO_TYPE_I4:
5737                                 ins->type = STACK_I4;
5738                                 break;
5739                         case MONO_TYPE_I8:
5740                                 ins->type = STACK_I8;
5741                                 break;
5742                         case MONO_TYPE_I:
5743 #if SIZEOF_REGISTER == 8
5744                                 ins->type = STACK_I8;
5745 #else
5746                                 ins->type = STACK_I4;
5747 #endif
5748                                 break;
5749                         case MONO_TYPE_R4:
5750                                 ins->type = cfg->r4_stack_type;
5751                                 break;
5752                         case MONO_TYPE_R8:
5753                                 ins->type = STACK_R8;
5754                                 break;
5755                         default:
5756                                 g_assert (mini_type_is_reference (fsig->params [1]));
5757                                 ins->type = STACK_OBJ;
5758                                 break;
5759                         }
5760
5761                         if (is_float) {
5762                                 MONO_INST_NEW (cfg, i2f, i2f_opcode);
5763                                 i2f->dreg = mono_alloc_freg (cfg);
5764                                 i2f->sreg1 = ins->dreg;
5765                                 i2f->type = STACK_R8;
5766                                 if (i2f_opcode == OP_MOVE_I4_TO_F)
5767                                         i2f->backend.spill_var = mini_get_int_to_float_spill_area (cfg);
5768                                 MONO_ADD_INS (cfg->cbb, i2f);
5769
5770                                 ins = i2f;
5771                         }
5772
5773                         if (cfg->gen_write_barriers && is_ref)
5774                                 mini_emit_write_barrier (cfg, args [0], args [1]);
5775                 }
5776                 else if ((strcmp (cmethod->name, "CompareExchange") == 0) && fsig->param_count == 4 &&
5777                          fsig->params [1]->type == MONO_TYPE_I4) {
5778                         MonoInst *cmp, *ceq;
5779
5780                         if (!mono_arch_opcode_supported (OP_ATOMIC_CAS_I4))
5781                                 return NULL;
5782
5783                         /* int32 r = CAS (location, value, comparand); */
5784                         MONO_INST_NEW (cfg, ins, OP_ATOMIC_CAS_I4);
5785                         ins->dreg = alloc_ireg (cfg);
5786                         ins->sreg1 = args [0]->dreg;
5787                         ins->sreg2 = args [1]->dreg;
5788                         ins->sreg3 = args [2]->dreg;
5789                         ins->type = STACK_I4;
5790                         MONO_ADD_INS (cfg->cbb, ins);
5791
5792                         /* bool result = r == comparand; */
5793                         MONO_INST_NEW (cfg, cmp, OP_ICOMPARE);
5794                         cmp->sreg1 = ins->dreg;
5795                         cmp->sreg2 = args [2]->dreg;
5796                         cmp->type = STACK_I4;
5797                         MONO_ADD_INS (cfg->cbb, cmp);
5798
5799                         MONO_INST_NEW (cfg, ceq, OP_ICEQ);
5800                         ceq->dreg = alloc_ireg (cfg);
5801                         ceq->type = STACK_I4;
5802                         MONO_ADD_INS (cfg->cbb, ceq);
5803
5804                         /* *success = result; */
5805                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI1_MEMBASE_REG, args [3]->dreg, 0, ceq->dreg);
5806
5807                         cfg->has_atomic_cas_i4 = TRUE;
5808                 }
5809                 else if (strcmp (cmethod->name, "MemoryBarrier") == 0 && fsig->param_count == 0)
5810                         ins = mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
5811
5812                 if (ins)
5813                         return ins;
5814         } else if (cmethod->klass->image == mono_defaults.corlib &&
5815                            (strcmp (cmethod->klass->name_space, "System.Threading") == 0) &&
5816                            (strcmp (cmethod->klass->name, "Volatile") == 0)) {
5817                 ins = NULL;
5818
5819                 if (!cfg->llvm_only && !strcmp (cmethod->name, "Read") && fsig->param_count == 1) {
5820                         guint32 opcode = 0;
5821                         MonoType *t = fsig->params [0];
5822                         gboolean is_ref;
5823                         gboolean is_float = t->type == MONO_TYPE_R4 || t->type == MONO_TYPE_R8;
5824
5825                         g_assert (t->byref);
5826                         /* t is a byref type, so the reference check is more complicated */
5827                         is_ref = mini_type_is_reference (&mono_class_from_mono_type (t)->byval_arg);
5828                         if (t->type == MONO_TYPE_I1)
5829                                 opcode = OP_ATOMIC_LOAD_I1;
5830                         else if (t->type == MONO_TYPE_U1 || t->type == MONO_TYPE_BOOLEAN)
5831                                 opcode = OP_ATOMIC_LOAD_U1;
5832                         else if (t->type == MONO_TYPE_I2)
5833                                 opcode = OP_ATOMIC_LOAD_I2;
5834                         else if (t->type == MONO_TYPE_U2)
5835                                 opcode = OP_ATOMIC_LOAD_U2;
5836                         else if (t->type == MONO_TYPE_I4)
5837                                 opcode = OP_ATOMIC_LOAD_I4;
5838                         else if (t->type == MONO_TYPE_U4)
5839                                 opcode = OP_ATOMIC_LOAD_U4;
5840                         else if (t->type == MONO_TYPE_R4)
5841                                 opcode = OP_ATOMIC_LOAD_R4;
5842                         else if (t->type == MONO_TYPE_R8)
5843                                 opcode = OP_ATOMIC_LOAD_R8;
5844 #if SIZEOF_REGISTER == 8
5845                         else if (t->type == MONO_TYPE_I8 || t->type == MONO_TYPE_I)
5846                                 opcode = OP_ATOMIC_LOAD_I8;
5847                         else if (is_ref || t->type == MONO_TYPE_U8 || t->type == MONO_TYPE_U)
5848                                 opcode = OP_ATOMIC_LOAD_U8;
5849 #else
5850                         else if (t->type == MONO_TYPE_I)
5851                                 opcode = OP_ATOMIC_LOAD_I4;
5852                         else if (is_ref || t->type == MONO_TYPE_U)
5853                                 opcode = OP_ATOMIC_LOAD_U4;
5854 #endif
5855
5856                         if (opcode) {
5857                                 if (!mono_arch_opcode_supported (opcode))
5858                                         return NULL;
5859
5860                                 MONO_INST_NEW (cfg, ins, opcode);
5861                                 ins->dreg = is_ref ? mono_alloc_ireg_ref (cfg) : (is_float ? mono_alloc_freg (cfg) : mono_alloc_ireg (cfg));
5862                                 ins->sreg1 = args [0]->dreg;
5863                                 ins->backend.memory_barrier_kind = MONO_MEMORY_BARRIER_ACQ;
5864                                 MONO_ADD_INS (cfg->cbb, ins);
5865
5866                                 switch (t->type) {
5867                                 case MONO_TYPE_BOOLEAN:
5868                                 case MONO_TYPE_I1:
5869                                 case MONO_TYPE_U1:
5870                                 case MONO_TYPE_I2:
5871                                 case MONO_TYPE_U2:
5872                                 case MONO_TYPE_I4:
5873                                 case MONO_TYPE_U4:
5874                                         ins->type = STACK_I4;
5875                                         break;
5876                                 case MONO_TYPE_I8:
5877                                 case MONO_TYPE_U8:
5878                                         ins->type = STACK_I8;
5879                                         break;
5880                                 case MONO_TYPE_I:
5881                                 case MONO_TYPE_U:
5882 #if SIZEOF_REGISTER == 8
5883                                         ins->type = STACK_I8;
5884 #else
5885                                         ins->type = STACK_I4;
5886 #endif
5887                                         break;
5888                                 case MONO_TYPE_R4:
5889                                         ins->type = cfg->r4_stack_type;
5890                                         break;
5891                                 case MONO_TYPE_R8:
5892                                         ins->type = STACK_R8;
5893                                         break;
5894                                 default:
5895                                         g_assert (is_ref);
5896                                         ins->type = STACK_OBJ;
5897                                         break;
5898                                 }
5899                         }
5900                 }
5901
5902                 if (!cfg->llvm_only && !strcmp (cmethod->name, "Write") && fsig->param_count == 2) {
5903                         guint32 opcode = 0;
5904                         MonoType *t = fsig->params [0];
5905                         gboolean is_ref;
5906
5907                         g_assert (t->byref);
5908                         is_ref = mini_type_is_reference (&mono_class_from_mono_type (t)->byval_arg);
5909                         if (t->type == MONO_TYPE_I1)
5910                                 opcode = OP_ATOMIC_STORE_I1;
5911                         else if (t->type == MONO_TYPE_U1 || t->type == MONO_TYPE_BOOLEAN)
5912                                 opcode = OP_ATOMIC_STORE_U1;
5913                         else if (t->type == MONO_TYPE_I2)
5914                                 opcode = OP_ATOMIC_STORE_I2;
5915                         else if (t->type == MONO_TYPE_U2)
5916                                 opcode = OP_ATOMIC_STORE_U2;
5917                         else if (t->type == MONO_TYPE_I4)
5918                                 opcode = OP_ATOMIC_STORE_I4;
5919                         else if (t->type == MONO_TYPE_U4)
5920                                 opcode = OP_ATOMIC_STORE_U4;
5921                         else if (t->type == MONO_TYPE_R4)
5922                                 opcode = OP_ATOMIC_STORE_R4;
5923                         else if (t->type == MONO_TYPE_R8)
5924                                 opcode = OP_ATOMIC_STORE_R8;
5925 #if SIZEOF_REGISTER == 8
5926                         else if (t->type == MONO_TYPE_I8 || t->type == MONO_TYPE_I)
5927                                 opcode = OP_ATOMIC_STORE_I8;
5928                         else if (is_ref || t->type == MONO_TYPE_U8 || t->type == MONO_TYPE_U)
5929                                 opcode = OP_ATOMIC_STORE_U8;
5930 #else
5931                         else if (t->type == MONO_TYPE_I)
5932                                 opcode = OP_ATOMIC_STORE_I4;
5933                         else if (is_ref || t->type == MONO_TYPE_U)
5934                                 opcode = OP_ATOMIC_STORE_U4;
5935 #endif
5936
5937                         if (opcode) {
5938                                 if (!mono_arch_opcode_supported (opcode))
5939                                         return NULL;
5940
5941                                 MONO_INST_NEW (cfg, ins, opcode);
5942                                 ins->dreg = args [0]->dreg;
5943                                 ins->sreg1 = args [1]->dreg;
5944                                 ins->backend.memory_barrier_kind = MONO_MEMORY_BARRIER_REL;
5945                                 MONO_ADD_INS (cfg->cbb, ins);
5946
5947                                 if (cfg->gen_write_barriers && is_ref)
5948                                         mini_emit_write_barrier (cfg, args [0], args [1]);
5949                         }
5950                 }
5951
5952                 if (ins)
5953                         return ins;
5954         } else if (cmethod->klass->image == mono_defaults.corlib &&
5955                            (strcmp (cmethod->klass->name_space, "System.Diagnostics") == 0) &&
5956                            (strcmp (cmethod->klass->name, "Debugger") == 0)) {
5957                 if (!strcmp (cmethod->name, "Break") && fsig->param_count == 0) {
5958                         if (should_insert_brekpoint (cfg->method)) {
5959                                 ins = mono_emit_jit_icall (cfg, mono_debugger_agent_user_break, NULL);
5960                         } else {
5961                                 MONO_INST_NEW (cfg, ins, OP_NOP);
5962                                 MONO_ADD_INS (cfg->cbb, ins);
5963                         }
5964                         return ins;
5965                 }
5966         } else if (cmethod->klass->image == mono_defaults.corlib &&
5967                    (strcmp (cmethod->klass->name_space, "System") == 0) &&
5968                    (strcmp (cmethod->klass->name, "Environment") == 0)) {
5969                 if (!strcmp (cmethod->name, "get_IsRunningOnWindows") && fsig->param_count == 0) {
5970 #ifdef TARGET_WIN32
5971                         EMIT_NEW_ICONST (cfg, ins, 1);
5972 #else
5973                         EMIT_NEW_ICONST (cfg, ins, 0);
5974 #endif
5975                 }
5976         } else if (cmethod->klass->image == mono_defaults.corlib &&
5977                            (strcmp (cmethod->klass->name_space, "System.Reflection") == 0) &&
5978                            (strcmp (cmethod->klass->name, "Assembly") == 0)) {
5979                 if (cfg->llvm_only && !strcmp (cmethod->name, "GetExecutingAssembly")) {
5980                         /* No stack walks are currently available, so implement this as an intrinsic */
5981                         MonoInst *assembly_ins;
5982
5983                         EMIT_NEW_AOTCONST (cfg, assembly_ins, MONO_PATCH_INFO_IMAGE, cfg->method->klass->image);
5984                         ins = mono_emit_jit_icall (cfg, mono_get_assembly_object, &assembly_ins);
5985                         return ins;
5986                 }
5987         } else if (cmethod->klass->image == mono_defaults.corlib &&
5988                            (strcmp (cmethod->klass->name_space, "System.Reflection") == 0) &&
5989                            (strcmp (cmethod->klass->name, "MethodBase") == 0)) {
5990                 if (cfg->llvm_only && !strcmp (cmethod->name, "GetCurrentMethod")) {
5991                         /* No stack walks are currently available, so implement this as an intrinsic */
5992                         MonoInst *method_ins;
5993                         MonoMethod *declaring = cfg->method;
5994
5995                         /* This returns the declaring generic method */
5996                         if (declaring->is_inflated)
5997                                 declaring = ((MonoMethodInflated*)cfg->method)->declaring;
5998                         EMIT_NEW_AOTCONST (cfg, method_ins, MONO_PATCH_INFO_METHODCONST, declaring);
5999                         ins = mono_emit_jit_icall (cfg, mono_get_method_object, &method_ins);
6000                         cfg->no_inline = TRUE;
6001                         if (cfg->method != cfg->current_method)
6002                                 inline_failure (cfg, "MethodBase:GetCurrentMethod ()");
6003                         return ins;
6004                 }
6005         } else if (cmethod->klass == mono_defaults.math_class) {
6006                 /* 
6007                  * There is general branchless code for Min/Max, but it does not work for 
6008                  * all inputs:
6009                  * http://everything2.com/?node_id=1051618
6010                  */
6011         } else if (cmethod->klass == mono_defaults.systemtype_class && !strcmp (cmethod->name, "op_Equality")) {
6012                 EMIT_NEW_BIALU (cfg, ins, OP_COMPARE, -1, args [0]->dreg, args [1]->dreg);
6013                 MONO_INST_NEW (cfg, ins, OP_PCEQ);
6014                 ins->dreg = alloc_preg (cfg);
6015                 ins->type = STACK_I4;
6016                 MONO_ADD_INS (cfg->cbb, ins);
6017                 return ins;
6018         } else if (((!strcmp (cmethod->klass->image->assembly->aname.name, "MonoMac") ||
6019                     !strcmp (cmethod->klass->image->assembly->aname.name, "monotouch")) &&
6020                                 !strcmp (cmethod->klass->name_space, "XamCore.ObjCRuntime") &&
6021                                 !strcmp (cmethod->klass->name, "Selector")) ||
6022                            ((!strcmp (cmethod->klass->image->assembly->aname.name, "Xamarin.iOS") ||
6023                                  !strcmp (cmethod->klass->image->assembly->aname.name, "Xamarin.Mac")) &&
6024                                 !strcmp (cmethod->klass->name_space, "ObjCRuntime") &&
6025                                 !strcmp (cmethod->klass->name, "Selector"))
6026                            ) {
6027                 if ((cfg->backend->have_objc_get_selector || cfg->compile_llvm) &&
6028                         !strcmp (cmethod->name, "GetHandle") && fsig->param_count == 1 &&
6029                     (args [0]->opcode == OP_GOT_ENTRY || args [0]->opcode == OP_AOTCONST) &&
6030                     cfg->compile_aot) {
6031                         MonoInst *pi;
6032                         MonoJumpInfoToken *ji;
6033                         char *s;
6034
6035                         if (args [0]->opcode == OP_GOT_ENTRY) {
6036                                 pi = (MonoInst *)args [0]->inst_p1;
6037                                 g_assert (pi->opcode == OP_PATCH_INFO);
6038                                 g_assert (GPOINTER_TO_INT (pi->inst_p1) == MONO_PATCH_INFO_LDSTR);
6039                                 ji = (MonoJumpInfoToken *)pi->inst_p0;
6040                         } else {
6041                                 g_assert (GPOINTER_TO_INT (args [0]->inst_p1) == MONO_PATCH_INFO_LDSTR);
6042                                 ji = (MonoJumpInfoToken *)args [0]->inst_p0;
6043                         }
6044
6045                         NULLIFY_INS (args [0]);
6046
6047                         s = mono_ldstr_utf8 (ji->image, mono_metadata_token_index (ji->token), &cfg->error);
6048                         return_val_if_nok (&cfg->error, NULL);
6049
6050                         MONO_INST_NEW (cfg, ins, OP_OBJC_GET_SELECTOR);
6051                         ins->dreg = mono_alloc_ireg (cfg);
6052                         // FIXME: Leaks
6053                         ins->inst_p0 = s;
6054                         MONO_ADD_INS (cfg->cbb, ins);
6055                         return ins;
6056                 }
6057         } else if (cmethod->klass->image == mono_defaults.corlib &&
6058                         (strcmp (cmethod->klass->name_space, "System.Runtime.InteropServices") == 0) &&
6059                         (strcmp (cmethod->klass->name, "Marshal") == 0)) {
6060                 //Convert Marshal.PtrToStructure<T> of blittable T to direct loads
6061                 if (strcmp (cmethod->name, "PtrToStructure") == 0 &&
6062                                 cmethod->is_inflated &&
6063                                 fsig->param_count == 1 &&
6064                                 !mini_method_check_context_used (cfg, cmethod)) {
6065
6066                         MonoGenericContext *method_context = mono_method_get_context (cmethod);
6067                         MonoType *arg0 = method_context->method_inst->type_argv [0];
6068                         if (mono_type_is_native_blittable (arg0))
6069                                 return mini_emit_memory_load (cfg, arg0, args [0], 0, 0);
6070                 }
6071         }
6072
6073 #ifdef MONO_ARCH_SIMD_INTRINSICS
6074         if (cfg->opt & MONO_OPT_SIMD) {
6075                 ins = mono_emit_simd_intrinsics (cfg, cmethod, fsig, args);
6076                 if (ins)
6077                         return ins;
6078         }
6079 #endif
6080
6081         ins = mono_emit_native_types_intrinsics (cfg, cmethod, fsig, args);
6082         if (ins)
6083                 return ins;
6084
6085         if (COMPILE_LLVM (cfg)) {
6086                 ins = llvm_emit_inst_for_method (cfg, cmethod, fsig, args);
6087                 if (ins)
6088                         return ins;
6089         }
6090
6091         return mono_arch_emit_inst_for_method (cfg, cmethod, fsig, args);
6092 }
6093
6094 /*
6095  * This entry point could be used later for arbitrary method
6096  * redirection.
6097  */
6098 inline static MonoInst*
6099 mini_redirect_call (MonoCompile *cfg, MonoMethod *method,  
6100                                         MonoMethodSignature *signature, MonoInst **args, MonoInst *this_ins)
6101 {
6102         if (method->klass == mono_defaults.string_class) {
6103                 /* managed string allocation support */
6104                 if (strcmp (method->name, "InternalAllocateStr") == 0 && !(mono_profiler_events & MONO_PROFILE_ALLOCATIONS) && !(cfg->opt & MONO_OPT_SHARED)) {
6105                         MonoInst *iargs [2];
6106                         MonoVTable *vtable = mono_class_vtable (cfg->domain, method->klass);
6107                         MonoMethod *managed_alloc = NULL;
6108
6109                         g_assert (vtable); /*Should not fail since it System.String*/
6110 #ifndef MONO_CROSS_COMPILE
6111                         managed_alloc = mono_gc_get_managed_allocator (method->klass, FALSE, FALSE);
6112 #endif
6113                         if (!managed_alloc)
6114                                 return NULL;
6115                         EMIT_NEW_VTABLECONST (cfg, iargs [0], vtable);
6116                         iargs [1] = args [0];
6117                         return mono_emit_method_call (cfg, managed_alloc, iargs, this_ins);
6118                 }
6119         }
6120         return NULL;
6121 }
6122
6123 static void
6124 mono_save_args (MonoCompile *cfg, MonoMethodSignature *sig, MonoInst **sp)
6125 {
6126         MonoInst *store, *temp;
6127         int i;
6128
6129         for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
6130                 MonoType *argtype = (sig->hasthis && (i == 0)) ? type_from_stack_type (*sp) : sig->params [i - sig->hasthis];
6131
6132                 /*
6133                  * FIXME: We should use *args++ = sp [0], but that would mean the arg
6134                  * would be different than the MonoInst's used to represent arguments, and
6135                  * the ldelema implementation can't deal with that.
6136                  * Solution: When ldelema is used on an inline argument, create a var for 
6137                  * it, emit ldelema on that var, and emit the saving code below in
6138                  * inline_method () if needed.
6139                  */
6140                 temp = mono_compile_create_var (cfg, argtype, OP_LOCAL);
6141                 cfg->args [i] = temp;
6142                 /* This uses cfg->args [i] which is set by the preceeding line */
6143                 EMIT_NEW_ARGSTORE (cfg, store, i, *sp);
6144                 store->cil_code = sp [0]->cil_code;
6145                 sp++;
6146         }
6147 }
6148
6149 #define MONO_INLINE_CALLED_LIMITED_METHODS 1
6150 #define MONO_INLINE_CALLER_LIMITED_METHODS 1
6151
6152 #if (MONO_INLINE_CALLED_LIMITED_METHODS)
6153 static gboolean
6154 check_inline_called_method_name_limit (MonoMethod *called_method)
6155 {
6156         int strncmp_result;
6157         static const char *limit = NULL;
6158         
6159         if (limit == NULL) {
6160                 const char *limit_string = g_getenv ("MONO_INLINE_CALLED_METHOD_NAME_LIMIT");
6161
6162                 if (limit_string != NULL)
6163                         limit = limit_string;
6164                 else
6165                         limit = "";
6166         }
6167
6168         if (limit [0] != '\0') {
6169                 char *called_method_name = mono_method_full_name (called_method, TRUE);
6170
6171                 strncmp_result = strncmp (called_method_name, limit, strlen (limit));
6172                 g_free (called_method_name);
6173         
6174                 //return (strncmp_result <= 0);
6175                 return (strncmp_result == 0);
6176         } else {
6177                 return TRUE;
6178         }
6179 }
6180 #endif
6181
6182 #if (MONO_INLINE_CALLER_LIMITED_METHODS)
6183 static gboolean
6184 check_inline_caller_method_name_limit (MonoMethod *caller_method)
6185 {
6186         int strncmp_result;
6187         static const char *limit = NULL;
6188         
6189         if (limit == NULL) {
6190                 const char *limit_string = g_getenv ("MONO_INLINE_CALLER_METHOD_NAME_LIMIT");
6191                 if (limit_string != NULL) {
6192                         limit = limit_string;
6193                 } else {
6194                         limit = "";
6195                 }
6196         }
6197
6198         if (limit [0] != '\0') {
6199                 char *caller_method_name = mono_method_full_name (caller_method, TRUE);
6200
6201                 strncmp_result = strncmp (caller_method_name, limit, strlen (limit));
6202                 g_free (caller_method_name);
6203         
6204                 //return (strncmp_result <= 0);
6205                 return (strncmp_result == 0);
6206         } else {
6207                 return TRUE;
6208         }
6209 }
6210 #endif
6211
6212 static void
6213 emit_init_rvar (MonoCompile *cfg, int dreg, MonoType *rtype)
6214 {
6215         static double r8_0 = 0.0;
6216         static float r4_0 = 0.0;
6217         MonoInst *ins;
6218         int t;
6219
6220         rtype = mini_get_underlying_type (rtype);
6221         t = rtype->type;
6222
6223         if (rtype->byref) {
6224                 MONO_EMIT_NEW_PCONST (cfg, dreg, NULL);
6225         } else if (t >= MONO_TYPE_BOOLEAN && t <= MONO_TYPE_U4) {
6226                 MONO_EMIT_NEW_ICONST (cfg, dreg, 0);
6227         } else if (t == MONO_TYPE_I8 || t == MONO_TYPE_U8) {
6228                 MONO_EMIT_NEW_I8CONST (cfg, dreg, 0);
6229         } else if (cfg->r4fp && t == MONO_TYPE_R4) {
6230                 MONO_INST_NEW (cfg, ins, OP_R4CONST);
6231                 ins->type = STACK_R4;
6232                 ins->inst_p0 = (void*)&r4_0;
6233                 ins->dreg = dreg;
6234                 MONO_ADD_INS (cfg->cbb, ins);
6235         } else if (t == MONO_TYPE_R4 || t == MONO_TYPE_R8) {
6236                 MONO_INST_NEW (cfg, ins, OP_R8CONST);
6237                 ins->type = STACK_R8;
6238                 ins->inst_p0 = (void*)&r8_0;
6239                 ins->dreg = dreg;
6240                 MONO_ADD_INS (cfg->cbb, ins);
6241         } else if ((t == MONO_TYPE_VALUETYPE) || (t == MONO_TYPE_TYPEDBYREF) ||
6242                    ((t == MONO_TYPE_GENERICINST) && mono_type_generic_inst_is_valuetype (rtype))) {
6243                 MONO_EMIT_NEW_VZERO (cfg, dreg, mono_class_from_mono_type (rtype));
6244         } else if (((t == MONO_TYPE_VAR) || (t == MONO_TYPE_MVAR)) && mini_type_var_is_vt (rtype)) {
6245                 MONO_EMIT_NEW_VZERO (cfg, dreg, mono_class_from_mono_type (rtype));
6246         } else {
6247                 MONO_EMIT_NEW_PCONST (cfg, dreg, NULL);
6248         }
6249 }
6250
6251 static void
6252 emit_dummy_init_rvar (MonoCompile *cfg, int dreg, MonoType *rtype)
6253 {
6254         int t;
6255
6256         rtype = mini_get_underlying_type (rtype);
6257         t = rtype->type;
6258
6259         if (rtype->byref) {
6260                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_PCONST);
6261         } else if (t >= MONO_TYPE_BOOLEAN && t <= MONO_TYPE_U4) {
6262                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_ICONST);
6263         } else if (t == MONO_TYPE_I8 || t == MONO_TYPE_U8) {
6264                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_I8CONST);
6265         } else if (cfg->r4fp && t == MONO_TYPE_R4) {
6266                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_R4CONST);
6267         } else if (t == MONO_TYPE_R4 || t == MONO_TYPE_R8) {
6268                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_R8CONST);
6269         } else if ((t == MONO_TYPE_VALUETYPE) || (t == MONO_TYPE_TYPEDBYREF) ||
6270                    ((t == MONO_TYPE_GENERICINST) && mono_type_generic_inst_is_valuetype (rtype))) {
6271                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_VZERO);
6272         } else if (((t == MONO_TYPE_VAR) || (t == MONO_TYPE_MVAR)) && mini_type_var_is_vt (rtype)) {
6273                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_VZERO);
6274         } else {
6275                 emit_init_rvar (cfg, dreg, rtype);
6276         }
6277 }
6278
6279 /* If INIT is FALSE, emit dummy initialization statements to keep the IR valid */
6280 static void
6281 emit_init_local (MonoCompile *cfg, int local, MonoType *type, gboolean init)
6282 {
6283         MonoInst *var = cfg->locals [local];
6284         if (COMPILE_SOFT_FLOAT (cfg)) {
6285                 MonoInst *store;
6286                 int reg = alloc_dreg (cfg, (MonoStackType)var->type);
6287                 emit_init_rvar (cfg, reg, type);
6288                 EMIT_NEW_LOCSTORE (cfg, store, local, cfg->cbb->last_ins);
6289         } else {
6290                 if (init)
6291                         emit_init_rvar (cfg, var->dreg, type);
6292                 else
6293                         emit_dummy_init_rvar (cfg, var->dreg, type);
6294         }
6295 }
6296
6297 int
6298 mini_inline_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **sp, guchar *ip, guint real_offset, gboolean inline_always)
6299 {
6300         return inline_method (cfg, cmethod, fsig, sp, ip, real_offset, inline_always);
6301 }
6302
6303 /*
6304  * inline_method:
6305  *
6306  * Return the cost of inlining CMETHOD, or zero if it should not be inlined.
6307  */
6308 static int
6309 inline_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **sp,
6310                guchar *ip, guint real_offset, gboolean inline_always)
6311 {
6312         MonoError error;
6313         MonoInst *ins, *rvar = NULL;
6314         MonoMethodHeader *cheader;
6315         MonoBasicBlock *ebblock, *sbblock;
6316         int i, costs;
6317         MonoMethod *prev_inlined_method;
6318         MonoInst **prev_locals, **prev_args;
6319         MonoType **prev_arg_types;
6320         guint prev_real_offset;
6321         GHashTable *prev_cbb_hash;
6322         MonoBasicBlock **prev_cil_offset_to_bb;
6323         MonoBasicBlock *prev_cbb;
6324         const unsigned char *prev_ip;
6325         unsigned char *prev_cil_start;
6326         guint32 prev_cil_offset_to_bb_len;
6327         MonoMethod *prev_current_method;
6328         MonoGenericContext *prev_generic_context;
6329         gboolean ret_var_set, prev_ret_var_set, prev_disable_inline, virtual_ = FALSE;
6330
6331         g_assert (cfg->exception_type == MONO_EXCEPTION_NONE);
6332
6333 #if (MONO_INLINE_CALLED_LIMITED_METHODS)
6334         if ((! inline_always) && ! check_inline_called_method_name_limit (cmethod))
6335                 return 0;
6336 #endif
6337 #if (MONO_INLINE_CALLER_LIMITED_METHODS)
6338         if ((! inline_always) && ! check_inline_caller_method_name_limit (cfg->method))
6339                 return 0;
6340 #endif
6341
6342         if (!fsig)
6343                 fsig = mono_method_signature (cmethod);
6344
6345         if (cfg->verbose_level > 2)
6346                 printf ("INLINE START %p %s -> %s\n", cmethod,  mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
6347
6348         if (!cmethod->inline_info) {
6349                 cfg->stat_inlineable_methods++;
6350                 cmethod->inline_info = 1;
6351         }
6352
6353         /* allocate local variables */
6354         cheader = mono_method_get_header_checked (cmethod, &error);
6355         if (!cheader) {
6356                 if (inline_always) {
6357                         mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
6358                         mono_error_move (&cfg->error, &error);
6359                 } else {
6360                         mono_error_cleanup (&error);
6361                 }
6362                 return 0;
6363         }
6364
6365         /*Must verify before creating locals as it can cause the JIT to assert.*/
6366         if (mono_compile_is_broken (cfg, cmethod, FALSE)) {
6367                 mono_metadata_free_mh (cheader);
6368                 return 0;
6369         }
6370
6371         /* allocate space to store the return value */
6372         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
6373                 rvar = mono_compile_create_var (cfg, fsig->ret, OP_LOCAL);
6374         }
6375
6376         prev_locals = cfg->locals;
6377         cfg->locals = (MonoInst **)mono_mempool_alloc0 (cfg->mempool, cheader->num_locals * sizeof (MonoInst*));
6378         for (i = 0; i < cheader->num_locals; ++i)
6379                 cfg->locals [i] = mono_compile_create_var (cfg, cheader->locals [i], OP_LOCAL);
6380
6381         /* allocate start and end blocks */
6382         /* This is needed so if the inline is aborted, we can clean up */
6383         NEW_BBLOCK (cfg, sbblock);
6384         sbblock->real_offset = real_offset;
6385
6386         NEW_BBLOCK (cfg, ebblock);
6387         ebblock->block_num = cfg->num_bblocks++;
6388         ebblock->real_offset = real_offset;
6389
6390         prev_args = cfg->args;
6391         prev_arg_types = cfg->arg_types;
6392         prev_inlined_method = cfg->inlined_method;
6393         cfg->inlined_method = cmethod;
6394         cfg->ret_var_set = FALSE;
6395         cfg->inline_depth ++;
6396         prev_real_offset = cfg->real_offset;
6397         prev_cbb_hash = cfg->cbb_hash;
6398         prev_cil_offset_to_bb = cfg->cil_offset_to_bb;
6399         prev_cil_offset_to_bb_len = cfg->cil_offset_to_bb_len;
6400         prev_cil_start = cfg->cil_start;
6401         prev_ip = cfg->ip;
6402         prev_cbb = cfg->cbb;
6403         prev_current_method = cfg->current_method;
6404         prev_generic_context = cfg->generic_context;
6405         prev_ret_var_set = cfg->ret_var_set;
6406         prev_disable_inline = cfg->disable_inline;
6407
6408         if (ip && *ip == CEE_CALLVIRT && !(cmethod->flags & METHOD_ATTRIBUTE_STATIC))
6409                 virtual_ = TRUE;
6410
6411         costs = mono_method_to_ir (cfg, cmethod, sbblock, ebblock, rvar, sp, real_offset, virtual_);
6412
6413         ret_var_set = cfg->ret_var_set;
6414
6415         cfg->inlined_method = prev_inlined_method;
6416         cfg->real_offset = prev_real_offset;
6417         cfg->cbb_hash = prev_cbb_hash;
6418         cfg->cil_offset_to_bb = prev_cil_offset_to_bb;
6419         cfg->cil_offset_to_bb_len = prev_cil_offset_to_bb_len;
6420         cfg->cil_start = prev_cil_start;
6421         cfg->ip = prev_ip;
6422         cfg->locals = prev_locals;
6423         cfg->args = prev_args;
6424         cfg->arg_types = prev_arg_types;
6425         cfg->current_method = prev_current_method;
6426         cfg->generic_context = prev_generic_context;
6427         cfg->ret_var_set = prev_ret_var_set;
6428         cfg->disable_inline = prev_disable_inline;
6429         cfg->inline_depth --;
6430
6431         if ((costs >= 0 && costs < 60) || inline_always || (costs >= 0 && (cmethod->iflags & METHOD_IMPL_ATTRIBUTE_AGGRESSIVE_INLINING))) {
6432                 if (cfg->verbose_level > 2)
6433                         printf ("INLINE END %s -> %s\n", mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
6434
6435                 cfg->stat_inlined_methods++;
6436
6437                 /* always add some code to avoid block split failures */
6438                 MONO_INST_NEW (cfg, ins, OP_NOP);
6439                 MONO_ADD_INS (prev_cbb, ins);
6440
6441                 prev_cbb->next_bb = sbblock;
6442                 link_bblock (cfg, prev_cbb, sbblock);
6443
6444                 /* 
6445                  * Get rid of the begin and end bblocks if possible to aid local
6446                  * optimizations.
6447                  */
6448                 if (prev_cbb->out_count == 1)
6449                         mono_merge_basic_blocks (cfg, prev_cbb, sbblock);
6450
6451                 if ((prev_cbb->out_count == 1) && (prev_cbb->out_bb [0]->in_count == 1) && (prev_cbb->out_bb [0] != ebblock))
6452                         mono_merge_basic_blocks (cfg, prev_cbb, prev_cbb->out_bb [0]);
6453
6454                 if ((ebblock->in_count == 1) && ebblock->in_bb [0]->out_count == 1) {
6455                         MonoBasicBlock *prev = ebblock->in_bb [0];
6456
6457                         if (prev->next_bb == ebblock) {
6458                                 mono_merge_basic_blocks (cfg, prev, ebblock);
6459                                 cfg->cbb = prev;
6460                                 if ((prev_cbb->out_count == 1) && (prev_cbb->out_bb [0]->in_count == 1) && (prev_cbb->out_bb [0] == prev)) {
6461                                         mono_merge_basic_blocks (cfg, prev_cbb, prev);
6462                                         cfg->cbb = prev_cbb;
6463                                 }
6464                         } else {
6465                                 /* There could be a bblock after 'prev', and making 'prev' the current bb could cause problems */
6466                                 cfg->cbb = ebblock;
6467                         }
6468                 } else {
6469                         /* 
6470                          * Its possible that the rvar is set in some prev bblock, but not in others.
6471                          * (#1835).
6472                          */
6473                         if (rvar) {
6474                                 MonoBasicBlock *bb;
6475
6476                                 for (i = 0; i < ebblock->in_count; ++i) {
6477                                         bb = ebblock->in_bb [i];
6478
6479                                         if (bb->last_ins && bb->last_ins->opcode == OP_NOT_REACHED) {
6480                                                 cfg->cbb = bb;
6481
6482                                                 emit_init_rvar (cfg, rvar->dreg, fsig->ret);
6483                                         }
6484                                 }
6485                         }
6486
6487                         cfg->cbb = ebblock;
6488                 }
6489
6490                 if (rvar) {
6491                         /*
6492                          * If the inlined method contains only a throw, then the ret var is not 
6493                          * set, so set it to a dummy value.
6494                          */
6495                         if (!ret_var_set)
6496                                 emit_init_rvar (cfg, rvar->dreg, fsig->ret);
6497
6498                         EMIT_NEW_TEMPLOAD (cfg, ins, rvar->inst_c0);
6499                         *sp++ = ins;
6500                 }
6501                 cfg->headers_to_free = g_slist_prepend_mempool (cfg->mempool, cfg->headers_to_free, cheader);
6502                 return costs + 1;
6503         } else {
6504                 if (cfg->verbose_level > 2)
6505                         printf ("INLINE ABORTED %s (cost %d)\n", mono_method_full_name (cmethod, TRUE), costs);
6506                 cfg->exception_type = MONO_EXCEPTION_NONE;
6507
6508                 /* This gets rid of the newly added bblocks */
6509                 cfg->cbb = prev_cbb;
6510         }
6511         cfg->headers_to_free = g_slist_prepend_mempool (cfg->mempool, cfg->headers_to_free, cheader);
6512         return 0;
6513 }
6514
6515 /*
6516  * Some of these comments may well be out-of-date.
6517  * Design decisions: we do a single pass over the IL code (and we do bblock 
6518  * splitting/merging in the few cases when it's required: a back jump to an IL
6519  * address that was not already seen as bblock starting point).
6520  * Code is validated as we go (full verification is still better left to metadata/verify.c).
6521  * Complex operations are decomposed in simpler ones right away. We need to let the 
6522  * arch-specific code peek and poke inside this process somehow (except when the 
6523  * optimizations can take advantage of the full semantic info of coarse opcodes).
6524  * All the opcodes of the form opcode.s are 'normalized' to opcode.
6525  * MonoInst->opcode initially is the IL opcode or some simplification of that 
6526  * (OP_LOAD, OP_STORE). The arch-specific code may rearrange it to an arch-specific 
6527  * opcode with value bigger than OP_LAST.
6528  * At this point the IR can be handed over to an interpreter, a dumb code generator
6529  * or to the optimizing code generator that will translate it to SSA form.
6530  *
6531  * Profiling directed optimizations.
6532  * We may compile by default with few or no optimizations and instrument the code
6533  * or the user may indicate what methods to optimize the most either in a config file
6534  * or through repeated runs where the compiler applies offline the optimizations to 
6535  * each method and then decides if it was worth it.
6536  */
6537
6538 #define CHECK_TYPE(ins) if (!(ins)->type) UNVERIFIED
6539 #define CHECK_STACK(num) if ((sp - stack_start) < (num)) UNVERIFIED
6540 #define CHECK_STACK_OVF(num) if (((sp - stack_start) + (num)) > header->max_stack) UNVERIFIED
6541 #define CHECK_ARG(num) if ((unsigned)(num) >= (unsigned)num_args) UNVERIFIED
6542 #define CHECK_LOCAL(num) if ((unsigned)(num) >= (unsigned)header->num_locals) UNVERIFIED
6543 #define CHECK_OPSIZE(size) if (ip + size > end) UNVERIFIED
6544 #define CHECK_UNVERIFIABLE(cfg) if (cfg->unverifiable) UNVERIFIED
6545 #define CHECK_TYPELOAD(klass) if (!(klass) || mono_class_has_failure (klass)) TYPE_LOAD_ERROR ((klass))
6546
6547 /* offset from br.s -> br like opcodes */
6548 #define BIG_BRANCH_OFFSET 13
6549
6550 static gboolean
6551 ip_in_bb (MonoCompile *cfg, MonoBasicBlock *bb, const guint8* ip)
6552 {
6553         MonoBasicBlock *b = cfg->cil_offset_to_bb [ip - cfg->cil_start];
6554
6555         return b == NULL || b == bb;
6556 }
6557
6558 static int
6559 get_basic_blocks (MonoCompile *cfg, MonoMethodHeader* header, guint real_offset, unsigned char *start, unsigned char *end, unsigned char **pos)
6560 {
6561         unsigned char *ip = start;
6562         unsigned char *target;
6563         int i;
6564         guint cli_addr;
6565         MonoBasicBlock *bblock;
6566         const MonoOpcode *opcode;
6567
6568         while (ip < end) {
6569                 cli_addr = ip - start;
6570                 i = mono_opcode_value ((const guint8 **)&ip, end);
6571                 if (i < 0)
6572                         UNVERIFIED;
6573                 opcode = &mono_opcodes [i];
6574                 switch (opcode->argument) {
6575                 case MonoInlineNone:
6576                         ip++; 
6577                         break;
6578                 case MonoInlineString:
6579                 case MonoInlineType:
6580                 case MonoInlineField:
6581                 case MonoInlineMethod:
6582                 case MonoInlineTok:
6583                 case MonoInlineSig:
6584                 case MonoShortInlineR:
6585                 case MonoInlineI:
6586                         ip += 5;
6587                         break;
6588                 case MonoInlineVar:
6589                         ip += 3;
6590                         break;
6591                 case MonoShortInlineVar:
6592                 case MonoShortInlineI:
6593                         ip += 2;
6594                         break;
6595                 case MonoShortInlineBrTarget:
6596                         target = start + cli_addr + 2 + (signed char)ip [1];
6597                         GET_BBLOCK (cfg, bblock, target);
6598                         ip += 2;
6599                         if (ip < end)
6600                                 GET_BBLOCK (cfg, bblock, ip);
6601                         break;
6602                 case MonoInlineBrTarget:
6603                         target = start + cli_addr + 5 + (gint32)read32 (ip + 1);
6604                         GET_BBLOCK (cfg, bblock, target);
6605                         ip += 5;
6606                         if (ip < end)
6607                                 GET_BBLOCK (cfg, bblock, ip);
6608                         break;
6609                 case MonoInlineSwitch: {
6610                         guint32 n = read32 (ip + 1);
6611                         guint32 j;
6612                         ip += 5;
6613                         cli_addr += 5 + 4 * n;
6614                         target = start + cli_addr;
6615                         GET_BBLOCK (cfg, bblock, target);
6616                         
6617                         for (j = 0; j < n; ++j) {
6618                                 target = start + cli_addr + (gint32)read32 (ip);
6619                                 GET_BBLOCK (cfg, bblock, target);
6620                                 ip += 4;
6621                         }
6622                         break;
6623                 }
6624                 case MonoInlineR:
6625                 case MonoInlineI8:
6626                         ip += 9;
6627                         break;
6628                 default:
6629                         g_assert_not_reached ();
6630                 }
6631
6632                 if (i == CEE_THROW) {
6633                         unsigned char *bb_start = ip - 1;
6634                         
6635                         /* Find the start of the bblock containing the throw */
6636                         bblock = NULL;
6637                         while ((bb_start >= start) && !bblock) {
6638                                 bblock = cfg->cil_offset_to_bb [(bb_start) - start];
6639                                 bb_start --;
6640                         }
6641                         if (bblock)
6642                                 bblock->out_of_line = 1;
6643                 }
6644         }
6645         return 0;
6646 unverified:
6647 exception_exit:
6648         *pos = ip;
6649         return 1;
6650 }
6651
6652 static inline MonoMethod *
6653 mini_get_method_allow_open (MonoMethod *m, guint32 token, MonoClass *klass, MonoGenericContext *context, MonoError *error)
6654 {
6655         MonoMethod *method;
6656
6657         error_init (error);
6658
6659         if (m->wrapper_type != MONO_WRAPPER_NONE) {
6660                 method = (MonoMethod *)mono_method_get_wrapper_data (m, token);
6661                 if (context) {
6662                         method = mono_class_inflate_generic_method_checked (method, context, error);
6663                 }
6664         } else {
6665                 method = mono_get_method_checked (m->klass->image, token, klass, context, error);
6666         }
6667
6668         return method;
6669 }
6670
6671 static inline MonoMethod *
6672 mini_get_method (MonoCompile *cfg, MonoMethod *m, guint32 token, MonoClass *klass, MonoGenericContext *context)
6673 {
6674         MonoError error;
6675         MonoMethod *method = mini_get_method_allow_open (m, token, klass, context, cfg ? &cfg->error : &error);
6676
6677         if (method && cfg && !cfg->gshared && mono_class_is_open_constructed_type (&method->klass->byval_arg)) {
6678                 mono_error_set_bad_image (&cfg->error, cfg->method->klass->image, "Method with open type while not compiling gshared");
6679                 method = NULL;
6680         }
6681
6682         if (!method && !cfg)
6683                 mono_error_cleanup (&error); /* FIXME don't swallow the error */
6684
6685         return method;
6686 }
6687
6688 MonoClass*
6689 mini_get_class (MonoMethod *method, guint32 token, MonoGenericContext *context)
6690 {
6691         MonoError error;
6692         MonoClass *klass;
6693
6694         if (method->wrapper_type != MONO_WRAPPER_NONE) {
6695                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
6696                 if (context) {
6697                         klass = mono_class_inflate_generic_class_checked (klass, context, &error);
6698                         mono_error_cleanup (&error); /* FIXME don't swallow the error */
6699                 }
6700         } else {
6701                 klass = mono_class_get_and_inflate_typespec_checked (method->klass->image, token, context, &error);
6702                 mono_error_cleanup (&error); /* FIXME don't swallow the error */
6703         }
6704         if (klass)
6705                 mono_class_init (klass);
6706         return klass;
6707 }
6708
6709 static inline MonoMethodSignature*
6710 mini_get_signature (MonoMethod *method, guint32 token, MonoGenericContext *context, MonoError *error)
6711 {
6712         MonoMethodSignature *fsig;
6713
6714         error_init (error);
6715         if (method->wrapper_type != MONO_WRAPPER_NONE) {
6716                 fsig = (MonoMethodSignature *)mono_method_get_wrapper_data (method, token);
6717         } else {
6718                 fsig = mono_metadata_parse_signature_checked (method->klass->image, token, error);
6719                 return_val_if_nok (error, NULL);
6720         }
6721         if (context) {
6722                 fsig = mono_inflate_generic_signature(fsig, context, error);
6723         }
6724         return fsig;
6725 }
6726
6727 static MonoMethod*
6728 throw_exception (void)
6729 {
6730         static MonoMethod *method = NULL;
6731
6732         if (!method) {
6733                 MonoSecurityManager *secman = mono_security_manager_get_methods ();
6734                 method = mono_class_get_method_from_name (secman->securitymanager, "ThrowException", 1);
6735         }
6736         g_assert (method);
6737         return method;
6738 }
6739
6740 static void
6741 emit_throw_exception (MonoCompile *cfg, MonoException *ex)
6742 {
6743         MonoMethod *thrower = throw_exception ();
6744         MonoInst *args [1];
6745
6746         EMIT_NEW_PCONST (cfg, args [0], ex);
6747         mono_emit_method_call (cfg, thrower, args, NULL);
6748 }
6749
6750 /*
6751  * Return the original method is a wrapper is specified. We can only access 
6752  * the custom attributes from the original method.
6753  */
6754 static MonoMethod*
6755 get_original_method (MonoMethod *method)
6756 {
6757         if (method->wrapper_type == MONO_WRAPPER_NONE)
6758                 return method;
6759
6760         /* native code (which is like Critical) can call any managed method XXX FIXME XXX to validate all usages */
6761         if (method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED)
6762                 return NULL;
6763
6764         /* in other cases we need to find the original method */
6765         return mono_marshal_method_from_wrapper (method);
6766 }
6767
6768 static void
6769 ensure_method_is_allowed_to_access_field (MonoCompile *cfg, MonoMethod *caller, MonoClassField *field)
6770 {
6771         /* we can't get the coreclr security level on wrappers since they don't have the attributes */
6772         MonoException *ex = mono_security_core_clr_is_field_access_allowed (get_original_method (caller), field);
6773         if (ex)
6774                 emit_throw_exception (cfg, ex);
6775 }
6776
6777 static void
6778 ensure_method_is_allowed_to_call_method (MonoCompile *cfg, MonoMethod *caller, MonoMethod *callee)
6779 {
6780         /* we can't get the coreclr security level on wrappers since they don't have the attributes */
6781         MonoException *ex = mono_security_core_clr_is_call_allowed (get_original_method (caller), callee);
6782         if (ex)
6783                 emit_throw_exception (cfg, ex);
6784 }
6785
6786 /*
6787  * Check that the IL instructions at ip are the array initialization
6788  * sequence and return the pointer to the data and the size.
6789  */
6790 static const char*
6791 initialize_array_data (MonoMethod *method, gboolean aot, unsigned char *ip, MonoClass *klass, guint32 len, int *out_size, guint32 *out_field_token)
6792 {
6793         /*
6794          * newarr[System.Int32]
6795          * dup
6796          * ldtoken field valuetype ...
6797          * call void class [mscorlib]System.Runtime.CompilerServices.RuntimeHelpers::InitializeArray(class [mscorlib]System.Array, valuetype [mscorlib]System.RuntimeFieldHandle)
6798          */
6799         if (ip [0] == CEE_DUP && ip [1] == CEE_LDTOKEN && ip [5] == 0x4 && ip [6] == CEE_CALL) {
6800                 MonoError error;
6801                 guint32 token = read32 (ip + 7);
6802                 guint32 field_token = read32 (ip + 2);
6803                 guint32 field_index = field_token & 0xffffff;
6804                 guint32 rva;
6805                 const char *data_ptr;
6806                 int size = 0;
6807                 MonoMethod *cmethod;
6808                 MonoClass *dummy_class;
6809                 MonoClassField *field = mono_field_from_token_checked (method->klass->image, field_token, &dummy_class, NULL, &error);
6810                 int dummy_align;
6811
6812                 if (!field) {
6813                         mono_error_cleanup (&error); /* FIXME don't swallow the error */
6814                         return NULL;
6815                 }
6816
6817                 *out_field_token = field_token;
6818
6819                 cmethod = mini_get_method (NULL, method, token, NULL, NULL);
6820                 if (!cmethod)
6821                         return NULL;
6822                 if (strcmp (cmethod->name, "InitializeArray") || strcmp (cmethod->klass->name, "RuntimeHelpers") || cmethod->klass->image != mono_defaults.corlib)
6823                         return NULL;
6824                 switch (mini_get_underlying_type (&klass->byval_arg)->type) {
6825                 case MONO_TYPE_I1:
6826                 case MONO_TYPE_U1:
6827                         size = 1; break;
6828                 /* we need to swap on big endian, so punt. Should we handle R4 and R8 as well? */
6829 #if TARGET_BYTE_ORDER == G_LITTLE_ENDIAN
6830                 case MONO_TYPE_I2:
6831                 case MONO_TYPE_U2:
6832                         size = 2; break;
6833                 case MONO_TYPE_I4:
6834                 case MONO_TYPE_U4:
6835                 case MONO_TYPE_R4:
6836                         size = 4; break;
6837                 case MONO_TYPE_R8:
6838                 case MONO_TYPE_I8:
6839                 case MONO_TYPE_U8:
6840                         size = 8; break;
6841 #endif
6842                 default:
6843                         return NULL;
6844                 }
6845                 size *= len;
6846                 if (size > mono_type_size (field->type, &dummy_align))
6847                     return NULL;
6848                 *out_size = size;
6849                 /*g_print ("optimized in %s: size: %d, numelems: %d\n", method->name, size, newarr->inst_newa_len->inst_c0);*/
6850                 if (!image_is_dynamic (method->klass->image)) {
6851                         field_index = read32 (ip + 2) & 0xffffff;
6852                         mono_metadata_field_info (method->klass->image, field_index - 1, NULL, &rva, NULL);
6853                         data_ptr = mono_image_rva_map (method->klass->image, rva);
6854                         /*g_print ("field: 0x%08x, rva: %d, rva_ptr: %p\n", read32 (ip + 2), rva, data_ptr);*/
6855                         /* for aot code we do the lookup on load */
6856                         if (aot && data_ptr)
6857                                 return (const char *)GUINT_TO_POINTER (rva);
6858                 } else {
6859                         /*FIXME is it possible to AOT a SRE assembly not meant to be saved? */ 
6860                         g_assert (!aot);
6861                         data_ptr = mono_field_get_data (field);
6862                 }
6863                 return data_ptr;
6864         }
6865         return NULL;
6866 }
6867
6868 static void
6869 set_exception_type_from_invalid_il (MonoCompile *cfg, MonoMethod *method, unsigned char *ip)
6870 {
6871         MonoError error;
6872         char *method_fname = mono_method_full_name (method, TRUE);
6873         char *method_code;
6874         MonoMethodHeader *header = mono_method_get_header_checked (method, &error);
6875
6876         if (!header) {
6877                 method_code = g_strdup_printf ("could not parse method body due to %s", mono_error_get_message (&error));
6878                 mono_error_cleanup (&error);
6879         } else if (header->code_size == 0)
6880                 method_code = g_strdup ("method body is empty.");
6881         else
6882                 method_code = mono_disasm_code_one (NULL, method, ip, NULL);
6883         mono_cfg_set_exception_invalid_program (cfg, g_strdup_printf ("Invalid IL code in %s: %s\n", method_fname, method_code));
6884         g_free (method_fname);
6885         g_free (method_code);
6886         cfg->headers_to_free = g_slist_prepend_mempool (cfg->mempool, cfg->headers_to_free, header);
6887 }
6888
6889 static void
6890 emit_stloc_ir (MonoCompile *cfg, MonoInst **sp, MonoMethodHeader *header, int n)
6891 {
6892         MonoInst *ins;
6893         guint32 opcode = mono_type_to_regmove (cfg, header->locals [n]);
6894         if ((opcode == OP_MOVE) && cfg->cbb->last_ins == sp [0]  &&
6895                         ((sp [0]->opcode == OP_ICONST) || (sp [0]->opcode == OP_I8CONST))) {
6896                 /* Optimize reg-reg moves away */
6897                 /* 
6898                  * Can't optimize other opcodes, since sp[0] might point to
6899                  * the last ins of a decomposed opcode.
6900                  */
6901                 sp [0]->dreg = (cfg)->locals [n]->dreg;
6902         } else {
6903                 EMIT_NEW_LOCSTORE (cfg, ins, n, *sp);
6904         }
6905 }
6906
6907 /*
6908  * ldloca inhibits many optimizations so try to get rid of it in common
6909  * cases.
6910  */
6911 static inline unsigned char *
6912 emit_optimized_ldloca_ir (MonoCompile *cfg, unsigned char *ip, unsigned char *end, int size)
6913 {
6914         int local, token;
6915         MonoClass *klass;
6916         MonoType *type;
6917
6918         if (size == 1) {
6919                 local = ip [1];
6920                 ip += 2;
6921         } else {
6922                 local = read16 (ip + 2);
6923                 ip += 4;
6924         }
6925         
6926         if (ip + 6 < end && (ip [0] == CEE_PREFIX1) && (ip [1] == CEE_INITOBJ) && ip_in_bb (cfg, cfg->cbb, ip + 1)) {
6927                 /* From the INITOBJ case */
6928                 token = read32 (ip + 2);
6929                 klass = mini_get_class (cfg->current_method, token, cfg->generic_context);
6930                 CHECK_TYPELOAD (klass);
6931                 type = mini_get_underlying_type (&klass->byval_arg);
6932                 emit_init_local (cfg, local, type, TRUE);
6933                 return ip + 6;
6934         }
6935  exception_exit:
6936         return NULL;
6937 }
6938
6939 static MonoInst*
6940 emit_llvmonly_virtual_call (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, int context_used, MonoInst **sp)
6941 {
6942         MonoInst *icall_args [16];
6943         MonoInst *call_target, *ins, *vtable_ins;
6944         int arg_reg, this_reg, vtable_reg;
6945         gboolean is_iface = mono_class_is_interface (cmethod->klass);
6946         gboolean is_gsharedvt = cfg->gsharedvt && mini_is_gsharedvt_variable_signature (fsig);
6947         gboolean variant_iface = FALSE;
6948         guint32 slot;
6949         int offset;
6950         gboolean special_array_interface = cmethod->klass->is_array_special_interface;
6951
6952         /*
6953          * In llvm-only mode, vtables contain function descriptors instead of
6954          * method addresses/trampolines.
6955          */
6956         MONO_EMIT_NULL_CHECK (cfg, sp [0]->dreg);
6957
6958         if (is_iface)
6959                 slot = mono_method_get_imt_slot (cmethod);
6960         else
6961                 slot = mono_method_get_vtable_index (cmethod);
6962
6963         this_reg = sp [0]->dreg;
6964
6965         if (is_iface && mono_class_has_variant_generic_params (cmethod->klass))
6966                 variant_iface = TRUE;
6967
6968         if (!fsig->generic_param_count && !is_iface && !is_gsharedvt) {
6969                 /*
6970                  * The simplest case, a normal virtual call.
6971                  */
6972                 int slot_reg = alloc_preg (cfg);
6973                 int addr_reg = alloc_preg (cfg);
6974                 int arg_reg = alloc_preg (cfg);
6975                 MonoBasicBlock *non_null_bb;
6976
6977                 vtable_reg = alloc_preg (cfg);
6978                 EMIT_NEW_LOAD_MEMBASE (cfg, vtable_ins, OP_LOAD_MEMBASE, vtable_reg, this_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
6979                 offset = MONO_STRUCT_OFFSET (MonoVTable, vtable) + (slot * SIZEOF_VOID_P);
6980
6981                 /* Load the vtable slot, which contains a function descriptor. */
6982                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, slot_reg, vtable_reg, offset);
6983
6984                 NEW_BBLOCK (cfg, non_null_bb);
6985
6986                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, slot_reg, 0);
6987                 cfg->cbb->last_ins->flags |= MONO_INST_LIKELY;
6988                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, non_null_bb);
6989
6990                 /* Slow path */
6991                 // FIXME: Make the wrapper use the preserveall cconv
6992                 // FIXME: Use one icall per slot for small slot numbers ?
6993                 icall_args [0] = vtable_ins;
6994                 EMIT_NEW_ICONST (cfg, icall_args [1], slot);
6995                 /* Make the icall return the vtable slot value to save some code space */
6996                 ins = mono_emit_jit_icall (cfg, mono_init_vtable_slot, icall_args);
6997                 ins->dreg = slot_reg;
6998                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, non_null_bb);
6999
7000                 /* Fastpath */
7001                 MONO_START_BB (cfg, non_null_bb);
7002                 /* Load the address + arg from the vtable slot */
7003                 EMIT_NEW_LOAD_MEMBASE (cfg, call_target, OP_LOAD_MEMBASE, addr_reg, slot_reg, 0);
7004                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, arg_reg, slot_reg, SIZEOF_VOID_P);
7005
7006                 return emit_extra_arg_calli (cfg, fsig, sp, arg_reg, call_target);
7007         }
7008
7009         if (!fsig->generic_param_count && is_iface && !variant_iface && !is_gsharedvt && !special_array_interface) {
7010                 /*
7011                  * A simple interface call
7012                  *
7013                  * We make a call through an imt slot to obtain the function descriptor we need to call.
7014                  * The imt slot contains a function descriptor for a runtime function + arg.
7015                  */
7016                 int slot_reg = alloc_preg (cfg);
7017                 int addr_reg = alloc_preg (cfg);
7018                 int arg_reg = alloc_preg (cfg);
7019                 MonoInst *thunk_addr_ins, *thunk_arg_ins, *ftndesc_ins;
7020
7021                 vtable_reg = alloc_preg (cfg);
7022                 EMIT_NEW_LOAD_MEMBASE (cfg, vtable_ins, OP_LOAD_MEMBASE, vtable_reg, this_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
7023                 offset = ((gint32)slot - MONO_IMT_SIZE) * SIZEOF_VOID_P;
7024
7025                 /*
7026                  * The slot is already initialized when the vtable is created so there is no need
7027                  * to check it here.
7028                  */
7029
7030                 /* Load the imt slot, which contains a function descriptor. */
7031                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, slot_reg, vtable_reg, offset);
7032
7033                 /* Load the address + arg of the imt thunk from the imt slot */
7034                 EMIT_NEW_LOAD_MEMBASE (cfg, thunk_addr_ins, OP_LOAD_MEMBASE, addr_reg, slot_reg, 0);
7035                 EMIT_NEW_LOAD_MEMBASE (cfg, thunk_arg_ins, OP_LOAD_MEMBASE, arg_reg, slot_reg, SIZEOF_VOID_P);
7036                 /*
7037                  * IMT thunks in llvm-only mode are C functions which take an info argument
7038                  * plus the imt method and return the ftndesc to call.
7039                  */
7040                 icall_args [0] = thunk_arg_ins;
7041                 icall_args [1] = emit_get_rgctx_method (cfg, context_used,
7042                                                                                                 cmethod, MONO_RGCTX_INFO_METHOD);
7043                 ftndesc_ins = mini_emit_calli (cfg, helper_sig_llvmonly_imt_trampoline, icall_args, thunk_addr_ins, NULL, NULL);
7044
7045                 return emit_llvmonly_calli (cfg, fsig, sp, ftndesc_ins);
7046         }
7047
7048         if ((fsig->generic_param_count || variant_iface || special_array_interface) && !is_gsharedvt) {
7049                 /*
7050                  * This is similar to the interface case, the vtable slot points to an imt thunk which is
7051                  * dynamically extended as more instantiations are discovered.
7052                  * This handles generic virtual methods both on classes and interfaces.
7053                  */
7054                 int slot_reg = alloc_preg (cfg);
7055                 int addr_reg = alloc_preg (cfg);
7056                 int arg_reg = alloc_preg (cfg);
7057                 int ftndesc_reg = alloc_preg (cfg);
7058                 MonoInst *thunk_addr_ins, *thunk_arg_ins, *ftndesc_ins;
7059                 MonoBasicBlock *slowpath_bb, *end_bb;
7060
7061                 NEW_BBLOCK (cfg, slowpath_bb);
7062                 NEW_BBLOCK (cfg, end_bb);
7063
7064                 vtable_reg = alloc_preg (cfg);
7065                 EMIT_NEW_LOAD_MEMBASE (cfg, vtable_ins, OP_LOAD_MEMBASE, vtable_reg, this_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
7066                 if (is_iface)
7067                         offset = ((gint32)slot - MONO_IMT_SIZE) * SIZEOF_VOID_P;
7068                 else
7069                         offset = MONO_STRUCT_OFFSET (MonoVTable, vtable) + (slot * SIZEOF_VOID_P);
7070
7071                 /* Load the slot, which contains a function descriptor. */
7072                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, slot_reg, vtable_reg, offset);
7073
7074                 /* These slots are not initialized, so fall back to the slow path until they are initialized */
7075                 /* That happens when mono_method_add_generic_virtual_invocation () creates an IMT thunk */
7076                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, slot_reg, 0);
7077                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, slowpath_bb);
7078
7079                 /* Fastpath */
7080                 /* Same as with iface calls */
7081                 EMIT_NEW_LOAD_MEMBASE (cfg, thunk_addr_ins, OP_LOAD_MEMBASE, addr_reg, slot_reg, 0);
7082                 EMIT_NEW_LOAD_MEMBASE (cfg, thunk_arg_ins, OP_LOAD_MEMBASE, arg_reg, slot_reg, SIZEOF_VOID_P);
7083                 icall_args [0] = thunk_arg_ins;
7084                 icall_args [1] = emit_get_rgctx_method (cfg, context_used,
7085                                                                                                 cmethod, MONO_RGCTX_INFO_METHOD);
7086                 ftndesc_ins = mini_emit_calli (cfg, helper_sig_llvmonly_imt_trampoline, icall_args, thunk_addr_ins, NULL, NULL);
7087                 ftndesc_ins->dreg = ftndesc_reg;
7088                 /*
7089                  * Unlike normal iface calls, these imt thunks can return NULL, i.e. when they are passed an instantiation
7090                  * they don't know about yet. Fall back to the slowpath in that case.
7091                  */
7092                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, ftndesc_reg, 0);
7093                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, slowpath_bb);
7094
7095                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
7096
7097                 /* Slowpath */
7098                 MONO_START_BB (cfg, slowpath_bb);
7099                 icall_args [0] = vtable_ins;
7100                 EMIT_NEW_ICONST (cfg, icall_args [1], slot);
7101                 icall_args [2] = emit_get_rgctx_method (cfg, context_used,
7102                                                                                                 cmethod, MONO_RGCTX_INFO_METHOD);
7103                 if (is_iface)
7104                         ftndesc_ins = mono_emit_jit_icall (cfg, mono_resolve_generic_virtual_iface_call, icall_args);
7105                 else
7106                         ftndesc_ins = mono_emit_jit_icall (cfg, mono_resolve_generic_virtual_call, icall_args);
7107                 ftndesc_ins->dreg = ftndesc_reg;
7108                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
7109
7110                 /* Common case */
7111                 MONO_START_BB (cfg, end_bb);
7112                 return emit_llvmonly_calli (cfg, fsig, sp, ftndesc_ins);
7113         }
7114
7115         /*
7116          * Non-optimized cases
7117          */
7118         icall_args [0] = sp [0];
7119         EMIT_NEW_ICONST (cfg, icall_args [1], slot);
7120
7121         icall_args [2] = emit_get_rgctx_method (cfg, context_used,
7122                                                                                         cmethod, MONO_RGCTX_INFO_METHOD);
7123
7124         arg_reg = alloc_preg (cfg);
7125         MONO_EMIT_NEW_PCONST (cfg, arg_reg, NULL);
7126         EMIT_NEW_VARLOADA_VREG (cfg, icall_args [3], arg_reg, &mono_defaults.int_class->byval_arg);
7127
7128         g_assert (is_gsharedvt);
7129         if (is_iface)
7130                 call_target = mono_emit_jit_icall (cfg, mono_resolve_iface_call_gsharedvt, icall_args);
7131         else
7132                 call_target = mono_emit_jit_icall (cfg, mono_resolve_vcall_gsharedvt, icall_args);
7133
7134         /*
7135          * Pass the extra argument even if the callee doesn't receive it, most
7136          * calling conventions allow this.
7137          */
7138         return emit_extra_arg_calli (cfg, fsig, sp, arg_reg, call_target);
7139 }
7140
7141 static gboolean
7142 is_exception_class (MonoClass *klass)
7143 {
7144         while (klass) {
7145                 if (klass == mono_defaults.exception_class)
7146                         return TRUE;
7147                 klass = klass->parent;
7148         }
7149         return FALSE;
7150 }
7151
7152 /*
7153  * is_jit_optimizer_disabled:
7154  *
7155  *   Determine whenever M's assembly has a DebuggableAttribute with the
7156  * IsJITOptimizerDisabled flag set.
7157  */
7158 static gboolean
7159 is_jit_optimizer_disabled (MonoMethod *m)
7160 {
7161         MonoError error;
7162         MonoAssembly *ass = m->klass->image->assembly;
7163         MonoCustomAttrInfo* attrs;
7164         MonoClass *klass;
7165         int i;
7166         gboolean val = FALSE;
7167
7168         g_assert (ass);
7169         if (ass->jit_optimizer_disabled_inited)
7170                 return ass->jit_optimizer_disabled;
7171
7172         klass = mono_class_try_get_debuggable_attribute_class ();
7173
7174         if (!klass) {
7175                 /* Linked away */
7176                 ass->jit_optimizer_disabled = FALSE;
7177                 mono_memory_barrier ();
7178                 ass->jit_optimizer_disabled_inited = TRUE;
7179                 return FALSE;
7180         }
7181
7182         attrs = mono_custom_attrs_from_assembly_checked (ass, FALSE, &error);
7183         mono_error_cleanup (&error); /* FIXME don't swallow the error */
7184         if (attrs) {
7185                 for (i = 0; i < attrs->num_attrs; ++i) {
7186                         MonoCustomAttrEntry *attr = &attrs->attrs [i];
7187                         const gchar *p;
7188                         MonoMethodSignature *sig;
7189
7190                         if (!attr->ctor || attr->ctor->klass != klass)
7191                                 continue;
7192                         /* Decode the attribute. See reflection.c */
7193                         p = (const char*)attr->data;
7194                         g_assert (read16 (p) == 0x0001);
7195                         p += 2;
7196
7197                         // FIXME: Support named parameters
7198                         sig = mono_method_signature (attr->ctor);
7199                         if (sig->param_count != 2 || sig->params [0]->type != MONO_TYPE_BOOLEAN || sig->params [1]->type != MONO_TYPE_BOOLEAN)
7200                                 continue;
7201                         /* Two boolean arguments */
7202                         p ++;
7203                         val = *p;
7204                 }
7205                 mono_custom_attrs_free (attrs);
7206         }
7207
7208         ass->jit_optimizer_disabled = val;
7209         mono_memory_barrier ();
7210         ass->jit_optimizer_disabled_inited = TRUE;
7211
7212         return val;
7213 }
7214
7215 static gboolean
7216 is_supported_tail_call (MonoCompile *cfg, MonoMethod *method, MonoMethod *cmethod, MonoMethodSignature *fsig, int call_opcode)
7217 {
7218         gboolean supported_tail_call;
7219         int i;
7220
7221         supported_tail_call = mono_arch_tail_call_supported (cfg, mono_method_signature (method), mono_method_signature (cmethod));
7222
7223         for (i = 0; i < fsig->param_count; ++i) {
7224                 if (fsig->params [i]->byref || fsig->params [i]->type == MONO_TYPE_PTR || fsig->params [i]->type == MONO_TYPE_FNPTR)
7225                         /* These can point to the current method's stack */
7226                         supported_tail_call = FALSE;
7227         }
7228         if (fsig->hasthis && cmethod->klass->valuetype)
7229                 /* this might point to the current method's stack */
7230                 supported_tail_call = FALSE;
7231         if (cmethod->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)
7232                 supported_tail_call = FALSE;
7233         if (cfg->method->save_lmf)
7234                 supported_tail_call = FALSE;
7235         if (cmethod->wrapper_type && cmethod->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
7236                 supported_tail_call = FALSE;
7237         if (call_opcode != CEE_CALL)
7238                 supported_tail_call = FALSE;
7239
7240         /* Debugging support */
7241 #if 0
7242         if (supported_tail_call) {
7243                 if (!mono_debug_count ())
7244                         supported_tail_call = FALSE;
7245         }
7246 #endif
7247
7248         return supported_tail_call;
7249 }
7250
7251 /*
7252  * handle_ctor_call:
7253  *
7254  *   Handle calls made to ctors from NEWOBJ opcodes.
7255  */
7256 static void
7257 handle_ctor_call (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, int context_used,
7258                                   MonoInst **sp, guint8 *ip, int *inline_costs)
7259 {
7260         MonoInst *vtable_arg = NULL, *callvirt_this_arg = NULL, *ins;
7261
7262         if (cmethod->klass->valuetype && mono_class_generic_sharing_enabled (cmethod->klass) &&
7263                                         mono_method_is_generic_sharable (cmethod, TRUE)) {
7264                 if (cmethod->is_inflated && mono_method_get_context (cmethod)->method_inst) {
7265                         mono_class_vtable (cfg->domain, cmethod->klass);
7266                         CHECK_TYPELOAD (cmethod->klass);
7267
7268                         vtable_arg = emit_get_rgctx_method (cfg, context_used,
7269                                                                                                 cmethod, MONO_RGCTX_INFO_METHOD_RGCTX);
7270                 } else {
7271                         if (context_used) {
7272                                 vtable_arg = mini_emit_get_rgctx_klass (cfg, context_used,
7273                                                                                                    cmethod->klass, MONO_RGCTX_INFO_VTABLE);
7274                         } else {
7275                                 MonoVTable *vtable = mono_class_vtable (cfg->domain, cmethod->klass);
7276
7277                                 CHECK_TYPELOAD (cmethod->klass);
7278                                 EMIT_NEW_VTABLECONST (cfg, vtable_arg, vtable);
7279                         }
7280                 }
7281         }
7282
7283         /* Avoid virtual calls to ctors if possible */
7284         if (mono_class_is_marshalbyref (cmethod->klass))
7285                 callvirt_this_arg = sp [0];
7286
7287         if (cmethod && (cfg->opt & MONO_OPT_INTRINS) && (ins = mini_emit_inst_for_ctor (cfg, cmethod, fsig, sp))) {
7288                 g_assert (MONO_TYPE_IS_VOID (fsig->ret));
7289                 CHECK_CFG_EXCEPTION;
7290         } else if ((cfg->opt & MONO_OPT_INLINE) && cmethod && !context_used && !vtable_arg &&
7291                            mono_method_check_inlining (cfg, cmethod) &&
7292                            !mono_class_is_subclass_of (cmethod->klass, mono_defaults.exception_class, FALSE)) {
7293                 int costs;
7294
7295                 if ((costs = inline_method (cfg, cmethod, fsig, sp, ip, cfg->real_offset, FALSE))) {
7296                         cfg->real_offset += 5;
7297
7298                         *inline_costs += costs - 5;
7299                 } else {
7300                         INLINE_FAILURE ("inline failure");
7301                         // FIXME-VT: Clean this up
7302                         if (cfg->gsharedvt && mini_is_gsharedvt_signature (fsig))
7303                                 GSHAREDVT_FAILURE(*ip);
7304                         mono_emit_method_call_full (cfg, cmethod, fsig, FALSE, sp, callvirt_this_arg, NULL, NULL);
7305                 }
7306         } else if (cfg->gsharedvt && mini_is_gsharedvt_signature (fsig)) {
7307                 MonoInst *addr;
7308
7309                 addr = emit_get_rgctx_gsharedvt_call (cfg, context_used, fsig, cmethod, MONO_RGCTX_INFO_METHOD_GSHAREDVT_OUT_TRAMPOLINE);
7310
7311                 if (cfg->llvm_only) {
7312                         // FIXME: Avoid initializing vtable_arg
7313                         emit_llvmonly_calli (cfg, fsig, sp, addr);
7314                 } else {
7315                         mini_emit_calli (cfg, fsig, sp, addr, NULL, vtable_arg);
7316                 }
7317         } else if (context_used &&
7318                            ((!mono_method_is_generic_sharable_full (cmethod, TRUE, FALSE, FALSE) ||
7319                                  !mono_class_generic_sharing_enabled (cmethod->klass)) || cfg->gsharedvt)) {
7320                 MonoInst *cmethod_addr;
7321
7322                 /* Generic calls made out of gsharedvt methods cannot be patched, so use an indirect call */
7323
7324                 if (cfg->llvm_only) {
7325                         MonoInst *addr = emit_get_rgctx_method (cfg, context_used, cmethod,
7326                                                                                                         MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
7327                         emit_llvmonly_calli (cfg, fsig, sp, addr);
7328                 } else {
7329                         cmethod_addr = emit_get_rgctx_method (cfg, context_used,
7330                                                                                                   cmethod, MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
7331
7332                         mini_emit_calli (cfg, fsig, sp, cmethod_addr, NULL, vtable_arg);
7333                 }
7334         } else {
7335                 INLINE_FAILURE ("ctor call");
7336                 ins = mono_emit_method_call_full (cfg, cmethod, fsig, FALSE, sp,
7337                                                                                   callvirt_this_arg, NULL, vtable_arg);
7338         }
7339  exception_exit:
7340         return;
7341 }
7342
7343 static void
7344 emit_setret (MonoCompile *cfg, MonoInst *val)
7345 {
7346         MonoType *ret_type = mini_get_underlying_type (mono_method_signature (cfg->method)->ret);
7347         MonoInst *ins;
7348
7349         if (mini_type_to_stind (cfg, ret_type) == CEE_STOBJ) {
7350                 MonoInst *ret_addr;
7351
7352                 if (!cfg->vret_addr) {
7353                         EMIT_NEW_VARSTORE (cfg, ins, cfg->ret, ret_type, val);
7354                 } else {
7355                         EMIT_NEW_RETLOADA (cfg, ret_addr);
7356
7357                         EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STOREV_MEMBASE, ret_addr->dreg, 0, val->dreg);
7358                         ins->klass = mono_class_from_mono_type (ret_type);
7359                 }
7360         } else {
7361 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
7362                 if (COMPILE_SOFT_FLOAT (cfg) && !ret_type->byref && ret_type->type == MONO_TYPE_R4) {
7363                         MonoInst *iargs [1];
7364                         MonoInst *conv;
7365
7366                         iargs [0] = val;
7367                         conv = mono_emit_jit_icall (cfg, mono_fload_r4_arg, iargs);
7368                         mono_arch_emit_setret (cfg, cfg->method, conv);
7369                 } else {
7370                         mono_arch_emit_setret (cfg, cfg->method, val);
7371                 }
7372 #else
7373                 mono_arch_emit_setret (cfg, cfg->method, val);
7374 #endif
7375         }
7376 }
7377
7378 /*
7379  * mono_method_to_ir:
7380  *
7381  * Translate the .net IL into linear IR.
7382  *
7383  * @start_bblock: if not NULL, the starting basic block, used during inlining.
7384  * @end_bblock: if not NULL, the ending basic block, used during inlining.
7385  * @return_var: if not NULL, the place where the return value is stored, used during inlining.   
7386  * @inline_args: if not NULL, contains the arguments to the inline call
7387  * @inline_offset: if not zero, the real offset from the inline call, or zero otherwise.
7388  * @is_virtual_call: whether this method is being called as a result of a call to callvirt
7389  *
7390  * This method is used to turn ECMA IL into Mono's internal Linear IR
7391  * reprensetation.  It is used both for entire methods, as well as
7392  * inlining existing methods.  In the former case, the @start_bblock,
7393  * @end_bblock, @return_var, @inline_args are all set to NULL, and the
7394  * inline_offset is set to zero.
7395  * 
7396  * Returns: the inline cost, or -1 if there was an error processing this method.
7397  */
7398 int
7399 mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_bblock, MonoBasicBlock *end_bblock, 
7400                    MonoInst *return_var, MonoInst **inline_args, 
7401                    guint inline_offset, gboolean is_virtual_call)
7402 {
7403         MonoError error;
7404         MonoInst *ins, **sp, **stack_start;
7405         MonoBasicBlock *tblock = NULL, *init_localsbb = NULL;
7406         MonoSimpleBasicBlock *bb = NULL, *original_bb = NULL;
7407         MonoMethod *cmethod, *method_definition;
7408         MonoInst **arg_array;
7409         MonoMethodHeader *header;
7410         MonoImage *image;
7411         guint32 token, ins_flag;
7412         MonoClass *klass;
7413         MonoClass *constrained_class = NULL;
7414         unsigned char *ip, *end, *target, *err_pos;
7415         MonoMethodSignature *sig;
7416         MonoGenericContext *generic_context = NULL;
7417         MonoGenericContainer *generic_container = NULL;
7418         MonoType **param_types;
7419         int i, n, start_new_bblock, dreg;
7420         int num_calls = 0, inline_costs = 0;
7421         int breakpoint_id = 0;
7422         guint num_args;
7423         GSList *class_inits = NULL;
7424         gboolean dont_verify, dont_verify_stloc, readonly = FALSE;
7425         int context_used;
7426         gboolean init_locals, seq_points, skip_dead_blocks;
7427         gboolean sym_seq_points = FALSE;
7428         MonoDebugMethodInfo *minfo;
7429         MonoBitSet *seq_point_locs = NULL;
7430         MonoBitSet *seq_point_set_locs = NULL;
7431
7432         cfg->disable_inline = is_jit_optimizer_disabled (method);
7433
7434         /* serialization and xdomain stuff may need access to private fields and methods */
7435         dont_verify = method->klass->image->assembly->corlib_internal? TRUE: FALSE;
7436         dont_verify |= method->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE;
7437         dont_verify |= method->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH;
7438         dont_verify |= method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE; /* bug #77896 */
7439         dont_verify |= method->wrapper_type == MONO_WRAPPER_COMINTEROP;
7440         dont_verify |= method->wrapper_type == MONO_WRAPPER_COMINTEROP_INVOKE;
7441
7442         /* still some type unsafety issues in marshal wrappers... (unknown is PtrToStructure) */
7443         dont_verify_stloc = method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE;
7444         dont_verify_stloc |= method->wrapper_type == MONO_WRAPPER_UNKNOWN;
7445         dont_verify_stloc |= method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED;
7446         dont_verify_stloc |= method->wrapper_type == MONO_WRAPPER_STELEMREF;
7447
7448         image = method->klass->image;
7449         header = mono_method_get_header_checked (method, &cfg->error);
7450         if (!header) {
7451                 mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
7452                 goto exception_exit;
7453         } else {
7454                 cfg->headers_to_free = g_slist_prepend_mempool (cfg->mempool, cfg->headers_to_free, header);
7455         }
7456
7457         generic_container = mono_method_get_generic_container (method);
7458         sig = mono_method_signature (method);
7459         num_args = sig->hasthis + sig->param_count;
7460         ip = (unsigned char*)header->code;
7461         cfg->cil_start = ip;
7462         end = ip + header->code_size;
7463         cfg->stat_cil_code_size += header->code_size;
7464
7465         seq_points = cfg->gen_seq_points && cfg->method == method;
7466
7467         if (method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED) {
7468                 /* We could hit a seq point before attaching to the JIT (#8338) */
7469                 seq_points = FALSE;
7470         }
7471
7472         if (cfg->gen_sdb_seq_points && cfg->method == method) {
7473                 minfo = mono_debug_lookup_method (method);
7474                 if (minfo) {
7475                         MonoSymSeqPoint *sps;
7476                         int i, n_il_offsets;
7477
7478                         mono_debug_get_seq_points (minfo, NULL, NULL, NULL, &sps, &n_il_offsets);
7479                         seq_point_locs = mono_bitset_mem_new (mono_mempool_alloc0 (cfg->mempool, mono_bitset_alloc_size (header->code_size, 0)), header->code_size, 0);
7480                         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);
7481                         sym_seq_points = TRUE;
7482                         for (i = 0; i < n_il_offsets; ++i) {
7483                                 if (sps [i].il_offset < header->code_size)
7484                                         mono_bitset_set_fast (seq_point_locs, sps [i].il_offset);
7485                         }
7486                         g_free (sps);
7487
7488                         MonoDebugMethodAsyncInfo* asyncMethod = mono_debug_lookup_method_async_debug_info (method);
7489                         if (asyncMethod) {
7490                                 for (i = 0; asyncMethod != NULL && i < asyncMethod->num_awaits; i++)
7491                                 {
7492                                         mono_bitset_set_fast (seq_point_locs, asyncMethod->resume_offsets[i]);
7493                                         mono_bitset_set_fast (seq_point_locs, asyncMethod->yield_offsets[i]);
7494                                 }
7495                                 mono_debug_free_method_async_debug_info (asyncMethod);
7496                         }
7497                 } else if (!method->wrapper_type && !method->dynamic && mono_debug_image_has_debug_info (method->klass->image)) {
7498                         /* Methods without line number info like auto-generated property accessors */
7499                         seq_point_locs = mono_bitset_mem_new (mono_mempool_alloc0 (cfg->mempool, mono_bitset_alloc_size (header->code_size, 0)), header->code_size, 0);
7500                         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);
7501                         sym_seq_points = TRUE;
7502                 }
7503         }
7504
7505         /* 
7506          * Methods without init_locals set could cause asserts in various passes
7507          * (#497220). To work around this, we emit dummy initialization opcodes
7508          * (OP_DUMMY_ICONST etc.) which generate no code. These are only supported
7509          * on some platforms.
7510          */
7511         if ((cfg->opt & MONO_OPT_UNSAFE) && cfg->backend->have_dummy_init)
7512                 init_locals = header->init_locals;
7513         else
7514                 init_locals = TRUE;
7515
7516         method_definition = method;
7517         while (method_definition->is_inflated) {
7518                 MonoMethodInflated *imethod = (MonoMethodInflated *) method_definition;
7519                 method_definition = imethod->declaring;
7520         }
7521
7522         /* SkipVerification is not allowed if core-clr is enabled */
7523         if (!dont_verify && mini_assembly_can_skip_verification (cfg->domain, method)) {
7524                 dont_verify = TRUE;
7525                 dont_verify_stloc = TRUE;
7526         }
7527
7528         if (sig->is_inflated)
7529                 generic_context = mono_method_get_context (method);
7530         else if (generic_container)
7531                 generic_context = &generic_container->context;
7532         cfg->generic_context = generic_context;
7533
7534         if (!cfg->gshared)
7535                 g_assert (!sig->has_type_parameters);
7536
7537         if (sig->generic_param_count && method->wrapper_type == MONO_WRAPPER_NONE) {
7538                 g_assert (method->is_inflated);
7539                 g_assert (mono_method_get_context (method)->method_inst);
7540         }
7541         if (method->is_inflated && mono_method_get_context (method)->method_inst)
7542                 g_assert (sig->generic_param_count);
7543
7544         if (cfg->method == method) {
7545                 cfg->real_offset = 0;
7546         } else {
7547                 cfg->real_offset = inline_offset;
7548         }
7549
7550         cfg->cil_offset_to_bb = (MonoBasicBlock **)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoBasicBlock*) * header->code_size);
7551         cfg->cil_offset_to_bb_len = header->code_size;
7552
7553         cfg->current_method = method;
7554
7555         if (cfg->verbose_level > 2)
7556                 printf ("method to IR %s\n", mono_method_full_name (method, TRUE));
7557
7558         param_types = (MonoType **)mono_mempool_alloc (cfg->mempool, sizeof (MonoType*) * num_args);
7559         if (sig->hasthis)
7560                 param_types [0] = method->klass->valuetype?&method->klass->this_arg:&method->klass->byval_arg;
7561         for (n = 0; n < sig->param_count; ++n)
7562                 param_types [n + sig->hasthis] = sig->params [n];
7563         cfg->arg_types = param_types;
7564
7565         cfg->dont_inline = g_list_prepend (cfg->dont_inline, method);
7566         if (cfg->method == method) {
7567
7568                 if (cfg->prof_options & MONO_PROFILE_INS_COVERAGE)
7569                         cfg->coverage_info = mono_profiler_coverage_alloc (cfg->method, header->code_size);
7570
7571                 /* ENTRY BLOCK */
7572                 NEW_BBLOCK (cfg, start_bblock);
7573                 cfg->bb_entry = start_bblock;
7574                 start_bblock->cil_code = NULL;
7575                 start_bblock->cil_length = 0;
7576
7577                 /* EXIT BLOCK */
7578                 NEW_BBLOCK (cfg, end_bblock);
7579                 cfg->bb_exit = end_bblock;
7580                 end_bblock->cil_code = NULL;
7581                 end_bblock->cil_length = 0;
7582                 end_bblock->flags |= BB_INDIRECT_JUMP_TARGET;
7583                 g_assert (cfg->num_bblocks == 2);
7584
7585                 arg_array = cfg->args;
7586
7587                 if (header->num_clauses) {
7588                         cfg->spvars = g_hash_table_new (NULL, NULL);
7589                         cfg->exvars = g_hash_table_new (NULL, NULL);
7590                 }
7591                 /* handle exception clauses */
7592                 for (i = 0; i < header->num_clauses; ++i) {
7593                         MonoBasicBlock *try_bb;
7594                         MonoExceptionClause *clause = &header->clauses [i];
7595                         GET_BBLOCK (cfg, try_bb, ip + clause->try_offset);
7596
7597                         try_bb->real_offset = clause->try_offset;
7598                         try_bb->try_start = TRUE;
7599                         try_bb->region = ((i + 1) << 8) | clause->flags;
7600                         GET_BBLOCK (cfg, tblock, ip + clause->handler_offset);
7601                         tblock->real_offset = clause->handler_offset;
7602                         tblock->flags |= BB_EXCEPTION_HANDLER;
7603
7604                         /*
7605                          * Linking the try block with the EH block hinders inlining as we won't be able to 
7606                          * merge the bblocks from inlining and produce an artificial hole for no good reason.
7607                          */
7608                         if (COMPILE_LLVM (cfg))
7609                                 link_bblock (cfg, try_bb, tblock);
7610
7611                         if (*(ip + clause->handler_offset) == CEE_POP)
7612                                 tblock->flags |= BB_EXCEPTION_DEAD_OBJ;
7613
7614                         if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY ||
7615                             clause->flags == MONO_EXCEPTION_CLAUSE_FILTER ||
7616                             clause->flags == MONO_EXCEPTION_CLAUSE_FAULT) {
7617                                 MONO_INST_NEW (cfg, ins, OP_START_HANDLER);
7618                                 MONO_ADD_INS (tblock, ins);
7619
7620                                 if (seq_points && clause->flags != MONO_EXCEPTION_CLAUSE_FINALLY && clause->flags != MONO_EXCEPTION_CLAUSE_FILTER) {
7621                                         /* finally clauses already have a seq point */
7622                                         /* seq points for filter clauses are emitted below */
7623                                         NEW_SEQ_POINT (cfg, ins, clause->handler_offset, TRUE);
7624                                         MONO_ADD_INS (tblock, ins);
7625                                 }
7626
7627                                 /* todo: is a fault block unsafe to optimize? */
7628                                 if (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT)
7629                                         tblock->flags |= BB_EXCEPTION_UNSAFE;
7630                         }
7631
7632                         /*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);
7633                           while (p < end) {
7634                           printf ("%s", mono_disasm_code_one (NULL, method, p, &p));
7635                           }*/
7636                         /* catch and filter blocks get the exception object on the stack */
7637                         if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE ||
7638                             clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
7639
7640                                 /* mostly like handle_stack_args (), but just sets the input args */
7641                                 /* printf ("handling clause at IL_%04x\n", clause->handler_offset); */
7642                                 tblock->in_scount = 1;
7643                                 tblock->in_stack = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*));
7644                                 tblock->in_stack [0] = mono_create_exvar_for_offset (cfg, clause->handler_offset);
7645
7646                                 cfg->cbb = tblock;
7647
7648 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
7649                                 /* The EH code passes in the exception in a register to both JITted and LLVM compiled code */
7650                                 if (!cfg->compile_llvm) {
7651                                         MONO_INST_NEW (cfg, ins, OP_GET_EX_OBJ);
7652                                         ins->dreg = tblock->in_stack [0]->dreg;
7653                                         MONO_ADD_INS (tblock, ins);
7654                                 }
7655 #else
7656                                 MonoInst *dummy_use;
7657
7658                                 /* 
7659                                  * Add a dummy use for the exvar so its liveness info will be
7660                                  * correct.
7661                                  */
7662                                 EMIT_NEW_DUMMY_USE (cfg, dummy_use, tblock->in_stack [0]);
7663 #endif
7664
7665                                 if (seq_points && clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
7666                                         NEW_SEQ_POINT (cfg, ins, clause->handler_offset, TRUE);
7667                                         MONO_ADD_INS (tblock, ins);
7668                                 }
7669                                 
7670                                 if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
7671                                         GET_BBLOCK (cfg, tblock, ip + clause->data.filter_offset);
7672                                         tblock->flags |= BB_EXCEPTION_HANDLER;
7673                                         tblock->real_offset = clause->data.filter_offset;
7674                                         tblock->in_scount = 1;
7675                                         tblock->in_stack = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*));
7676                                         /* The filter block shares the exvar with the handler block */
7677                                         tblock->in_stack [0] = mono_create_exvar_for_offset (cfg, clause->handler_offset);
7678                                         MONO_INST_NEW (cfg, ins, OP_START_HANDLER);
7679                                         MONO_ADD_INS (tblock, ins);
7680                                 }
7681                         }
7682
7683                         if (clause->flags != MONO_EXCEPTION_CLAUSE_FILTER &&
7684                                         clause->data.catch_class &&
7685                                         cfg->gshared &&
7686                                         mono_class_check_context_used (clause->data.catch_class)) {
7687                                 /*
7688                                  * In shared generic code with catch
7689                                  * clauses containing type variables
7690                                  * the exception handling code has to
7691                                  * be able to get to the rgctx.
7692                                  * Therefore we have to make sure that
7693                                  * the vtable/mrgctx argument (for
7694                                  * static or generic methods) or the
7695                                  * "this" argument (for non-static
7696                                  * methods) are live.
7697                                  */
7698                                 if ((method->flags & METHOD_ATTRIBUTE_STATIC) ||
7699                                                 mini_method_get_context (method)->method_inst ||
7700                                                 method->klass->valuetype) {
7701                                         mono_get_vtable_var (cfg);
7702                                 } else {
7703                                         MonoInst *dummy_use;
7704
7705                                         EMIT_NEW_DUMMY_USE (cfg, dummy_use, arg_array [0]);
7706                                 }
7707                         }
7708                 }
7709         } else {
7710                 arg_array = (MonoInst **) alloca (sizeof (MonoInst *) * num_args);
7711                 cfg->cbb = start_bblock;
7712                 cfg->args = arg_array;
7713                 mono_save_args (cfg, sig, inline_args);
7714         }
7715
7716         /* FIRST CODE BLOCK */
7717         NEW_BBLOCK (cfg, tblock);
7718         tblock->cil_code = ip;
7719         cfg->cbb = tblock;
7720         cfg->ip = ip;
7721
7722         ADD_BBLOCK (cfg, tblock);
7723
7724         if (cfg->method == method) {
7725                 breakpoint_id = mono_debugger_method_has_breakpoint (method);
7726                 if (breakpoint_id) {
7727                         MONO_INST_NEW (cfg, ins, OP_BREAK);
7728                         MONO_ADD_INS (cfg->cbb, ins);
7729                 }
7730         }
7731
7732         /* we use a separate basic block for the initialization code */
7733         NEW_BBLOCK (cfg, init_localsbb);
7734         if (cfg->method == method)
7735                 cfg->bb_init = init_localsbb;
7736         init_localsbb->real_offset = cfg->real_offset;
7737         start_bblock->next_bb = init_localsbb;
7738         init_localsbb->next_bb = cfg->cbb;
7739         link_bblock (cfg, start_bblock, init_localsbb);
7740         link_bblock (cfg, init_localsbb, cfg->cbb);
7741                 
7742         cfg->cbb = init_localsbb;
7743
7744         if (cfg->gsharedvt && cfg->method == method) {
7745                 MonoGSharedVtMethodInfo *info;
7746                 MonoInst *var, *locals_var;
7747                 int dreg;
7748
7749                 info = (MonoGSharedVtMethodInfo *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoGSharedVtMethodInfo));
7750                 info->method = cfg->method;
7751                 info->count_entries = 16;
7752                 info->entries = (MonoRuntimeGenericContextInfoTemplate *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoRuntimeGenericContextInfoTemplate) * info->count_entries);
7753                 cfg->gsharedvt_info = info;
7754
7755                 var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
7756                 /* prevent it from being register allocated */
7757                 //var->flags |= MONO_INST_VOLATILE;
7758                 cfg->gsharedvt_info_var = var;
7759
7760                 ins = emit_get_rgctx_gsharedvt_method (cfg, mini_method_check_context_used (cfg, method), method, info);
7761                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, var->dreg, ins->dreg);
7762
7763                 /* Allocate locals */
7764                 locals_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
7765                 /* prevent it from being register allocated */
7766                 //locals_var->flags |= MONO_INST_VOLATILE;
7767                 cfg->gsharedvt_locals_var = locals_var;
7768
7769                 dreg = alloc_ireg (cfg);
7770                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, dreg, var->dreg, MONO_STRUCT_OFFSET (MonoGSharedVtMethodRuntimeInfo, locals_size));
7771
7772                 MONO_INST_NEW (cfg, ins, OP_LOCALLOC);
7773                 ins->dreg = locals_var->dreg;
7774                 ins->sreg1 = dreg;
7775                 MONO_ADD_INS (cfg->cbb, ins);
7776                 cfg->gsharedvt_locals_var_ins = ins;
7777                 
7778                 cfg->flags |= MONO_CFG_HAS_ALLOCA;
7779                 /*
7780                 if (init_locals)
7781                         ins->flags |= MONO_INST_INIT;
7782                 */
7783         }
7784
7785         if (mono_security_core_clr_enabled ()) {
7786                 /* check if this is native code, e.g. an icall or a p/invoke */
7787                 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
7788                         MonoMethod *wrapped = mono_marshal_method_from_wrapper (method);
7789                         if (wrapped) {
7790                                 gboolean pinvk = (wrapped->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL);
7791                                 gboolean icall = (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL);
7792
7793                                 /* if this ia a native call then it can only be JITted from platform code */
7794                                 if ((icall || pinvk) && method->klass && method->klass->image) {
7795                                         if (!mono_security_core_clr_is_platform_image (method->klass->image)) {
7796                                                 MonoException *ex = icall ? mono_get_exception_security () : 
7797                                                         mono_get_exception_method_access ();
7798                                                 emit_throw_exception (cfg, ex);
7799                                         }
7800                                 }
7801                         }
7802                 }
7803         }
7804
7805         CHECK_CFG_EXCEPTION;
7806
7807         if (header->code_size == 0)
7808                 UNVERIFIED;
7809
7810         if (get_basic_blocks (cfg, header, cfg->real_offset, ip, end, &err_pos)) {
7811                 ip = err_pos;
7812                 UNVERIFIED;
7813         }
7814
7815         if (cfg->method == method)
7816                 mono_debug_init_method (cfg, cfg->cbb, breakpoint_id);
7817
7818         for (n = 0; n < header->num_locals; ++n) {
7819                 if (header->locals [n]->type == MONO_TYPE_VOID && !header->locals [n]->byref)
7820                         UNVERIFIED;
7821         }
7822         class_inits = NULL;
7823
7824         /* We force the vtable variable here for all shared methods
7825            for the possibility that they might show up in a stack
7826            trace where their exact instantiation is needed. */
7827         if (cfg->gshared && method == cfg->method) {
7828                 if ((method->flags & METHOD_ATTRIBUTE_STATIC) ||
7829                                 mini_method_get_context (method)->method_inst ||
7830                                 method->klass->valuetype) {
7831                         mono_get_vtable_var (cfg);
7832                 } else {
7833                         /* FIXME: Is there a better way to do this?
7834                            We need the variable live for the duration
7835                            of the whole method. */
7836                         cfg->args [0]->flags |= MONO_INST_VOLATILE;
7837                 }
7838         }
7839
7840         /* add a check for this != NULL to inlined methods */
7841         if (is_virtual_call) {
7842                 MonoInst *arg_ins;
7843
7844                 NEW_ARGLOAD (cfg, arg_ins, 0);
7845                 MONO_ADD_INS (cfg->cbb, arg_ins);
7846                 MONO_EMIT_NEW_CHECK_THIS (cfg, arg_ins->dreg);
7847         }
7848
7849         skip_dead_blocks = !dont_verify;
7850         if (skip_dead_blocks) {
7851                 original_bb = bb = mono_basic_block_split (method, &cfg->error, header);
7852                 CHECK_CFG_ERROR;
7853                 g_assert (bb);
7854         }
7855
7856         /* we use a spare stack slot in SWITCH and NEWOBJ and others */
7857         stack_start = sp = (MonoInst **)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst*) * (header->max_stack + 1));
7858
7859         ins_flag = 0;
7860         start_new_bblock = 0;
7861         while (ip < end) {
7862                 if (cfg->method == method)
7863                         cfg->real_offset = ip - header->code;
7864                 else
7865                         cfg->real_offset = inline_offset;
7866                 cfg->ip = ip;
7867
7868                 context_used = 0;
7869
7870                 if (start_new_bblock) {
7871                         cfg->cbb->cil_length = ip - cfg->cbb->cil_code;
7872                         if (start_new_bblock == 2) {
7873                                 g_assert (ip == tblock->cil_code);
7874                         } else {
7875                                 GET_BBLOCK (cfg, tblock, ip);
7876                         }
7877                         cfg->cbb->next_bb = tblock;
7878                         cfg->cbb = tblock;
7879                         start_new_bblock = 0;
7880                         for (i = 0; i < cfg->cbb->in_scount; ++i) {
7881                                 if (cfg->verbose_level > 3)
7882                                         printf ("loading %d from temp %d\n", i, (int)cfg->cbb->in_stack [i]->inst_c0);
7883                                 EMIT_NEW_TEMPLOAD (cfg, ins, cfg->cbb->in_stack [i]->inst_c0);
7884                                 *sp++ = ins;
7885                         }
7886                         if (class_inits)
7887                                 g_slist_free (class_inits);
7888                         class_inits = NULL;
7889                 } else {
7890                         if ((tblock = cfg->cil_offset_to_bb [ip - cfg->cil_start]) && (tblock != cfg->cbb)) {
7891                                 link_bblock (cfg, cfg->cbb, tblock);
7892                                 if (sp != stack_start) {
7893                                         handle_stack_args (cfg, stack_start, sp - stack_start);
7894                                         sp = stack_start;
7895                                         CHECK_UNVERIFIABLE (cfg);
7896                                 }
7897                                 cfg->cbb->next_bb = tblock;
7898                                 cfg->cbb = tblock;
7899                                 for (i = 0; i < cfg->cbb->in_scount; ++i) {
7900                                         if (cfg->verbose_level > 3)
7901                                                 printf ("loading %d from temp %d\n", i, (int)cfg->cbb->in_stack [i]->inst_c0);
7902                                         EMIT_NEW_TEMPLOAD (cfg, ins, cfg->cbb->in_stack [i]->inst_c0);
7903                                         *sp++ = ins;
7904                                 }
7905                                 g_slist_free (class_inits);
7906                                 class_inits = NULL;
7907                         }
7908                 }
7909
7910                 if (skip_dead_blocks) {
7911                         int ip_offset = ip - header->code;
7912
7913                         if (ip_offset == bb->end)
7914                                 bb = bb->next;
7915
7916                         if (bb->dead) {
7917                                 int op_size = mono_opcode_size (ip, end);
7918                                 g_assert (op_size > 0); /*The BB formation pass must catch all bad ops*/
7919
7920                                 if (cfg->verbose_level > 3) printf ("SKIPPING DEAD OP at %x\n", ip_offset);
7921
7922                                 if (ip_offset + op_size == bb->end) {
7923                                         MONO_INST_NEW (cfg, ins, OP_NOP);
7924                                         MONO_ADD_INS (cfg->cbb, ins);
7925                                         start_new_bblock = 1;
7926                                 }
7927
7928                                 ip += op_size;
7929                                 continue;
7930                         }
7931                 }
7932                 /*
7933                  * Sequence points are points where the debugger can place a breakpoint.
7934                  * Currently, we generate these automatically at points where the IL
7935                  * stack is empty.
7936                  */
7937                 if (seq_points && ((!sym_seq_points && (sp == stack_start)) || (sym_seq_points && mono_bitset_test_fast (seq_point_locs, ip - header->code)))) {
7938                         /*
7939                          * Make methods interruptable at the beginning, and at the targets of
7940                          * backward branches.
7941                          * Also, do this at the start of every bblock in methods with clauses too,
7942                          * to be able to handle instructions with inprecise control flow like
7943                          * throw/endfinally.
7944                          * Backward branches are handled at the end of method-to-ir ().
7945                          */
7946                         gboolean intr_loc = ip == header->code || (!cfg->cbb->last_ins && cfg->header->num_clauses);
7947                         gboolean sym_seq_point = sym_seq_points && mono_bitset_test_fast (seq_point_locs, ip - header->code);
7948
7949                         /* Avoid sequence points on empty IL like .volatile */
7950                         // FIXME: Enable this
7951                         //if (!(cfg->cbb->last_ins && cfg->cbb->last_ins->opcode == OP_SEQ_POINT)) {
7952                         NEW_SEQ_POINT (cfg, ins, ip - header->code, intr_loc);
7953                         if ((sp != stack_start) && !sym_seq_point)
7954                                 ins->flags |= MONO_INST_NONEMPTY_STACK;
7955                         MONO_ADD_INS (cfg->cbb, ins);
7956
7957                         if (sym_seq_points)
7958                                 mono_bitset_set_fast (seq_point_set_locs, ip - header->code);
7959                 }
7960
7961                 cfg->cbb->real_offset = cfg->real_offset;
7962
7963                 if ((cfg->method == method) && cfg->coverage_info) {
7964                         guint32 cil_offset = ip - header->code;
7965                         cfg->coverage_info->data [cil_offset].cil_code = ip;
7966
7967                         /* TODO: Use an increment here */
7968 #if defined(TARGET_X86)
7969                         MONO_INST_NEW (cfg, ins, OP_STORE_MEM_IMM);
7970                         ins->inst_p0 = &(cfg->coverage_info->data [cil_offset].count);
7971                         ins->inst_imm = 1;
7972                         MONO_ADD_INS (cfg->cbb, ins);
7973 #else
7974                         EMIT_NEW_PCONST (cfg, ins, &(cfg->coverage_info->data [cil_offset].count));
7975                         MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STORE_MEMBASE_IMM, ins->dreg, 0, 1);
7976 #endif
7977                 }
7978
7979                 if (cfg->verbose_level > 3)
7980                         printf ("converting (in B%d: stack: %d) %s", cfg->cbb->block_num, (int)(sp - stack_start), mono_disasm_code_one (NULL, method, ip, NULL));
7981
7982                 switch (*ip) {
7983                 case CEE_NOP:
7984                         if (seq_points && !sym_seq_points && sp != stack_start) {
7985                                 /*
7986                                  * The C# compiler uses these nops to notify the JIT that it should
7987                                  * insert seq points.
7988                                  */
7989                                 NEW_SEQ_POINT (cfg, ins, ip - header->code, FALSE);
7990                                 MONO_ADD_INS (cfg->cbb, ins);
7991                         }
7992                         if (cfg->keep_cil_nops)
7993                                 MONO_INST_NEW (cfg, ins, OP_HARD_NOP);
7994                         else
7995                                 MONO_INST_NEW (cfg, ins, OP_NOP);
7996                         ip++;
7997                         MONO_ADD_INS (cfg->cbb, ins);
7998                         break;
7999                 case CEE_BREAK:
8000                         if (should_insert_brekpoint (cfg->method)) {
8001                                 ins = mono_emit_jit_icall (cfg, mono_debugger_agent_user_break, NULL);
8002                         } else {
8003                                 MONO_INST_NEW (cfg, ins, OP_NOP);
8004                         }
8005                         ip++;
8006                         MONO_ADD_INS (cfg->cbb, ins);
8007                         break;
8008                 case CEE_LDARG_0:
8009                 case CEE_LDARG_1:
8010                 case CEE_LDARG_2:
8011                 case CEE_LDARG_3:
8012                         CHECK_STACK_OVF (1);
8013                         n = (*ip)-CEE_LDARG_0;
8014                         CHECK_ARG (n);
8015                         EMIT_NEW_ARGLOAD (cfg, ins, n);
8016                         ip++;
8017                         *sp++ = ins;
8018                         break;
8019                 case CEE_LDLOC_0:
8020                 case CEE_LDLOC_1:
8021                 case CEE_LDLOC_2:
8022                 case CEE_LDLOC_3:
8023                         CHECK_STACK_OVF (1);
8024                         n = (*ip)-CEE_LDLOC_0;
8025                         CHECK_LOCAL (n);
8026                         EMIT_NEW_LOCLOAD (cfg, ins, n);
8027                         ip++;
8028                         *sp++ = ins;
8029                         break;
8030                 case CEE_STLOC_0:
8031                 case CEE_STLOC_1:
8032                 case CEE_STLOC_2:
8033                 case CEE_STLOC_3: {
8034                         CHECK_STACK (1);
8035                         n = (*ip)-CEE_STLOC_0;
8036                         CHECK_LOCAL (n);
8037                         --sp;
8038                         if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [n], *sp))
8039                                 UNVERIFIED;
8040                         emit_stloc_ir (cfg, sp, header, n);
8041                         ++ip;
8042                         inline_costs += 1;
8043                         break;
8044                         }
8045                 case CEE_LDARG_S:
8046                         CHECK_OPSIZE (2);
8047                         CHECK_STACK_OVF (1);
8048                         n = ip [1];
8049                         CHECK_ARG (n);
8050                         EMIT_NEW_ARGLOAD (cfg, ins, n);
8051                         *sp++ = ins;
8052                         ip += 2;
8053                         break;
8054                 case CEE_LDARGA_S:
8055                         CHECK_OPSIZE (2);
8056                         CHECK_STACK_OVF (1);
8057                         n = ip [1];
8058                         CHECK_ARG (n);
8059                         NEW_ARGLOADA (cfg, ins, n);
8060                         MONO_ADD_INS (cfg->cbb, ins);
8061                         *sp++ = ins;
8062                         ip += 2;
8063                         break;
8064                 case CEE_STARG_S:
8065                         CHECK_OPSIZE (2);
8066                         CHECK_STACK (1);
8067                         --sp;
8068                         n = ip [1];
8069                         CHECK_ARG (n);
8070                         if (!dont_verify_stloc && target_type_is_incompatible (cfg, param_types [ip [1]], *sp))
8071                                 UNVERIFIED;
8072                         EMIT_NEW_ARGSTORE (cfg, ins, n, *sp);
8073                         ip += 2;
8074                         break;
8075                 case CEE_LDLOC_S:
8076                         CHECK_OPSIZE (2);
8077                         CHECK_STACK_OVF (1);
8078                         n = ip [1];
8079                         CHECK_LOCAL (n);
8080                         EMIT_NEW_LOCLOAD (cfg, ins, n);
8081                         *sp++ = ins;
8082                         ip += 2;
8083                         break;
8084                 case CEE_LDLOCA_S: {
8085                         unsigned char *tmp_ip;
8086                         CHECK_OPSIZE (2);
8087                         CHECK_STACK_OVF (1);
8088                         CHECK_LOCAL (ip [1]);
8089
8090                         if ((tmp_ip = emit_optimized_ldloca_ir (cfg, ip, end, 1))) {
8091                                 ip = tmp_ip;
8092                                 inline_costs += 1;
8093                                 break;
8094                         }
8095
8096                         EMIT_NEW_LOCLOADA (cfg, ins, ip [1]);
8097                         *sp++ = ins;
8098                         ip += 2;
8099                         break;
8100                 }
8101                 case CEE_STLOC_S:
8102                         CHECK_OPSIZE (2);
8103                         CHECK_STACK (1);
8104                         --sp;
8105                         CHECK_LOCAL (ip [1]);
8106                         if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [ip [1]], *sp))
8107                                 UNVERIFIED;
8108                         emit_stloc_ir (cfg, sp, header, ip [1]);
8109                         ip += 2;
8110                         inline_costs += 1;
8111                         break;
8112                 case CEE_LDNULL:
8113                         CHECK_STACK_OVF (1);
8114                         EMIT_NEW_PCONST (cfg, ins, NULL);
8115                         ins->type = STACK_OBJ;
8116                         ++ip;
8117                         *sp++ = ins;
8118                         break;
8119                 case CEE_LDC_I4_M1:
8120                         CHECK_STACK_OVF (1);
8121                         EMIT_NEW_ICONST (cfg, ins, -1);
8122                         ++ip;
8123                         *sp++ = ins;
8124                         break;
8125                 case CEE_LDC_I4_0:
8126                 case CEE_LDC_I4_1:
8127                 case CEE_LDC_I4_2:
8128                 case CEE_LDC_I4_3:
8129                 case CEE_LDC_I4_4:
8130                 case CEE_LDC_I4_5:
8131                 case CEE_LDC_I4_6:
8132                 case CEE_LDC_I4_7:
8133                 case CEE_LDC_I4_8:
8134                         CHECK_STACK_OVF (1);
8135                         EMIT_NEW_ICONST (cfg, ins, (*ip) - CEE_LDC_I4_0);
8136                         ++ip;
8137                         *sp++ = ins;
8138                         break;
8139                 case CEE_LDC_I4_S:
8140                         CHECK_OPSIZE (2);
8141                         CHECK_STACK_OVF (1);
8142                         ++ip;
8143                         EMIT_NEW_ICONST (cfg, ins, *((signed char*)ip));
8144                         ++ip;
8145                         *sp++ = ins;
8146                         break;
8147                 case CEE_LDC_I4:
8148                         CHECK_OPSIZE (5);
8149                         CHECK_STACK_OVF (1);
8150                         EMIT_NEW_ICONST (cfg, ins, (gint32)read32 (ip + 1));
8151                         ip += 5;
8152                         *sp++ = ins;
8153                         break;
8154                 case CEE_LDC_I8:
8155                         CHECK_OPSIZE (9);
8156                         CHECK_STACK_OVF (1);
8157                         MONO_INST_NEW (cfg, ins, OP_I8CONST);
8158                         ins->type = STACK_I8;
8159                         ins->dreg = alloc_dreg (cfg, STACK_I8);
8160                         ++ip;
8161                         ins->inst_l = (gint64)read64 (ip);
8162                         MONO_ADD_INS (cfg->cbb, ins);
8163                         ip += 8;
8164                         *sp++ = ins;
8165                         break;
8166                 case CEE_LDC_R4: {
8167                         float *f;
8168                         gboolean use_aotconst = FALSE;
8169
8170 #ifdef TARGET_POWERPC
8171                         /* FIXME: Clean this up */
8172                         if (cfg->compile_aot)
8173                                 use_aotconst = TRUE;
8174 #endif
8175
8176                         /* FIXME: we should really allocate this only late in the compilation process */
8177                         f = (float *)mono_domain_alloc (cfg->domain, sizeof (float));
8178                         CHECK_OPSIZE (5);
8179                         CHECK_STACK_OVF (1);
8180
8181                         if (use_aotconst) {
8182                                 MonoInst *cons;
8183                                 int dreg;
8184
8185                                 EMIT_NEW_AOTCONST (cfg, cons, MONO_PATCH_INFO_R4, f);
8186
8187                                 dreg = alloc_freg (cfg);
8188                                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADR4_MEMBASE, dreg, cons->dreg, 0);
8189                                 ins->type = cfg->r4_stack_type;
8190                         } else {
8191                                 MONO_INST_NEW (cfg, ins, OP_R4CONST);
8192                                 ins->type = cfg->r4_stack_type;
8193                                 ins->dreg = alloc_dreg (cfg, STACK_R8);
8194                                 ins->inst_p0 = f;
8195                                 MONO_ADD_INS (cfg->cbb, ins);
8196                         }
8197                         ++ip;
8198                         readr4 (ip, f);
8199                         ip += 4;
8200                         *sp++ = ins;                    
8201                         break;
8202                 }
8203                 case CEE_LDC_R8: {
8204                         double *d;
8205                         gboolean use_aotconst = FALSE;
8206
8207 #ifdef TARGET_POWERPC
8208                         /* FIXME: Clean this up */
8209                         if (cfg->compile_aot)
8210                                 use_aotconst = TRUE;
8211 #endif
8212
8213                         /* FIXME: we should really allocate this only late in the compilation process */
8214                         d = (double *)mono_domain_alloc (cfg->domain, sizeof (double));
8215                         CHECK_OPSIZE (9);
8216                         CHECK_STACK_OVF (1);
8217
8218                         if (use_aotconst) {
8219                                 MonoInst *cons;
8220                                 int dreg;
8221
8222                                 EMIT_NEW_AOTCONST (cfg, cons, MONO_PATCH_INFO_R8, d);
8223
8224                                 dreg = alloc_freg (cfg);
8225                                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADR8_MEMBASE, dreg, cons->dreg, 0);
8226                                 ins->type = STACK_R8;
8227                         } else {
8228                                 MONO_INST_NEW (cfg, ins, OP_R8CONST);
8229                                 ins->type = STACK_R8;
8230                                 ins->dreg = alloc_dreg (cfg, STACK_R8);
8231                                 ins->inst_p0 = d;
8232                                 MONO_ADD_INS (cfg->cbb, ins);
8233                         }
8234                         ++ip;
8235                         readr8 (ip, d);
8236                         ip += 8;
8237                         *sp++ = ins;
8238                         break;
8239                 }
8240                 case CEE_DUP: {
8241                         MonoInst *temp, *store;
8242                         CHECK_STACK (1);
8243                         CHECK_STACK_OVF (1);
8244                         sp--;
8245                         ins = *sp;
8246
8247                         temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
8248                         EMIT_NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
8249
8250                         EMIT_NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
8251                         *sp++ = ins;
8252
8253                         EMIT_NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
8254                         *sp++ = ins;
8255
8256                         ++ip;
8257                         inline_costs += 2;
8258                         break;
8259                 }
8260                 case CEE_POP:
8261                         CHECK_STACK (1);
8262                         ip++;
8263                         --sp;
8264
8265 #ifdef TARGET_X86
8266                         if (sp [0]->type == STACK_R8)
8267                                 /* we need to pop the value from the x86 FP stack */
8268                                 MONO_EMIT_NEW_UNALU (cfg, OP_X86_FPOP, -1, sp [0]->dreg);
8269 #endif
8270                         break;
8271                 case CEE_JMP: {
8272                         MonoCallInst *call;
8273                         MonoMethodSignature *fsig;
8274                         int i, n;
8275
8276                         INLINE_FAILURE ("jmp");
8277                         GSHAREDVT_FAILURE (*ip);
8278
8279                         CHECK_OPSIZE (5);
8280                         if (stack_start != sp)
8281                                 UNVERIFIED;
8282                         token = read32 (ip + 1);
8283                         /* FIXME: check the signature matches */
8284                         cmethod = mini_get_method (cfg, method, token, NULL, generic_context);
8285                         CHECK_CFG_ERROR;
8286  
8287                         if (cfg->gshared && mono_method_check_context_used (cmethod))
8288                                 GENERIC_SHARING_FAILURE (CEE_JMP);
8289
8290                         emit_instrumentation_call (cfg, mono_profiler_method_leave);
8291
8292                         fsig = mono_method_signature (cmethod);
8293                         n = fsig->param_count + fsig->hasthis;
8294                         if (cfg->llvm_only) {
8295                                 MonoInst **args;
8296
8297                                 args = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * n);
8298                                 for (i = 0; i < n; ++i)
8299                                         EMIT_NEW_ARGLOAD (cfg, args [i], i);
8300                                 ins = mono_emit_method_call_full (cfg, cmethod, fsig, TRUE, args, NULL, NULL, NULL);
8301                                 /*
8302                                  * The code in mono-basic-block.c treats the rest of the code as dead, but we
8303                                  * have to emit a normal return since llvm expects it.
8304                                  */
8305                                 if (cfg->ret)
8306                                         emit_setret (cfg, ins);
8307                                 MONO_INST_NEW (cfg, ins, OP_BR);
8308                                 ins->inst_target_bb = end_bblock;
8309                                 MONO_ADD_INS (cfg->cbb, ins);
8310                                 link_bblock (cfg, cfg->cbb, end_bblock);
8311                                 ip += 5;
8312                                 break;
8313                         } else if (cfg->backend->have_op_tail_call) {
8314                                 /* Handle tail calls similarly to calls */
8315                                 DISABLE_AOT (cfg);
8316
8317                                 MONO_INST_NEW_CALL (cfg, call, OP_TAILCALL);
8318                                 call->method = cmethod;
8319                                 call->tail_call = TRUE;
8320                                 call->signature = mono_method_signature (cmethod);
8321                                 call->args = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * n);
8322                                 call->inst.inst_p0 = cmethod;
8323                                 for (i = 0; i < n; ++i)
8324                                         EMIT_NEW_ARGLOAD (cfg, call->args [i], i);
8325
8326                                 if (mini_type_is_vtype (mini_get_underlying_type (call->signature->ret)))
8327                                         call->vret_var = cfg->vret_addr;
8328
8329                                 mono_arch_emit_call (cfg, call);
8330                                 cfg->param_area = MAX(cfg->param_area, call->stack_usage);
8331                                 MONO_ADD_INS (cfg->cbb, (MonoInst*)call);
8332                         } else {
8333                                 for (i = 0; i < num_args; ++i)
8334                                         /* Prevent arguments from being optimized away */
8335                                         arg_array [i]->flags |= MONO_INST_VOLATILE;
8336
8337                                 MONO_INST_NEW_CALL (cfg, call, OP_JMP);
8338                                 ins = (MonoInst*)call;
8339                                 ins->inst_p0 = cmethod;
8340                                 MONO_ADD_INS (cfg->cbb, ins);
8341                         }
8342
8343                         ip += 5;
8344                         start_new_bblock = 1;
8345                         break;
8346                 }
8347                 case CEE_CALLI: {
8348                         MonoInst *addr;
8349                         MonoMethodSignature *fsig;
8350
8351                         CHECK_OPSIZE (5);
8352                         token = read32 (ip + 1);
8353
8354                         ins = NULL;
8355
8356                         //GSHAREDVT_FAILURE (*ip);
8357                         cmethod = NULL;
8358                         CHECK_STACK (1);
8359                         --sp;
8360                         addr = *sp;
8361                         fsig = mini_get_signature (method, token, generic_context, &cfg->error);
8362                         CHECK_CFG_ERROR;
8363
8364                         if (method->dynamic && fsig->pinvoke) {
8365                                 MonoInst *args [3];
8366
8367                                 /*
8368                                  * This is a call through a function pointer using a pinvoke
8369                                  * signature. Have to create a wrapper and call that instead.
8370                                  * FIXME: This is very slow, need to create a wrapper at JIT time
8371                                  * instead based on the signature.
8372                                  */
8373                                 EMIT_NEW_IMAGECONST (cfg, args [0], method->klass->image);
8374                                 EMIT_NEW_PCONST (cfg, args [1], fsig);
8375                                 args [2] = addr;
8376                                 addr = mono_emit_jit_icall (cfg, mono_get_native_calli_wrapper, args);
8377                         }
8378
8379                         n = fsig->param_count + fsig->hasthis;
8380
8381                         CHECK_STACK (n);
8382
8383                         //g_assert (!virtual_ || fsig->hasthis);
8384
8385                         sp -= n;
8386
8387                         inline_costs += 10 * num_calls++;
8388
8389                         /*
8390                          * Making generic calls out of gsharedvt methods.
8391                          * This needs to be used for all generic calls, not just ones with a gsharedvt signature, to avoid
8392                          * patching gshared method addresses into a gsharedvt method.
8393                          */
8394                         if (cfg->gsharedvt && mini_is_gsharedvt_signature (fsig)) {
8395                                 /*
8396                                  * We pass the address to the gsharedvt trampoline in the rgctx reg
8397                                  */
8398                                 MonoInst *callee = addr;
8399
8400                                 if (method->wrapper_type != MONO_WRAPPER_DELEGATE_INVOKE)
8401                                         /* Not tested */
8402                                         GSHAREDVT_FAILURE (*ip);
8403
8404                                 if (cfg->llvm_only)
8405                                         // FIXME:
8406                                         GSHAREDVT_FAILURE (*ip);
8407
8408                                 addr = emit_get_rgctx_sig (cfg, context_used,
8409                                                                                           fsig, MONO_RGCTX_INFO_SIG_GSHAREDVT_OUT_TRAMPOLINE_CALLI);
8410                                 ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, NULL, callee);
8411                                 goto calli_end;
8412                         }
8413
8414                         /* Prevent inlining of methods with indirect calls */
8415                         INLINE_FAILURE ("indirect call");
8416
8417                         if (addr->opcode == OP_PCONST || addr->opcode == OP_AOTCONST || addr->opcode == OP_GOT_ENTRY) {
8418                                 MonoJumpInfoType info_type;
8419                                 gpointer info_data;
8420
8421                                 /*
8422                                  * Instead of emitting an indirect call, emit a direct call
8423                                  * with the contents of the aotconst as the patch info.
8424                                  */
8425                                 if (addr->opcode == OP_PCONST || addr->opcode == OP_AOTCONST) {
8426                                         info_type = (MonoJumpInfoType)addr->inst_c1;
8427                                         info_data = addr->inst_p0;
8428                                 } else {
8429                                         info_type = (MonoJumpInfoType)addr->inst_right->inst_c1;
8430                                         info_data = addr->inst_right->inst_left;
8431                                 }
8432
8433                                 if (info_type == MONO_PATCH_INFO_ICALL_ADDR) {
8434                                         ins = (MonoInst*)mono_emit_abs_call (cfg, MONO_PATCH_INFO_ICALL_ADDR_CALL, info_data, fsig, sp);
8435                                         NULLIFY_INS (addr);
8436                                         goto calli_end;
8437                                 } else if (info_type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
8438                                         ins = (MonoInst*)mono_emit_abs_call (cfg, info_type, info_data, fsig, sp);
8439                                         NULLIFY_INS (addr);
8440                                         goto calli_end;
8441                                 }
8442                         }
8443                         ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
8444
8445                         calli_end:
8446
8447                         /* End of call, INS should contain the result of the call, if any */
8448
8449                         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
8450                                 g_assert (ins);
8451                                 *sp++ = mono_emit_widen_call_res (cfg, ins, fsig);
8452                         }
8453
8454                         CHECK_CFG_EXCEPTION;
8455
8456                         ip += 5;
8457                         ins_flag = 0;
8458                         constrained_class = NULL;
8459                         break;
8460                 }
8461                 case CEE_CALL:
8462                 case CEE_CALLVIRT: {
8463                         MonoInst *addr = NULL;
8464                         MonoMethodSignature *fsig = NULL;
8465                         int array_rank = 0;
8466                         int virtual_ = *ip == CEE_CALLVIRT;
8467                         gboolean pass_imt_from_rgctx = FALSE;
8468                         MonoInst *imt_arg = NULL;
8469                         MonoInst *keep_this_alive = NULL;
8470                         gboolean pass_vtable = FALSE;
8471                         gboolean pass_mrgctx = FALSE;
8472                         MonoInst *vtable_arg = NULL;
8473                         gboolean check_this = FALSE;
8474                         gboolean supported_tail_call = FALSE;
8475                         gboolean tail_call = FALSE;
8476                         gboolean need_seq_point = FALSE;
8477                         guint32 call_opcode = *ip;
8478                         gboolean emit_widen = TRUE;
8479                         gboolean push_res = TRUE;
8480                         gboolean skip_ret = FALSE;
8481                         gboolean delegate_invoke = FALSE;
8482                         gboolean direct_icall = FALSE;
8483                         gboolean constrained_partial_call = FALSE;
8484                         MonoMethod *cil_method;
8485
8486                         CHECK_OPSIZE (5);
8487                         token = read32 (ip + 1);
8488
8489                         ins = NULL;
8490
8491                         cmethod = mini_get_method (cfg, method, token, NULL, generic_context);
8492                         CHECK_CFG_ERROR;
8493
8494                         cil_method = cmethod;
8495                                 
8496                         if (constrained_class) {
8497                                 if ((constrained_class->byval_arg.type == MONO_TYPE_VAR || constrained_class->byval_arg.type == MONO_TYPE_MVAR) && cfg->gshared) {
8498                                         if (!mini_is_gsharedvt_klass (constrained_class)) {
8499                                                 g_assert (!cmethod->klass->valuetype);
8500                                                 if (!mini_type_is_reference (&constrained_class->byval_arg))
8501                                                         constrained_partial_call = TRUE;
8502                                         }
8503                                 }
8504
8505                                 if (method->wrapper_type != MONO_WRAPPER_NONE) {
8506                                         if (cfg->verbose_level > 2)
8507                                                 printf ("DM Constrained call to %s\n", mono_type_get_full_name (constrained_class));
8508                                         if (!((constrained_class->byval_arg.type == MONO_TYPE_VAR ||
8509                                                    constrained_class->byval_arg.type == MONO_TYPE_MVAR) &&
8510                                                   cfg->gshared)) {
8511                                                 cmethod = mono_get_method_constrained_with_method (image, cil_method, constrained_class, generic_context, &cfg->error);
8512                                                 CHECK_CFG_ERROR;
8513                                         }
8514                                 } else {
8515                                         if (cfg->verbose_level > 2)
8516                                                 printf ("Constrained call to %s\n", mono_type_get_full_name (constrained_class));
8517
8518                                         if ((constrained_class->byval_arg.type == MONO_TYPE_VAR || constrained_class->byval_arg.type == MONO_TYPE_MVAR) && cfg->gshared) {
8519                                                 /* 
8520                                                  * This is needed since get_method_constrained can't find 
8521                                                  * the method in klass representing a type var.
8522                                                  * The type var is guaranteed to be a reference type in this
8523                                                  * case.
8524                                                  */
8525                                                 if (!mini_is_gsharedvt_klass (constrained_class))
8526                                                         g_assert (!cmethod->klass->valuetype);
8527                                         } else {
8528                                                 cmethod = mono_get_method_constrained_checked (image, token, constrained_class, generic_context, &cil_method, &cfg->error);
8529                                                 CHECK_CFG_ERROR;
8530                                         }
8531                                 }
8532
8533                                 if (constrained_class->enumtype && !strcmp (cmethod->name, "GetHashCode")) {
8534                                         /* Use the corresponding method from the base type to avoid boxing */
8535                                         MonoType *base_type = mono_class_enum_basetype (constrained_class);
8536                                         g_assert (base_type);
8537                                         constrained_class = mono_class_from_mono_type (base_type);
8538                                         cmethod = mono_class_get_method_from_name (constrained_class, cmethod->name, 0);
8539                                         g_assert (cmethod);
8540                                 }
8541                         }
8542                                         
8543                         if (!dont_verify && !cfg->skip_visibility) {
8544                                 MonoMethod *target_method = cil_method;
8545                                 if (method->is_inflated) {
8546                                         target_method = mini_get_method_allow_open (method, token, NULL, &(mono_method_get_generic_container (method_definition)->context), &cfg->error);
8547                                         CHECK_CFG_ERROR;
8548                                 }
8549                                 if (!mono_method_can_access_method (method_definition, target_method) &&
8550                                         !mono_method_can_access_method (method, cil_method))
8551                                         emit_method_access_failure (cfg, method, cil_method);
8552                         }
8553
8554                         if (mono_security_core_clr_enabled ())
8555                                 ensure_method_is_allowed_to_call_method (cfg, method, cil_method);
8556
8557                         if (!virtual_ && (cmethod->flags & METHOD_ATTRIBUTE_ABSTRACT))
8558                                 /* MS.NET seems to silently convert this to a callvirt */
8559                                 virtual_ = 1;
8560
8561                         {
8562                                 /*
8563                                  * MS.NET accepts non virtual calls to virtual final methods of transparent proxy classes and
8564                                  * converts to a callvirt.
8565                                  *
8566                                  * tests/bug-515884.il is an example of this behavior
8567                                  */
8568                                 const int test_flags = METHOD_ATTRIBUTE_VIRTUAL | METHOD_ATTRIBUTE_FINAL | METHOD_ATTRIBUTE_STATIC;
8569                                 const int expected_flags = METHOD_ATTRIBUTE_VIRTUAL | METHOD_ATTRIBUTE_FINAL;
8570                                 if (!virtual_ && mono_class_is_marshalbyref (cmethod->klass) && (cmethod->flags & test_flags) == expected_flags && cfg->method->wrapper_type == MONO_WRAPPER_NONE)
8571                                         virtual_ = 1;
8572                         }
8573
8574                         if (!cmethod->klass->inited)
8575                                 if (!mono_class_init (cmethod->klass))
8576                                         TYPE_LOAD_ERROR (cmethod->klass);
8577
8578                         fsig = mono_method_signature (cmethod);
8579                         if (!fsig)
8580                                 LOAD_ERROR;
8581                         if (cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL &&
8582                                 mini_class_is_system_array (cmethod->klass)) {
8583                                 array_rank = cmethod->klass->rank;
8584                         } else if ((cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && icall_is_direct_callable (cfg, cmethod)) {
8585                                 direct_icall = TRUE;
8586                         } else if (fsig->pinvoke) {
8587                                 MonoMethod *wrapper = mono_marshal_get_native_wrapper (cmethod, TRUE, cfg->compile_aot);
8588                                 fsig = mono_method_signature (wrapper);
8589                         } else if (constrained_class) {
8590                         } else {
8591                                 fsig = mono_method_get_signature_checked (cmethod, image, token, generic_context, &cfg->error);
8592                                 CHECK_CFG_ERROR;
8593                         }
8594
8595                         if (cfg->llvm_only && !cfg->method->wrapper_type && (!cmethod || cmethod->is_inflated))
8596                                 cfg->signatures = g_slist_prepend_mempool (cfg->mempool, cfg->signatures, fsig);
8597
8598                         /* See code below */
8599                         if (cmethod->klass == mono_defaults.monitor_class && !strcmp (cmethod->name, "Enter") && mono_method_signature (cmethod)->param_count == 1) {
8600                                 MonoBasicBlock *tbb;
8601
8602                                 GET_BBLOCK (cfg, tbb, ip + 5);
8603                                 if (tbb->try_start && MONO_REGION_FLAGS(tbb->region) == MONO_EXCEPTION_CLAUSE_FINALLY) {
8604                                         /*
8605                                          * We want to extend the try block to cover the call, but we can't do it if the
8606                                          * call is made directly since its followed by an exception check.
8607                                          */
8608                                         direct_icall = FALSE;
8609                                 }
8610                         }
8611
8612                         mono_save_token_info (cfg, image, token, cil_method);
8613
8614                         if (!(seq_point_locs && mono_bitset_test_fast (seq_point_locs, ip + 5 - header->code)))
8615                                 need_seq_point = TRUE;
8616
8617                         /* Don't support calls made using type arguments for now */
8618                         /*
8619                           if (cfg->gsharedvt) {
8620                           if (mini_is_gsharedvt_signature (fsig))
8621                           GSHAREDVT_FAILURE (*ip);
8622                           }
8623                         */
8624
8625                         if (cmethod->string_ctor && method->wrapper_type != MONO_WRAPPER_RUNTIME_INVOKE)
8626                                 g_assert_not_reached ();
8627
8628                         n = fsig->param_count + fsig->hasthis;
8629
8630                         if (!cfg->gshared && mono_class_is_gtd (cmethod->klass))
8631                                 UNVERIFIED;
8632
8633                         if (!cfg->gshared)
8634                                 g_assert (!mono_method_check_context_used (cmethod));
8635
8636                         CHECK_STACK (n);
8637
8638                         //g_assert (!virtual_ || fsig->hasthis);
8639
8640                         sp -= n;
8641
8642                         if (cmethod && cmethod->klass->image == mono_defaults.corlib && !strcmp (cmethod->klass->name, "ThrowHelper"))
8643                                 cfg->cbb->out_of_line = TRUE;
8644
8645                         /*
8646                          * We have the `constrained.' prefix opcode.
8647                          */
8648                         if (constrained_class) {
8649                                 if (mini_is_gsharedvt_klass (constrained_class)) {
8650                                         if ((cmethod->klass != mono_defaults.object_class) && constrained_class->valuetype && cmethod->klass->valuetype) {
8651                                                 /* The 'Own method' case below */
8652                                         } else if (cmethod->klass->image != mono_defaults.corlib && !mono_class_is_interface (cmethod->klass) && !cmethod->klass->valuetype) {
8653                                                 /* 'The type parameter is instantiated as a reference type' case below. */
8654                                         } else {
8655                                                 ins = handle_constrained_gsharedvt_call (cfg, cmethod, fsig, sp, constrained_class, &emit_widen);
8656                                                 CHECK_CFG_EXCEPTION;
8657                                                 g_assert (ins);
8658                                                 goto call_end;
8659                                         }
8660                                 }
8661
8662                                 if (constrained_partial_call) {
8663                                         gboolean need_box = TRUE;
8664
8665                                         /*
8666                                          * The receiver is a valuetype, but the exact type is not known at compile time. This means the
8667                                          * called method is not known at compile time either. The called method could end up being
8668                                          * one of the methods on the parent classes (object/valuetype/enum), in which case we need
8669                                          * to box the receiver.
8670                                          * A simple solution would be to box always and make a normal virtual call, but that would
8671                                          * be bad performance wise.
8672                                          */
8673                                         if (mono_class_is_interface (cmethod->klass) && mono_class_is_ginst (cmethod->klass)) {
8674                                                 /*
8675                                                  * The parent classes implement no generic interfaces, so the called method will be a vtype method, so no boxing neccessary.
8676                                                  */
8677                                                 need_box = FALSE;
8678                                         }
8679
8680                                         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)) {
8681                                                 /* The called method is not virtual, i.e. Object:GetType (), the receiver is a vtype, has to box */
8682                                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &constrained_class->byval_arg, sp [0]->dreg, 0);
8683                                                 ins->klass = constrained_class;
8684                                                 sp [0] = handle_box (cfg, ins, constrained_class, mono_class_check_context_used (constrained_class));
8685                                                 CHECK_CFG_EXCEPTION;
8686                                         } else if (need_box) {
8687                                                 MonoInst *box_type;
8688                                                 MonoBasicBlock *is_ref_bb, *end_bb;
8689                                                 MonoInst *nonbox_call;
8690
8691                                                 /*
8692                                                  * Determine at runtime whenever the called method is defined on object/valuetype/enum, and emit a boxing call
8693                                                  * if needed.
8694                                                  * FIXME: It is possible to inline the called method in a lot of cases, i.e. for T_INT,
8695                                                  * the no-box case goes to a method in Int32, while the box case goes to a method in Enum.
8696                                                  */
8697                                                 addr = emit_get_rgctx_virt_method (cfg, mono_class_check_context_used (constrained_class), constrained_class, cmethod, MONO_RGCTX_INFO_VIRT_METHOD_CODE);
8698
8699                                                 NEW_BBLOCK (cfg, is_ref_bb);
8700                                                 NEW_BBLOCK (cfg, end_bb);
8701
8702                                                 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);
8703                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, box_type->dreg, MONO_GSHAREDVT_BOX_TYPE_REF);
8704                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, is_ref_bb);
8705
8706                                                 /* Non-ref case */
8707                                                 nonbox_call = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
8708
8709                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
8710
8711                                                 /* Ref case */
8712                                                 MONO_START_BB (cfg, is_ref_bb);
8713                                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &constrained_class->byval_arg, sp [0]->dreg, 0);
8714                                                 ins->klass = constrained_class;
8715                                                 sp [0] = handle_box (cfg, ins, constrained_class, mono_class_check_context_used (constrained_class));
8716                                                 ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
8717
8718                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
8719
8720                                                 MONO_START_BB (cfg, end_bb);
8721                                                 cfg->cbb = end_bb;
8722
8723                                                 nonbox_call->dreg = ins->dreg;
8724                                                 goto call_end;
8725                                         } else {
8726                                                 g_assert (mono_class_is_interface (cmethod->klass));
8727                                                 addr = emit_get_rgctx_virt_method (cfg, mono_class_check_context_used (constrained_class), constrained_class, cmethod, MONO_RGCTX_INFO_VIRT_METHOD_CODE);
8728                                                 ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
8729                                                 goto call_end;
8730                                         }
8731                                 } else if (constrained_class->valuetype && (cmethod->klass == mono_defaults.object_class || cmethod->klass == mono_defaults.enum_class->parent || cmethod->klass == mono_defaults.enum_class)) {
8732                                         /*
8733                                          * The type parameter is instantiated as a valuetype,
8734                                          * but that type doesn't override the method we're
8735                                          * calling, so we need to box `this'.
8736                                          */
8737                                         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &constrained_class->byval_arg, sp [0]->dreg, 0);
8738                                         ins->klass = constrained_class;
8739                                         sp [0] = handle_box (cfg, ins, constrained_class, mono_class_check_context_used (constrained_class));
8740                                         CHECK_CFG_EXCEPTION;
8741                                 } else if (!constrained_class->valuetype) {
8742                                         int dreg = alloc_ireg_ref (cfg);
8743
8744                                         /*
8745                                          * The type parameter is instantiated as a reference
8746                                          * type.  We have a managed pointer on the stack, so
8747                                          * we need to dereference it here.
8748                                          */
8749                                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, dreg, sp [0]->dreg, 0);
8750                                         ins->type = STACK_OBJ;
8751                                         sp [0] = ins;
8752                                 } else {
8753                                         if (cmethod->klass->valuetype) {
8754                                                 /* Own method */
8755                                         } else {
8756                                                 /* Interface method */
8757                                                 int ioffset, slot;
8758
8759                                                 mono_class_setup_vtable (constrained_class);
8760                                                 CHECK_TYPELOAD (constrained_class);
8761                                                 ioffset = mono_class_interface_offset (constrained_class, cmethod->klass);
8762                                                 if (ioffset == -1)
8763                                                         TYPE_LOAD_ERROR (constrained_class);
8764                                                 slot = mono_method_get_vtable_slot (cmethod);
8765                                                 if (slot == -1)
8766                                                         TYPE_LOAD_ERROR (cmethod->klass);
8767                                                 cmethod = constrained_class->vtable [ioffset + slot];
8768
8769                                                 if (cmethod->klass == mono_defaults.enum_class) {
8770                                                         /* Enum implements some interfaces, so treat this as the first case */
8771                                                         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &constrained_class->byval_arg, sp [0]->dreg, 0);
8772                                                         ins->klass = constrained_class;
8773                                                         sp [0] = handle_box (cfg, ins, constrained_class, mono_class_check_context_used (constrained_class));
8774                                                         CHECK_CFG_EXCEPTION;
8775                                                 }
8776                                         }
8777                                         virtual_ = 0;
8778                                 }
8779                                 constrained_class = NULL;
8780                         }
8781
8782                         if (check_call_signature (cfg, fsig, sp))
8783                                 UNVERIFIED;
8784
8785                         if ((cmethod->klass->parent == mono_defaults.multicastdelegate_class) && !strcmp (cmethod->name, "Invoke"))
8786                                 delegate_invoke = TRUE;
8787
8788                         if ((cfg->opt & MONO_OPT_INTRINS) && (ins = mini_emit_inst_for_sharable_method (cfg, cmethod, fsig, sp))) {
8789                                 if (!MONO_TYPE_IS_VOID (fsig->ret)) {
8790                                         type_to_eval_stack_type ((cfg), fsig->ret, ins);
8791                                         emit_widen = FALSE;
8792                                 }
8793
8794                                 goto call_end;
8795                         }
8796
8797                         /* 
8798                          * If the callee is a shared method, then its static cctor
8799                          * might not get called after the call was patched.
8800                          */
8801                         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)) {
8802                                 emit_class_init (cfg, cmethod->klass);
8803                                 CHECK_TYPELOAD (cmethod->klass);
8804                         }
8805
8806                         check_method_sharing (cfg, cmethod, &pass_vtable, &pass_mrgctx);
8807
8808                         if (cfg->gshared) {
8809                                 MonoGenericContext *cmethod_context = mono_method_get_context (cmethod);
8810
8811                                 context_used = mini_method_check_context_used (cfg, cmethod);
8812
8813                                 if (context_used && mono_class_is_interface (cmethod->klass)) {
8814                                         /* Generic method interface
8815                                            calls are resolved via a
8816                                            helper function and don't
8817                                            need an imt. */
8818                                         if (!cmethod_context || !cmethod_context->method_inst)
8819                                                 pass_imt_from_rgctx = TRUE;
8820                                 }
8821
8822                                 /*
8823                                  * If a shared method calls another
8824                                  * shared method then the caller must
8825                                  * have a generic sharing context
8826                                  * because the magic trampoline
8827                                  * requires it.  FIXME: We shouldn't
8828                                  * have to force the vtable/mrgctx
8829                                  * variable here.  Instead there
8830                                  * should be a flag in the cfg to
8831                                  * request a generic sharing context.
8832                                  */
8833                                 if (context_used &&
8834                                                 ((cfg->method->flags & METHOD_ATTRIBUTE_STATIC) || cfg->method->klass->valuetype))
8835                                         mono_get_vtable_var (cfg);
8836                         }
8837
8838                         if (pass_vtable) {
8839                                 if (context_used) {
8840                                         vtable_arg = mini_emit_get_rgctx_klass (cfg, context_used, cmethod->klass, MONO_RGCTX_INFO_VTABLE);
8841                                 } else {
8842                                         MonoVTable *vtable = mono_class_vtable (cfg->domain, cmethod->klass);
8843
8844                                         CHECK_TYPELOAD (cmethod->klass);
8845                                         EMIT_NEW_VTABLECONST (cfg, vtable_arg, vtable);
8846                                 }
8847                         }
8848
8849                         if (pass_mrgctx) {
8850                                 g_assert (!vtable_arg);
8851
8852                                 if (!cfg->compile_aot) {
8853                                         /* 
8854                                          * emit_get_rgctx_method () calls mono_class_vtable () so check 
8855                                          * for type load errors before.
8856                                          */
8857                                         mono_class_setup_vtable (cmethod->klass);
8858                                         CHECK_TYPELOAD (cmethod->klass);
8859                                 }
8860
8861                                 vtable_arg = emit_get_rgctx_method (cfg, context_used, cmethod, MONO_RGCTX_INFO_METHOD_RGCTX);
8862
8863                                 /* !marshalbyref is needed to properly handle generic methods + remoting */
8864                                 if ((!(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) ||
8865                                          MONO_METHOD_IS_FINAL (cmethod)) &&
8866                                         !mono_class_is_marshalbyref (cmethod->klass)) {
8867                                         if (virtual_)
8868                                                 check_this = TRUE;
8869                                         virtual_ = 0;
8870                                 }
8871                         }
8872
8873                         if (pass_imt_from_rgctx) {
8874                                 g_assert (!pass_vtable);
8875
8876                                 imt_arg = emit_get_rgctx_method (cfg, context_used,
8877                                         cmethod, MONO_RGCTX_INFO_METHOD);
8878                         }
8879
8880                         if (check_this)
8881                                 MONO_EMIT_NEW_CHECK_THIS (cfg, sp [0]->dreg);
8882
8883                         /* Calling virtual generic methods */
8884                         if (virtual_ && (cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) &&
8885                             !(MONO_METHOD_IS_FINAL (cmethod) && 
8886                               cmethod->wrapper_type != MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK) &&
8887                             fsig->generic_param_count && 
8888                                 !(cfg->gsharedvt && mini_is_gsharedvt_signature (fsig)) &&
8889                                 !cfg->llvm_only) {
8890                                 MonoInst *this_temp, *this_arg_temp, *store;
8891                                 MonoInst *iargs [4];
8892
8893                                 g_assert (fsig->is_inflated);
8894
8895                                 /* Prevent inlining of methods that contain indirect calls */
8896                                 INLINE_FAILURE ("virtual generic call");
8897
8898                                 if (cfg->gsharedvt && mini_is_gsharedvt_signature (fsig))
8899                                         GSHAREDVT_FAILURE (*ip);
8900
8901                                 if (cfg->backend->have_generalized_imt_trampoline && cfg->backend->gshared_supported && cmethod->wrapper_type == MONO_WRAPPER_NONE) {
8902                                         g_assert (!imt_arg);
8903                                         if (!context_used)
8904                                                 g_assert (cmethod->is_inflated);
8905                                         imt_arg = emit_get_rgctx_method (cfg, context_used,
8906                                                                                                          cmethod, MONO_RGCTX_INFO_METHOD);
8907                                         ins = mono_emit_method_call_full (cfg, cmethod, fsig, FALSE, sp, sp [0], imt_arg, NULL);
8908                                 } else {
8909                                         this_temp = mono_compile_create_var (cfg, type_from_stack_type (sp [0]), OP_LOCAL);
8910                                         NEW_TEMPSTORE (cfg, store, this_temp->inst_c0, sp [0]);
8911                                         MONO_ADD_INS (cfg->cbb, store);
8912
8913                                         /* FIXME: This should be a managed pointer */
8914                                         this_arg_temp = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
8915
8916                                         EMIT_NEW_TEMPLOAD (cfg, iargs [0], this_temp->inst_c0);
8917                                         iargs [1] = emit_get_rgctx_method (cfg, context_used,
8918                                                                                                            cmethod, MONO_RGCTX_INFO_METHOD);
8919                                         EMIT_NEW_TEMPLOADA (cfg, iargs [2], this_arg_temp->inst_c0);
8920                                         addr = mono_emit_jit_icall (cfg,
8921                                                                                                 mono_helper_compile_generic_method, iargs);
8922
8923                                         EMIT_NEW_TEMPLOAD (cfg, sp [0], this_arg_temp->inst_c0);
8924
8925                                         ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
8926                                 }
8927
8928                                 goto call_end;
8929                         }
8930
8931                         /*
8932                          * Implement a workaround for the inherent races involved in locking:
8933                          * Monitor.Enter ()
8934                          * try {
8935                          * } finally {
8936                          *    Monitor.Exit ()
8937                          * }
8938                          * If a thread abort happens between the call to Monitor.Enter () and the start of the
8939                          * try block, the Exit () won't be executed, see:
8940                          * http://www.bluebytesoftware.com/blog/2007/01/30/MonitorEnterThreadAbortsAndOrphanedLocks.aspx
8941                          * To work around this, we extend such try blocks to include the last x bytes
8942                          * of the Monitor.Enter () call.
8943                          */
8944                         if (cmethod->klass == mono_defaults.monitor_class && !strcmp (cmethod->name, "Enter") && mono_method_signature (cmethod)->param_count == 1) {
8945                                 MonoBasicBlock *tbb;
8946
8947                                 GET_BBLOCK (cfg, tbb, ip + 5);
8948                                 /* 
8949                                  * Only extend try blocks with a finally, to avoid catching exceptions thrown
8950                                  * from Monitor.Enter like ArgumentNullException.
8951                                  */
8952                                 if (tbb->try_start && MONO_REGION_FLAGS(tbb->region) == MONO_EXCEPTION_CLAUSE_FINALLY) {
8953                                         /* Mark this bblock as needing to be extended */
8954                                         tbb->extend_try_block = TRUE;
8955                                 }
8956                         }
8957
8958                         /* Conversion to a JIT intrinsic */
8959                         if ((cfg->opt & MONO_OPT_INTRINS) && (ins = mini_emit_inst_for_method (cfg, cmethod, fsig, sp))) {
8960                                 if (!MONO_TYPE_IS_VOID (fsig->ret)) {
8961                                         type_to_eval_stack_type ((cfg), fsig->ret, ins);
8962                                         emit_widen = FALSE;
8963                                 }
8964                                 goto call_end;
8965                         }
8966                         CHECK_CFG_ERROR;
8967                         
8968                         /* Inlining */
8969                         if ((cfg->opt & MONO_OPT_INLINE) &&
8970                                 (!virtual_ || !(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) || MONO_METHOD_IS_FINAL (cmethod)) &&
8971                             mono_method_check_inlining (cfg, cmethod)) {
8972                                 int costs;
8973                                 gboolean always = FALSE;
8974
8975                                 if ((cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
8976                                         (cmethod->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
8977                                         /* Prevent inlining of methods that call wrappers */
8978                                         INLINE_FAILURE ("wrapper call");
8979                                         cmethod = mono_marshal_get_native_wrapper (cmethod, TRUE, FALSE);
8980                                         always = TRUE;
8981                                 }
8982
8983                                 costs = inline_method (cfg, cmethod, fsig, sp, ip, cfg->real_offset, always);
8984                                 if (costs) {
8985                                         cfg->real_offset += 5;
8986
8987                                         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
8988                                                 /* *sp is already set by inline_method */
8989                                                 sp++;
8990                                                 push_res = FALSE;
8991                                         }
8992
8993                                         inline_costs += costs;
8994
8995                                         goto call_end;
8996                                 }
8997                         }
8998
8999                         /* Tail recursion elimination */
9000                         if ((cfg->opt & MONO_OPT_TAILC) && call_opcode == CEE_CALL && cmethod == method && ip [5] == CEE_RET && !vtable_arg) {
9001                                 gboolean has_vtargs = FALSE;
9002                                 int i;
9003
9004                                 /* Prevent inlining of methods with tail calls (the call stack would be altered) */
9005                                 INLINE_FAILURE ("tail call");
9006
9007                                 /* keep it simple */
9008                                 for (i =  fsig->param_count - 1; i >= 0; i--) {
9009                                         if (MONO_TYPE_ISSTRUCT (mono_method_signature (cmethod)->params [i])) 
9010                                                 has_vtargs = TRUE;
9011                                 }
9012
9013                                 if (!has_vtargs) {
9014                                         if (need_seq_point) {
9015                                                 emit_seq_point (cfg, method, ip, FALSE, TRUE);
9016                                                 need_seq_point = FALSE;
9017                                         }
9018                                         for (i = 0; i < n; ++i)
9019                                                 EMIT_NEW_ARGSTORE (cfg, ins, i, sp [i]);
9020                                         MONO_INST_NEW (cfg, ins, OP_BR);
9021                                         MONO_ADD_INS (cfg->cbb, ins);
9022                                         tblock = start_bblock->out_bb [0];
9023                                         link_bblock (cfg, cfg->cbb, tblock);
9024                                         ins->inst_target_bb = tblock;
9025                                         start_new_bblock = 1;
9026
9027                                         /* skip the CEE_RET, too */
9028                                         if (ip_in_bb (cfg, cfg->cbb, ip + 5))
9029                                                 skip_ret = TRUE;
9030                                         push_res = FALSE;
9031                                         goto call_end;
9032                                 }
9033                         }
9034
9035                         inline_costs += 10 * num_calls++;
9036
9037                         /*
9038                          * Synchronized wrappers.
9039                          * Its hard to determine where to replace a method with its synchronized
9040                          * wrapper without causing an infinite recursion. The current solution is
9041                          * to add the synchronized wrapper in the trampolines, and to
9042                          * change the called method to a dummy wrapper, and resolve that wrapper
9043                          * to the real method in mono_jit_compile_method ().
9044                          */
9045                         if (cfg->method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED) {
9046                                 MonoMethod *orig = mono_marshal_method_from_wrapper (cfg->method);
9047                                 if (cmethod == orig || (cmethod->is_inflated && mono_method_get_declaring_generic_method (cmethod) == orig))
9048                                         cmethod = mono_marshal_get_synchronized_inner_wrapper (cmethod);
9049                         }
9050
9051                         /*
9052                          * Making generic calls out of gsharedvt methods.
9053                          * This needs to be used for all generic calls, not just ones with a gsharedvt signature, to avoid
9054                          * patching gshared method addresses into a gsharedvt method.
9055                          */
9056                         if (cfg->gsharedvt && (mini_is_gsharedvt_signature (fsig) || cmethod->is_inflated || mono_class_is_ginst (cmethod->klass)) &&
9057                                 !(cmethod->klass->rank && cmethod->klass->byval_arg.type != MONO_TYPE_SZARRAY) &&
9058                                 (!(cfg->llvm_only && virtual_ && (cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL)))) {
9059                                 MonoRgctxInfoType info_type;
9060
9061                                 if (virtual_) {
9062                                         //if (mono_class_is_interface (cmethod->klass))
9063                                                 //GSHAREDVT_FAILURE (*ip);
9064                                         // disable for possible remoting calls
9065                                         if (fsig->hasthis && (mono_class_is_marshalbyref (method->klass) || method->klass == mono_defaults.object_class))
9066                                                 GSHAREDVT_FAILURE (*ip);
9067                                         if (fsig->generic_param_count) {
9068                                                 /* virtual generic call */
9069                                                 g_assert (!imt_arg);
9070                                                 /* Same as the virtual generic case above */
9071                                                 imt_arg = emit_get_rgctx_method (cfg, context_used,
9072                                                                                                                  cmethod, MONO_RGCTX_INFO_METHOD);
9073                                                 /* This is not needed, as the trampoline code will pass one, and it might be passed in the same reg as the imt arg */
9074                                                 vtable_arg = NULL;
9075                                         } else if (mono_class_is_interface (cmethod->klass) && !imt_arg) {
9076                                                 /* This can happen when we call a fully instantiated iface method */
9077                                                 imt_arg = emit_get_rgctx_method (cfg, context_used,
9078                                                                                                                  cmethod, MONO_RGCTX_INFO_METHOD);
9079                                                 vtable_arg = NULL;
9080                                         }
9081                                 }
9082
9083                                 if ((cmethod->klass->parent == mono_defaults.multicastdelegate_class) && (!strcmp (cmethod->name, "Invoke")))
9084                                         keep_this_alive = sp [0];
9085
9086                                 if (virtual_ && (cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL))
9087                                         info_type = MONO_RGCTX_INFO_METHOD_GSHAREDVT_OUT_TRAMPOLINE_VIRT;
9088                                 else
9089                                         info_type = MONO_RGCTX_INFO_METHOD_GSHAREDVT_OUT_TRAMPOLINE;
9090                                 addr = emit_get_rgctx_gsharedvt_call (cfg, context_used, fsig, cmethod, info_type);
9091
9092                                 if (cfg->llvm_only) {
9093                                         // FIXME: Avoid initializing vtable_arg
9094                                         ins = emit_llvmonly_calli (cfg, fsig, sp, addr);
9095                                 } else {
9096                                         ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, imt_arg, vtable_arg);
9097                                 }
9098                                 goto call_end;
9099                         }
9100
9101                         /* Generic sharing */
9102
9103                         /*
9104                          * Use this if the callee is gsharedvt sharable too, since
9105                          * at runtime we might find an instantiation so the call cannot
9106                          * be patched (the 'no_patch' code path in mini-trampolines.c).
9107                          */
9108                         if (context_used && !imt_arg && !array_rank && !delegate_invoke &&
9109                                 (!mono_method_is_generic_sharable_full (cmethod, TRUE, FALSE, FALSE) ||
9110                                  !mono_class_generic_sharing_enabled (cmethod->klass)) &&
9111                                 (!virtual_ || MONO_METHOD_IS_FINAL (cmethod) ||
9112                                  !(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL))) {
9113                                 INLINE_FAILURE ("gshared");
9114
9115                                 g_assert (cfg->gshared && cmethod);
9116                                 g_assert (!addr);
9117
9118                                 /*
9119                                  * We are compiling a call to a
9120                                  * generic method from shared code,
9121                                  * which means that we have to look up
9122                                  * the method in the rgctx and do an
9123                                  * indirect call.
9124                                  */
9125                                 if (fsig->hasthis)
9126                                         MONO_EMIT_NEW_CHECK_THIS (cfg, sp [0]->dreg);
9127
9128                                 if (cfg->llvm_only) {
9129                                         if (cfg->gsharedvt && mini_is_gsharedvt_variable_signature (fsig))
9130                                                 addr = emit_get_rgctx_method (cfg, context_used, cmethod, MONO_RGCTX_INFO_GSHAREDVT_OUT_WRAPPER);
9131                                         else
9132                                                 addr = emit_get_rgctx_method (cfg, context_used, cmethod, MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
9133                                         // FIXME: Avoid initializing imt_arg/vtable_arg
9134                                         ins = emit_llvmonly_calli (cfg, fsig, sp, addr);
9135                                 } else {
9136                                         addr = emit_get_rgctx_method (cfg, context_used, cmethod, MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
9137                                         ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, imt_arg, vtable_arg);
9138                                 }
9139                                 goto call_end;
9140                         }
9141
9142                         /* Direct calls to icalls */
9143                         if (direct_icall) {
9144                                 MonoMethod *wrapper;
9145                                 int costs;
9146
9147                                 /* Inline the wrapper */
9148                                 wrapper = mono_marshal_get_native_wrapper (cmethod, TRUE, cfg->compile_aot);
9149
9150                                 costs = inline_method (cfg, wrapper, fsig, sp, ip, cfg->real_offset, TRUE);
9151                                 g_assert (costs > 0);
9152                                 cfg->real_offset += 5;
9153
9154                                 if (!MONO_TYPE_IS_VOID (fsig->ret)) {
9155                                         /* *sp is already set by inline_method */
9156                                         sp++;
9157                                         push_res = FALSE;
9158                                 }
9159
9160                                 inline_costs += costs;
9161
9162                                 goto call_end;
9163                         }
9164                                         
9165                         /* Array methods */
9166                         if (array_rank) {
9167                                 MonoInst *addr;
9168
9169                                 if (strcmp (cmethod->name, "Set") == 0) { /* array Set */ 
9170                                         MonoInst *val = sp [fsig->param_count];
9171
9172                                         if (val->type == STACK_OBJ) {
9173                                                 MonoInst *iargs [2];
9174
9175                                                 iargs [0] = sp [0];
9176                                                 iargs [1] = val;
9177                                                 
9178                                                 mono_emit_jit_icall (cfg, mono_helper_stelem_ref_check, iargs);
9179                                         }
9180                                         
9181                                         addr = mini_emit_ldelema_ins (cfg, cmethod, sp, ip, TRUE);
9182                                         EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, fsig->params [fsig->param_count - 1], addr->dreg, 0, val->dreg);
9183                                         if (cfg->gen_write_barriers && val->type == STACK_OBJ && !MONO_INS_IS_PCONST_NULL (val))
9184                                                 mini_emit_write_barrier (cfg, addr, val);
9185                                         if (cfg->gen_write_barriers && mini_is_gsharedvt_klass (cmethod->klass))
9186                                                 GSHAREDVT_FAILURE (*ip);
9187                                 } else if (strcmp (cmethod->name, "Get") == 0) { /* array Get */
9188                                         addr = mini_emit_ldelema_ins (cfg, cmethod, sp, ip, FALSE);
9189
9190                                         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, fsig->ret, addr->dreg, 0);
9191                                 } else if (strcmp (cmethod->name, "Address") == 0) { /* array Address */
9192                                         if (!cmethod->klass->element_class->valuetype && !readonly)
9193                                                 mini_emit_check_array_type (cfg, sp [0], cmethod->klass);
9194                                         CHECK_TYPELOAD (cmethod->klass);
9195                                         
9196                                         readonly = FALSE;
9197                                         addr = mini_emit_ldelema_ins (cfg, cmethod, sp, ip, FALSE);
9198                                         ins = addr;
9199                                 } else {
9200                                         g_assert_not_reached ();
9201                                 }
9202
9203                                 emit_widen = FALSE;
9204                                 goto call_end;
9205                         }
9206
9207                         ins = mini_redirect_call (cfg, cmethod, fsig, sp, virtual_ ? sp [0] : NULL);
9208                         if (ins)
9209                                 goto call_end;
9210
9211                         /* Tail prefix / tail call optimization */
9212
9213                         /* FIXME: Enabling TAILC breaks some inlining/stack trace/etc tests */
9214                         /* FIXME: runtime generic context pointer for jumps? */
9215                         /* FIXME: handle this for generic sharing eventually */
9216                         if ((ins_flag & MONO_INST_TAILCALL) &&
9217                                 !vtable_arg && !cfg->gshared && is_supported_tail_call (cfg, method, cmethod, fsig, call_opcode))
9218                                 supported_tail_call = TRUE;
9219
9220                         if (supported_tail_call) {
9221                                 MonoCallInst *call;
9222
9223                                 /* Prevent inlining of methods with tail calls (the call stack would be altered) */
9224                                 INLINE_FAILURE ("tail call");
9225
9226                                 //printf ("HIT: %s -> %s\n", mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
9227
9228                                 if (cfg->backend->have_op_tail_call) {
9229                                         /* Handle tail calls similarly to normal calls */
9230                                         tail_call = TRUE;
9231                                 } else {
9232                                         emit_instrumentation_call (cfg, mono_profiler_method_leave);
9233
9234                                         MONO_INST_NEW_CALL (cfg, call, OP_JMP);
9235                                         call->tail_call = TRUE;
9236                                         call->method = cmethod;
9237                                         call->signature = mono_method_signature (cmethod);
9238
9239                                         /*
9240                                          * We implement tail calls by storing the actual arguments into the 
9241                                          * argument variables, then emitting a CEE_JMP.
9242                                          */
9243                                         for (i = 0; i < n; ++i) {
9244                                                 /* Prevent argument from being register allocated */
9245                                                 arg_array [i]->flags |= MONO_INST_VOLATILE;
9246                                                 EMIT_NEW_ARGSTORE (cfg, ins, i, sp [i]);
9247                                         }
9248                                         ins = (MonoInst*)call;
9249                                         ins->inst_p0 = cmethod;
9250                                         ins->inst_p1 = arg_array [0];
9251                                         MONO_ADD_INS (cfg->cbb, ins);
9252                                         link_bblock (cfg, cfg->cbb, end_bblock);
9253                                         start_new_bblock = 1;
9254
9255                                         // FIXME: Eliminate unreachable epilogs
9256
9257                                         /*
9258                                          * OP_TAILCALL has no return value, so skip the CEE_RET if it is
9259                                          * only reachable from this call.
9260                                          */
9261                                         GET_BBLOCK (cfg, tblock, ip + 5);
9262                                         if (tblock == cfg->cbb || tblock->in_count == 0)
9263                                                 skip_ret = TRUE;
9264                                         push_res = FALSE;
9265
9266                                         goto call_end;
9267                                 }
9268                         }
9269
9270                         /*
9271                          * Virtual calls in llvm-only mode.
9272                          */
9273                         if (cfg->llvm_only && virtual_ && cmethod && (cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
9274                                 ins = emit_llvmonly_virtual_call (cfg, cmethod, fsig, context_used, sp);
9275                                 goto call_end;
9276                         }
9277
9278                         /* Common call */
9279                         if (!(method->iflags & METHOD_IMPL_ATTRIBUTE_AGGRESSIVE_INLINING) && !(cmethod->iflags & METHOD_IMPL_ATTRIBUTE_AGGRESSIVE_INLINING))
9280                                 INLINE_FAILURE ("call");
9281                         ins = mono_emit_method_call_full (cfg, cmethod, fsig, tail_call, sp, virtual_ ? sp [0] : NULL,
9282                                                                                           imt_arg, vtable_arg);
9283
9284                         if (tail_call && !cfg->llvm_only) {
9285                                 link_bblock (cfg, cfg->cbb, end_bblock);
9286                                 start_new_bblock = 1;
9287
9288                                 // FIXME: Eliminate unreachable epilogs
9289
9290                                 /*
9291                                  * OP_TAILCALL has no return value, so skip the CEE_RET if it is
9292                                  * only reachable from this call.
9293                                  */
9294                                 GET_BBLOCK (cfg, tblock, ip + 5);
9295                                 if (tblock == cfg->cbb || tblock->in_count == 0)
9296                                         skip_ret = TRUE;
9297                                 push_res = FALSE;
9298                         }
9299
9300                         call_end:
9301
9302                         /* End of call, INS should contain the result of the call, if any */
9303
9304                         if (push_res && !MONO_TYPE_IS_VOID (fsig->ret)) {
9305                                 g_assert (ins);
9306                                 if (emit_widen)
9307                                         *sp++ = mono_emit_widen_call_res (cfg, ins, fsig);
9308                                 else
9309                                         *sp++ = ins;
9310                         }
9311
9312                         if (keep_this_alive) {
9313                                 MonoInst *dummy_use;
9314
9315                                 /* See mono_emit_method_call_full () */
9316                                 EMIT_NEW_DUMMY_USE (cfg, dummy_use, keep_this_alive);
9317                         }
9318
9319                         if (cfg->llvm_only && cmethod && method_needs_stack_walk (cfg, cmethod)) {
9320                                 /*
9321                                  * Clang can convert these calls to tail calls which screw up the stack
9322                                  * walk. This happens even when the -fno-optimize-sibling-calls
9323                                  * option is passed to clang.
9324                                  * Work around this by emitting a dummy call.
9325                                  */
9326                                 mono_emit_jit_icall (cfg, mono_dummy_jit_icall, NULL);
9327                         }
9328
9329                         CHECK_CFG_EXCEPTION;
9330
9331                         ip += 5;
9332                         if (skip_ret) {
9333                                 g_assert (*ip == CEE_RET);
9334                                 ip += 1;
9335                         }
9336                         ins_flag = 0;
9337                         constrained_class = NULL;
9338                         if (need_seq_point)
9339                                 emit_seq_point (cfg, method, ip, FALSE, TRUE);
9340                         break;
9341                 }
9342                 case CEE_RET:
9343                         if (cfg->method != method) {
9344                                 /* return from inlined method */
9345                                 /* 
9346                                  * If in_count == 0, that means the ret is unreachable due to
9347                                  * being preceeded by a throw. In that case, inline_method () will
9348                                  * handle setting the return value 
9349                                  * (test case: test_0_inline_throw ()).
9350                                  */
9351                                 if (return_var && cfg->cbb->in_count) {
9352                                         MonoType *ret_type = mono_method_signature (method)->ret;
9353
9354                                         MonoInst *store;
9355                                         CHECK_STACK (1);
9356                                         --sp;
9357
9358                                         if ((method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD || method->wrapper_type == MONO_WRAPPER_NONE) && target_type_is_incompatible (cfg, ret_type, *sp))
9359                                                 UNVERIFIED;
9360
9361                                         //g_assert (returnvar != -1);
9362                                         EMIT_NEW_TEMPSTORE (cfg, store, return_var->inst_c0, *sp);
9363                                         cfg->ret_var_set = TRUE;
9364                                 } 
9365                         } else {
9366                                 emit_instrumentation_call (cfg, mono_profiler_method_leave);
9367
9368                                 if (cfg->lmf_var && cfg->cbb->in_count && !cfg->llvm_only)
9369                                         emit_pop_lmf (cfg);
9370
9371                                 if (cfg->ret) {
9372                                         MonoType *ret_type = mini_get_underlying_type (mono_method_signature (method)->ret);
9373
9374                                         if (seq_points && !sym_seq_points) {
9375                                                 /* 
9376                                                  * Place a seq point here too even through the IL stack is not
9377                                                  * empty, so a step over on
9378                                                  * call <FOO>
9379                                                  * ret
9380                                                  * will work correctly.
9381                                                  */
9382                                                 NEW_SEQ_POINT (cfg, ins, ip - header->code, TRUE);
9383                                                 MONO_ADD_INS (cfg->cbb, ins);
9384                                         }
9385
9386                                         g_assert (!return_var);
9387                                         CHECK_STACK (1);
9388                                         --sp;
9389
9390                                         if ((method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD || method->wrapper_type == MONO_WRAPPER_NONE) && target_type_is_incompatible (cfg, ret_type, *sp))
9391                                                 UNVERIFIED;
9392
9393                                         emit_setret (cfg, *sp);
9394                                 }
9395                         }
9396                         if (sp != stack_start)
9397                                 UNVERIFIED;
9398                         MONO_INST_NEW (cfg, ins, OP_BR);
9399                         ip++;
9400                         ins->inst_target_bb = end_bblock;
9401                         MONO_ADD_INS (cfg->cbb, ins);
9402                         link_bblock (cfg, cfg->cbb, end_bblock);
9403                         start_new_bblock = 1;
9404                         break;
9405                 case CEE_BR_S:
9406                         CHECK_OPSIZE (2);
9407                         MONO_INST_NEW (cfg, ins, OP_BR);
9408                         ip++;
9409                         target = ip + 1 + (signed char)(*ip);
9410                         ++ip;
9411                         GET_BBLOCK (cfg, tblock, target);
9412                         link_bblock (cfg, cfg->cbb, tblock);
9413                         ins->inst_target_bb = tblock;
9414                         if (sp != stack_start) {
9415                                 handle_stack_args (cfg, stack_start, sp - stack_start);
9416                                 sp = stack_start;
9417                                 CHECK_UNVERIFIABLE (cfg);
9418                         }
9419                         MONO_ADD_INS (cfg->cbb, ins);
9420                         start_new_bblock = 1;
9421                         inline_costs += BRANCH_COST;
9422                         break;
9423                 case CEE_BEQ_S:
9424                 case CEE_BGE_S:
9425                 case CEE_BGT_S:
9426                 case CEE_BLE_S:
9427                 case CEE_BLT_S:
9428                 case CEE_BNE_UN_S:
9429                 case CEE_BGE_UN_S:
9430                 case CEE_BGT_UN_S:
9431                 case CEE_BLE_UN_S:
9432                 case CEE_BLT_UN_S:
9433                         CHECK_OPSIZE (2);
9434                         CHECK_STACK (2);
9435                         MONO_INST_NEW (cfg, ins, *ip + BIG_BRANCH_OFFSET);
9436                         ip++;
9437                         target = ip + 1 + *(signed char*)ip;
9438                         ip++;
9439
9440                         ADD_BINCOND (NULL);
9441
9442                         sp = stack_start;
9443                         inline_costs += BRANCH_COST;
9444                         break;
9445                 case CEE_BR:
9446                         CHECK_OPSIZE (5);
9447                         MONO_INST_NEW (cfg, ins, OP_BR);
9448                         ip++;
9449
9450                         target = ip + 4 + (gint32)read32(ip);
9451                         ip += 4;
9452                         GET_BBLOCK (cfg, tblock, target);
9453                         link_bblock (cfg, cfg->cbb, tblock);
9454                         ins->inst_target_bb = tblock;
9455                         if (sp != stack_start) {
9456                                 handle_stack_args (cfg, stack_start, sp - stack_start);
9457                                 sp = stack_start;
9458                                 CHECK_UNVERIFIABLE (cfg);
9459                         }
9460
9461                         MONO_ADD_INS (cfg->cbb, ins);
9462
9463                         start_new_bblock = 1;
9464                         inline_costs += BRANCH_COST;
9465                         break;
9466                 case CEE_BRFALSE_S:
9467                 case CEE_BRTRUE_S:
9468                 case CEE_BRFALSE:
9469                 case CEE_BRTRUE: {
9470                         MonoInst *cmp;
9471                         gboolean is_short = ((*ip) == CEE_BRFALSE_S) || ((*ip) == CEE_BRTRUE_S);
9472                         gboolean is_true = ((*ip) == CEE_BRTRUE_S) || ((*ip) == CEE_BRTRUE);
9473                         guint32 opsize = is_short ? 1 : 4;
9474
9475                         CHECK_OPSIZE (opsize);
9476                         CHECK_STACK (1);
9477                         if (sp [-1]->type == STACK_VTYPE || sp [-1]->type == STACK_R8)
9478                                 UNVERIFIED;
9479                         ip ++;
9480                         target = ip + opsize + (is_short ? *(signed char*)ip : (gint32)read32(ip));
9481                         ip += opsize;
9482
9483                         sp--;
9484
9485                         GET_BBLOCK (cfg, tblock, target);
9486                         link_bblock (cfg, cfg->cbb, tblock);
9487                         GET_BBLOCK (cfg, tblock, ip);
9488                         link_bblock (cfg, cfg->cbb, tblock);
9489
9490                         if (sp != stack_start) {
9491                                 handle_stack_args (cfg, stack_start, sp - stack_start);
9492                                 CHECK_UNVERIFIABLE (cfg);
9493                         }
9494
9495                         MONO_INST_NEW(cfg, cmp, OP_ICOMPARE_IMM);
9496                         cmp->sreg1 = sp [0]->dreg;
9497                         type_from_op (cfg, cmp, sp [0], NULL);
9498                         CHECK_TYPE (cmp);
9499
9500 #if SIZEOF_REGISTER == 4
9501                         if (cmp->opcode == OP_LCOMPARE_IMM) {
9502                                 /* Convert it to OP_LCOMPARE */
9503                                 MONO_INST_NEW (cfg, ins, OP_I8CONST);
9504                                 ins->type = STACK_I8;
9505                                 ins->dreg = alloc_dreg (cfg, STACK_I8);
9506                                 ins->inst_l = 0;
9507                                 MONO_ADD_INS (cfg->cbb, ins);
9508                                 cmp->opcode = OP_LCOMPARE;
9509                                 cmp->sreg2 = ins->dreg;
9510                         }
9511 #endif
9512                         MONO_ADD_INS (cfg->cbb, cmp);
9513
9514                         MONO_INST_NEW (cfg, ins, is_true ? CEE_BNE_UN : CEE_BEQ);
9515                         type_from_op (cfg, ins, sp [0], NULL);
9516                         MONO_ADD_INS (cfg->cbb, ins);
9517                         ins->inst_many_bb = (MonoBasicBlock **)mono_mempool_alloc (cfg->mempool, sizeof(gpointer)*2);
9518                         GET_BBLOCK (cfg, tblock, target);
9519                         ins->inst_true_bb = tblock;
9520                         GET_BBLOCK (cfg, tblock, ip);
9521                         ins->inst_false_bb = tblock;
9522                         start_new_bblock = 2;
9523
9524                         sp = stack_start;
9525                         inline_costs += BRANCH_COST;
9526                         break;
9527                 }
9528                 case CEE_BEQ:
9529                 case CEE_BGE:
9530                 case CEE_BGT:
9531                 case CEE_BLE:
9532                 case CEE_BLT:
9533                 case CEE_BNE_UN:
9534                 case CEE_BGE_UN:
9535                 case CEE_BGT_UN:
9536                 case CEE_BLE_UN:
9537                 case CEE_BLT_UN:
9538                         CHECK_OPSIZE (5);
9539                         CHECK_STACK (2);
9540                         MONO_INST_NEW (cfg, ins, *ip);
9541                         ip++;
9542                         target = ip + 4 + (gint32)read32(ip);
9543                         ip += 4;
9544
9545                         ADD_BINCOND (NULL);
9546
9547                         sp = stack_start;
9548                         inline_costs += BRANCH_COST;
9549                         break;
9550                 case CEE_SWITCH: {
9551                         MonoInst *src1;
9552                         MonoBasicBlock **targets;
9553                         MonoBasicBlock *default_bblock;
9554                         MonoJumpInfoBBTable *table;
9555                         int offset_reg = alloc_preg (cfg);
9556                         int target_reg = alloc_preg (cfg);
9557                         int table_reg = alloc_preg (cfg);
9558                         int sum_reg = alloc_preg (cfg);
9559                         gboolean use_op_switch;
9560
9561                         CHECK_OPSIZE (5);
9562                         CHECK_STACK (1);
9563                         n = read32 (ip + 1);
9564                         --sp;
9565                         src1 = sp [0];
9566                         if ((src1->type != STACK_I4) && (src1->type != STACK_PTR)) 
9567                                 UNVERIFIED;
9568
9569                         ip += 5;
9570                         CHECK_OPSIZE (n * sizeof (guint32));
9571                         target = ip + n * sizeof (guint32);
9572
9573                         GET_BBLOCK (cfg, default_bblock, target);
9574                         default_bblock->flags |= BB_INDIRECT_JUMP_TARGET;
9575
9576                         targets = (MonoBasicBlock **)mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * n);
9577                         for (i = 0; i < n; ++i) {
9578                                 GET_BBLOCK (cfg, tblock, target + (gint32)read32(ip));
9579                                 targets [i] = tblock;
9580                                 targets [i]->flags |= BB_INDIRECT_JUMP_TARGET;
9581                                 ip += 4;
9582                         }
9583
9584                         if (sp != stack_start) {
9585                                 /* 
9586                                  * Link the current bb with the targets as well, so handle_stack_args
9587                                  * will set their in_stack correctly.
9588                                  */
9589                                 link_bblock (cfg, cfg->cbb, default_bblock);
9590                                 for (i = 0; i < n; ++i)
9591                                         link_bblock (cfg, cfg->cbb, targets [i]);
9592
9593                                 handle_stack_args (cfg, stack_start, sp - stack_start);
9594                                 sp = stack_start;
9595                                 CHECK_UNVERIFIABLE (cfg);
9596
9597                                 /* Undo the links */
9598                                 mono_unlink_bblock (cfg, cfg->cbb, default_bblock);
9599                                 for (i = 0; i < n; ++i)
9600                                         mono_unlink_bblock (cfg, cfg->cbb, targets [i]);
9601                         }
9602
9603                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ICOMPARE_IMM, -1, src1->dreg, n);
9604                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBGE_UN, default_bblock);
9605
9606                         for (i = 0; i < n; ++i)
9607                                 link_bblock (cfg, cfg->cbb, targets [i]);
9608
9609                         table = (MonoJumpInfoBBTable *)mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfoBBTable));
9610                         table->table = targets;
9611                         table->table_size = n;
9612
9613                         use_op_switch = FALSE;
9614 #ifdef TARGET_ARM
9615                         /* ARM implements SWITCH statements differently */
9616                         /* FIXME: Make it use the generic implementation */
9617                         if (!cfg->compile_aot)
9618                                 use_op_switch = TRUE;
9619 #endif
9620
9621                         if (COMPILE_LLVM (cfg))
9622                                 use_op_switch = TRUE;
9623
9624                         cfg->cbb->has_jump_table = 1;
9625
9626                         if (use_op_switch) {
9627                                 MONO_INST_NEW (cfg, ins, OP_SWITCH);
9628                                 ins->sreg1 = src1->dreg;
9629                                 ins->inst_p0 = table;
9630                                 ins->inst_many_bb = targets;
9631                                 ins->klass = (MonoClass *)GUINT_TO_POINTER (n);
9632                                 MONO_ADD_INS (cfg->cbb, ins);
9633                         } else {
9634                                 if (sizeof (gpointer) == 8)
9635                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHL_IMM, offset_reg, src1->dreg, 3);
9636                                 else
9637                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHL_IMM, offset_reg, src1->dreg, 2);
9638
9639 #if SIZEOF_REGISTER == 8
9640                                 /* The upper word might not be zero, and we add it to a 64 bit address later */
9641                                 MONO_EMIT_NEW_UNALU (cfg, OP_ZEXT_I4, offset_reg, offset_reg);
9642 #endif
9643
9644                                 if (cfg->compile_aot) {
9645                                         MONO_EMIT_NEW_AOTCONST (cfg, table_reg, table, MONO_PATCH_INFO_SWITCH);
9646                                 } else {
9647                                         MONO_INST_NEW (cfg, ins, OP_JUMP_TABLE);
9648                                         ins->inst_c1 = MONO_PATCH_INFO_SWITCH;
9649                                         ins->inst_p0 = table;
9650                                         ins->dreg = table_reg;
9651                                         MONO_ADD_INS (cfg->cbb, ins);
9652                                 }
9653
9654                                 /* FIXME: Use load_memindex */
9655                                 MONO_EMIT_NEW_BIALU (cfg, OP_PADD, sum_reg, table_reg, offset_reg);
9656                                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, target_reg, sum_reg, 0);
9657                                 MONO_EMIT_NEW_UNALU (cfg, OP_BR_REG, -1, target_reg);
9658                         }
9659                         start_new_bblock = 1;
9660                         inline_costs += (BRANCH_COST * 2);
9661                         break;
9662                 }
9663                 case CEE_LDIND_I1:
9664                 case CEE_LDIND_U1:
9665                 case CEE_LDIND_I2:
9666                 case CEE_LDIND_U2:
9667                 case CEE_LDIND_I4:
9668                 case CEE_LDIND_U4:
9669                 case CEE_LDIND_I8:
9670                 case CEE_LDIND_I:
9671                 case CEE_LDIND_R4:
9672                 case CEE_LDIND_R8:
9673                 case CEE_LDIND_REF:
9674                         CHECK_STACK (1);
9675                         --sp;
9676
9677                         ins = mini_emit_memory_load (cfg, &ldind_to_type (*ip)->byval_arg, sp [0], 0, ins_flag);
9678                         *sp++ = ins;
9679                         ins_flag = 0;
9680                         ++ip;
9681                         break;
9682                 case CEE_STIND_REF:
9683                 case CEE_STIND_I1:
9684                 case CEE_STIND_I2:
9685                 case CEE_STIND_I4:
9686                 case CEE_STIND_I8:
9687                 case CEE_STIND_R4:
9688                 case CEE_STIND_R8:
9689                 case CEE_STIND_I:
9690                         CHECK_STACK (2);
9691                         sp -= 2;
9692
9693                         if (ins_flag & MONO_INST_VOLATILE) {
9694                                 /* Volatile stores have release semantics, see 12.6.7 in Ecma 335 */
9695                                 mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_REL);
9696                         }
9697
9698                         NEW_STORE_MEMBASE (cfg, ins, stind_to_store_membase (*ip), sp [0]->dreg, 0, sp [1]->dreg);
9699                         ins->flags |= ins_flag;
9700                         ins_flag = 0;
9701
9702                         MONO_ADD_INS (cfg->cbb, ins);
9703
9704                         if (cfg->gen_write_barriers && *ip == CEE_STIND_REF && method->wrapper_type != MONO_WRAPPER_WRITE_BARRIER && !MONO_INS_IS_PCONST_NULL (sp [1]))
9705                                 mini_emit_write_barrier (cfg, sp [0], sp [1]);
9706
9707                         inline_costs += 1;
9708                         ++ip;
9709                         break;
9710
9711                 case CEE_MUL:
9712                         CHECK_STACK (2);
9713
9714                         MONO_INST_NEW (cfg, ins, (*ip));
9715                         sp -= 2;
9716                         ins->sreg1 = sp [0]->dreg;
9717                         ins->sreg2 = sp [1]->dreg;
9718                         type_from_op (cfg, ins, sp [0], sp [1]);
9719                         CHECK_TYPE (ins);
9720                         ins->dreg = alloc_dreg ((cfg), (MonoStackType)(ins)->type);
9721
9722                         /* Use the immediate opcodes if possible */
9723                         if ((sp [1]->opcode == OP_ICONST) && mono_arch_is_inst_imm (sp [1]->inst_c0)) {
9724                                 int imm_opcode = mono_op_to_op_imm_noemul (ins->opcode);
9725                                 if (imm_opcode != -1) {
9726                                         ins->opcode = imm_opcode;
9727                                         ins->inst_p1 = (gpointer)(gssize)(sp [1]->inst_c0);
9728                                         ins->sreg2 = -1;
9729
9730                                         NULLIFY_INS (sp [1]);
9731                                 }
9732                         }
9733
9734                         MONO_ADD_INS ((cfg)->cbb, (ins));
9735
9736                         *sp++ = mono_decompose_opcode (cfg, ins);
9737                         ip++;
9738                         break;
9739                 case CEE_ADD:
9740                 case CEE_SUB:
9741                 case CEE_DIV:
9742                 case CEE_DIV_UN:
9743                 case CEE_REM:
9744                 case CEE_REM_UN:
9745                 case CEE_AND:
9746                 case CEE_OR:
9747                 case CEE_XOR:
9748                 case CEE_SHL:
9749                 case CEE_SHR:
9750                 case CEE_SHR_UN:
9751                         CHECK_STACK (2);
9752
9753                         MONO_INST_NEW (cfg, ins, (*ip));
9754                         sp -= 2;
9755                         ins->sreg1 = sp [0]->dreg;
9756                         ins->sreg2 = sp [1]->dreg;
9757                         type_from_op (cfg, ins, sp [0], sp [1]);
9758                         CHECK_TYPE (ins);
9759                         add_widen_op (cfg, ins, &sp [0], &sp [1]);
9760                         ins->dreg = alloc_dreg ((cfg), (MonoStackType)(ins)->type);
9761
9762                         /* FIXME: Pass opcode to is_inst_imm */
9763
9764                         /* Use the immediate opcodes if possible */
9765                         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)) {
9766                                 int imm_opcode = mono_op_to_op_imm_noemul (ins->opcode);
9767                                 if (imm_opcode != -1) {
9768                                         ins->opcode = imm_opcode;
9769                                         if (sp [1]->opcode == OP_I8CONST) {
9770 #if SIZEOF_REGISTER == 8
9771                                                 ins->inst_imm = sp [1]->inst_l;
9772 #else
9773                                                 ins->inst_ls_word = sp [1]->inst_ls_word;
9774                                                 ins->inst_ms_word = sp [1]->inst_ms_word;
9775 #endif
9776                                         }
9777                                         else
9778                                                 ins->inst_imm = (gssize)(sp [1]->inst_c0);
9779                                         ins->sreg2 = -1;
9780
9781                                         /* Might be followed by an instruction added by add_widen_op */
9782                                         if (sp [1]->next == NULL)
9783                                                 NULLIFY_INS (sp [1]);
9784                                 }
9785                         }
9786                         MONO_ADD_INS ((cfg)->cbb, (ins));
9787
9788                         *sp++ = mono_decompose_opcode (cfg, ins);
9789                         ip++;
9790                         break;
9791                 case CEE_NEG:
9792                 case CEE_NOT:
9793                 case CEE_CONV_I1:
9794                 case CEE_CONV_I2:
9795                 case CEE_CONV_I4:
9796                 case CEE_CONV_R4:
9797                 case CEE_CONV_R8:
9798                 case CEE_CONV_U4:
9799                 case CEE_CONV_I8:
9800                 case CEE_CONV_U8:
9801                 case CEE_CONV_OVF_I8:
9802                 case CEE_CONV_OVF_U8:
9803                 case CEE_CONV_R_UN:
9804                         CHECK_STACK (1);
9805
9806                         /* Special case this earlier so we have long constants in the IR */
9807                         if ((((*ip) == CEE_CONV_I8) || ((*ip) == CEE_CONV_U8)) && (sp [-1]->opcode == OP_ICONST)) {
9808                                 int data = sp [-1]->inst_c0;
9809                                 sp [-1]->opcode = OP_I8CONST;
9810                                 sp [-1]->type = STACK_I8;
9811 #if SIZEOF_REGISTER == 8
9812                                 if ((*ip) == CEE_CONV_U8)
9813                                         sp [-1]->inst_c0 = (guint32)data;
9814                                 else
9815                                         sp [-1]->inst_c0 = data;
9816 #else
9817                                 sp [-1]->inst_ls_word = data;
9818                                 if ((*ip) == CEE_CONV_U8)
9819                                         sp [-1]->inst_ms_word = 0;
9820                                 else
9821                                         sp [-1]->inst_ms_word = (data < 0) ? -1 : 0;
9822 #endif
9823                                 sp [-1]->dreg = alloc_dreg (cfg, STACK_I8);
9824                         }
9825                         else {
9826                                 ADD_UNOP (*ip);
9827                         }
9828                         ip++;
9829                         break;
9830                 case CEE_CONV_OVF_I4:
9831                 case CEE_CONV_OVF_I1:
9832                 case CEE_CONV_OVF_I2:
9833                 case CEE_CONV_OVF_I:
9834                 case CEE_CONV_OVF_U:
9835                         CHECK_STACK (1);
9836
9837                         if (sp [-1]->type == STACK_R8 || sp [-1]->type == STACK_R4) {
9838                                 ADD_UNOP (CEE_CONV_OVF_I8);
9839                                 ADD_UNOP (*ip);
9840                         } else {
9841                                 ADD_UNOP (*ip);
9842                         }
9843                         ip++;
9844                         break;
9845                 case CEE_CONV_OVF_U1:
9846                 case CEE_CONV_OVF_U2:
9847                 case CEE_CONV_OVF_U4:
9848                         CHECK_STACK (1);
9849
9850                         if (sp [-1]->type == STACK_R8 || sp [-1]->type == STACK_R4) {
9851                                 ADD_UNOP (CEE_CONV_OVF_U8);
9852                                 ADD_UNOP (*ip);
9853                         } else {
9854                                 ADD_UNOP (*ip);
9855                         }
9856                         ip++;
9857                         break;
9858                 case CEE_CONV_OVF_I1_UN:
9859                 case CEE_CONV_OVF_I2_UN:
9860                 case CEE_CONV_OVF_I4_UN:
9861                 case CEE_CONV_OVF_I8_UN:
9862                 case CEE_CONV_OVF_U1_UN:
9863                 case CEE_CONV_OVF_U2_UN:
9864                 case CEE_CONV_OVF_U4_UN:
9865                 case CEE_CONV_OVF_U8_UN:
9866                 case CEE_CONV_OVF_I_UN:
9867                 case CEE_CONV_OVF_U_UN:
9868                 case CEE_CONV_U2:
9869                 case CEE_CONV_U1:
9870                 case CEE_CONV_I:
9871                 case CEE_CONV_U:
9872                         CHECK_STACK (1);
9873                         ADD_UNOP (*ip);
9874                         CHECK_CFG_EXCEPTION;
9875                         ip++;
9876                         break;
9877                 case CEE_ADD_OVF:
9878                 case CEE_ADD_OVF_UN:
9879                 case CEE_MUL_OVF:
9880                 case CEE_MUL_OVF_UN:
9881                 case CEE_SUB_OVF:
9882                 case CEE_SUB_OVF_UN:
9883                         CHECK_STACK (2);
9884                         ADD_BINOP (*ip);
9885                         ip++;
9886                         break;
9887                 case CEE_CPOBJ:
9888                         GSHAREDVT_FAILURE (*ip);
9889                         CHECK_OPSIZE (5);
9890                         CHECK_STACK (2);
9891                         token = read32 (ip + 1);
9892                         klass = mini_get_class (method, token, generic_context);
9893                         CHECK_TYPELOAD (klass);
9894                         sp -= 2;
9895                         if (generic_class_is_reference_type (cfg, klass)) {
9896                                 MonoInst *store, *load;
9897                                 int dreg = alloc_ireg_ref (cfg);
9898
9899                                 NEW_LOAD_MEMBASE (cfg, load, OP_LOAD_MEMBASE, dreg, sp [1]->dreg, 0);
9900                                 load->flags |= ins_flag;
9901                                 MONO_ADD_INS (cfg->cbb, load);
9902
9903                                 NEW_STORE_MEMBASE (cfg, store, OP_STORE_MEMBASE_REG, sp [0]->dreg, 0, dreg);
9904                                 store->flags |= ins_flag;
9905                                 MONO_ADD_INS (cfg->cbb, store);
9906
9907                                 if (cfg->gen_write_barriers && cfg->method->wrapper_type != MONO_WRAPPER_WRITE_BARRIER)
9908                                         mini_emit_write_barrier (cfg, sp [0], sp [1]);
9909                         } else {
9910                                 mini_emit_stobj (cfg, sp [0], sp [1], klass, FALSE);
9911                         }
9912                         ins_flag = 0;
9913                         ip += 5;
9914                         break;
9915                 case CEE_LDOBJ: {
9916                         int loc_index = -1;
9917                         int stloc_len = 0;
9918
9919                         CHECK_OPSIZE (5);
9920                         CHECK_STACK (1);
9921                         --sp;
9922                         token = read32 (ip + 1);
9923                         klass = mini_get_class (method, token, generic_context);
9924                         CHECK_TYPELOAD (klass);
9925
9926                         /* Optimize the common ldobj+stloc combination */
9927                         switch (ip [5]) {
9928                         case CEE_STLOC_S:
9929                                 loc_index = ip [6];
9930                                 stloc_len = 2;
9931                                 break;
9932                         case CEE_STLOC_0:
9933                         case CEE_STLOC_1:
9934                         case CEE_STLOC_2:
9935                         case CEE_STLOC_3:
9936                                 loc_index = ip [5] - CEE_STLOC_0;
9937                                 stloc_len = 1;
9938                                 break;
9939                         default:
9940                                 break;
9941                         }
9942
9943                         if ((loc_index != -1) && ip_in_bb (cfg, cfg->cbb, ip + 5)) {
9944                                 CHECK_LOCAL (loc_index);
9945
9946                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, sp [0]->dreg, 0);
9947                                 ins->dreg = cfg->locals [loc_index]->dreg;
9948                                 ins->flags |= ins_flag;
9949                                 ip += 5;
9950                                 ip += stloc_len;
9951                                 if (ins_flag & MONO_INST_VOLATILE) {
9952                                         /* Volatile loads have acquire semantics, see 12.6.7 in Ecma 335 */
9953                                         mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_ACQ);
9954                                 }
9955                                 ins_flag = 0;
9956                                 break;
9957                         }
9958
9959                         /* Optimize the ldobj+stobj combination */
9960                         /* The reference case ends up being a load+store anyway */
9961                         /* Skip this if the operation is volatile. */
9962                         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)) {
9963                                 CHECK_STACK (1);
9964
9965                                 sp --;
9966
9967                                 mini_emit_stobj (cfg, sp [0], sp [1], klass, FALSE);
9968
9969                                 ip += 5 + 5;
9970                                 ins_flag = 0;
9971                                 break;
9972                         }
9973
9974                         ins = mini_emit_memory_load (cfg, &klass->byval_arg, sp [0], 0, ins_flag);
9975                         *sp++ = ins;
9976
9977                         ip += 5;
9978                         ins_flag = 0;
9979                         inline_costs += 1;
9980                         break;
9981                 }
9982                 case CEE_LDSTR:
9983                         CHECK_STACK_OVF (1);
9984                         CHECK_OPSIZE (5);
9985                         n = read32 (ip + 1);
9986
9987                         if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
9988                                 EMIT_NEW_PCONST (cfg, ins, mono_method_get_wrapper_data (method, n));
9989                                 ins->type = STACK_OBJ;
9990                                 *sp = ins;
9991                         }
9992                         else if (method->wrapper_type != MONO_WRAPPER_NONE) {
9993                                 MonoInst *iargs [1];
9994                                 char *str = (char *)mono_method_get_wrapper_data (method, n);
9995
9996                                 if (cfg->compile_aot)
9997                                         EMIT_NEW_LDSTRLITCONST (cfg, iargs [0], str);
9998                                 else
9999                                         EMIT_NEW_PCONST (cfg, iargs [0], str);
10000                                 *sp = mono_emit_jit_icall (cfg, mono_string_new_wrapper, iargs);
10001                         } else {
10002                                 if (cfg->opt & MONO_OPT_SHARED) {
10003                                         MonoInst *iargs [3];
10004
10005                                         if (cfg->compile_aot) {
10006                                                 cfg->ldstr_list = g_list_prepend (cfg->ldstr_list, GINT_TO_POINTER (n));
10007                                         }
10008                                         EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
10009                                         EMIT_NEW_IMAGECONST (cfg, iargs [1], image);
10010                                         EMIT_NEW_ICONST (cfg, iargs [2], mono_metadata_token_index (n));
10011                                         *sp = mono_emit_jit_icall (cfg, ves_icall_mono_ldstr, iargs);
10012                                         mono_ldstr_checked (cfg->domain, image, mono_metadata_token_index (n), &cfg->error);
10013                                         CHECK_CFG_ERROR;
10014                                 } else {
10015                                         if (cfg->cbb->out_of_line) {
10016                                                 MonoInst *iargs [2];
10017
10018                                                 if (image == mono_defaults.corlib) {
10019                                                         /* 
10020                                                          * Avoid relocations in AOT and save some space by using a 
10021                                                          * version of helper_ldstr specialized to mscorlib.
10022                                                          */
10023                                                         EMIT_NEW_ICONST (cfg, iargs [0], mono_metadata_token_index (n));
10024                                                         *sp = mono_emit_jit_icall (cfg, mono_helper_ldstr_mscorlib, iargs);
10025                                                 } else {
10026                                                         /* Avoid creating the string object */
10027                                                         EMIT_NEW_IMAGECONST (cfg, iargs [0], image);
10028                                                         EMIT_NEW_ICONST (cfg, iargs [1], mono_metadata_token_index (n));
10029                                                         *sp = mono_emit_jit_icall (cfg, mono_helper_ldstr, iargs);
10030                                                 }
10031                                         } 
10032                                         else
10033                                         if (cfg->compile_aot) {
10034                                                 NEW_LDSTRCONST (cfg, ins, image, n);
10035                                                 *sp = ins;
10036                                                 MONO_ADD_INS (cfg->cbb, ins);
10037                                         } 
10038                                         else {
10039                                                 NEW_PCONST (cfg, ins, NULL);
10040                                                 ins->type = STACK_OBJ;
10041                                                 ins->inst_p0 = mono_ldstr_checked (cfg->domain, image, mono_metadata_token_index (n), &cfg->error);
10042                                                 CHECK_CFG_ERROR;
10043                                                 
10044                                                 if (!ins->inst_p0)
10045                                                         OUT_OF_MEMORY_FAILURE;
10046
10047                                                 *sp = ins;
10048                                                 MONO_ADD_INS (cfg->cbb, ins);
10049                                         }
10050                                 }
10051                         }
10052
10053                         sp++;
10054                         ip += 5;
10055                         break;
10056                 case CEE_NEWOBJ: {
10057                         MonoInst *iargs [2];
10058                         MonoMethodSignature *fsig;
10059                         MonoInst this_ins;
10060                         MonoInst *alloc;
10061                         MonoInst *vtable_arg = NULL;
10062
10063                         CHECK_OPSIZE (5);
10064                         token = read32 (ip + 1);
10065                         cmethod = mini_get_method (cfg, method, token, NULL, generic_context);
10066                         CHECK_CFG_ERROR;
10067
10068                         fsig = mono_method_get_signature_checked (cmethod, image, token, generic_context, &cfg->error);
10069                         CHECK_CFG_ERROR;
10070
10071                         mono_save_token_info (cfg, image, token, cmethod);
10072
10073                         if (!mono_class_init (cmethod->klass))
10074                                 TYPE_LOAD_ERROR (cmethod->klass);
10075
10076                         context_used = mini_method_check_context_used (cfg, cmethod);
10077                                         
10078                         if (!dont_verify && !cfg->skip_visibility) {
10079                                 MonoMethod *cil_method = cmethod;
10080                                 MonoMethod *target_method = cil_method;
10081
10082                                 if (method->is_inflated) {
10083                                         target_method = mini_get_method_allow_open (method, token, NULL, &(mono_method_get_generic_container (method_definition)->context), &cfg->error);
10084                                         CHECK_CFG_ERROR;
10085                                 }
10086                                 
10087                                 if (!mono_method_can_access_method (method_definition, target_method) &&
10088                                         !mono_method_can_access_method (method, cil_method))
10089                                         emit_method_access_failure (cfg, method, cil_method);
10090                         }
10091
10092                         if (mono_security_core_clr_enabled ())
10093                                 ensure_method_is_allowed_to_call_method (cfg, method, cmethod);
10094
10095                         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)) {
10096                                 emit_class_init (cfg, cmethod->klass);
10097                                 CHECK_TYPELOAD (cmethod->klass);
10098                         }
10099
10100                         /*
10101                         if (cfg->gsharedvt) {
10102                                 if (mini_is_gsharedvt_variable_signature (sig))
10103                                         GSHAREDVT_FAILURE (*ip);
10104                         }
10105                         */
10106
10107                         n = fsig->param_count;
10108                         CHECK_STACK (n);
10109
10110                         /* 
10111                          * Generate smaller code for the common newobj <exception> instruction in
10112                          * argument checking code.
10113                          */
10114                         if (cfg->cbb->out_of_line && cmethod->klass->image == mono_defaults.corlib &&
10115                                 is_exception_class (cmethod->klass) && n <= 2 &&
10116                                 ((n < 1) || (!fsig->params [0]->byref && fsig->params [0]->type == MONO_TYPE_STRING)) && 
10117                                 ((n < 2) || (!fsig->params [1]->byref && fsig->params [1]->type == MONO_TYPE_STRING))) {
10118                                 MonoInst *iargs [3];
10119
10120                                 sp -= n;
10121
10122                                 EMIT_NEW_ICONST (cfg, iargs [0], cmethod->klass->type_token);
10123                                 switch (n) {
10124                                 case 0:
10125                                         *sp ++ = mono_emit_jit_icall (cfg, mono_create_corlib_exception_0, iargs);
10126                                         break;
10127                                 case 1:
10128                                         iargs [1] = sp [0];
10129                                         *sp ++ = mono_emit_jit_icall (cfg, mono_create_corlib_exception_1, iargs);
10130                                         break;
10131                                 case 2:
10132                                         iargs [1] = sp [0];
10133                                         iargs [2] = sp [1];
10134                                         *sp ++ = mono_emit_jit_icall (cfg, mono_create_corlib_exception_2, iargs);
10135                                         break;
10136                                 default:
10137                                         g_assert_not_reached ();
10138                                 }
10139
10140                                 ip += 5;
10141                                 inline_costs += 5;
10142                                 break;
10143                         }
10144
10145                         /* move the args to allow room for 'this' in the first position */
10146                         while (n--) {
10147                                 --sp;
10148                                 sp [1] = sp [0];
10149                         }
10150
10151                         /* check_call_signature () requires sp[0] to be set */
10152                         this_ins.type = STACK_OBJ;
10153                         sp [0] = &this_ins;
10154                         if (check_call_signature (cfg, fsig, sp))
10155                                 UNVERIFIED;
10156
10157                         iargs [0] = NULL;
10158
10159                         if (mini_class_is_system_array (cmethod->klass)) {
10160                                 *sp = emit_get_rgctx_method (cfg, context_used,
10161                                                                                          cmethod, MONO_RGCTX_INFO_METHOD);
10162
10163                                 /* Avoid varargs in the common case */
10164                                 if (fsig->param_count == 1)
10165                                         alloc = mono_emit_jit_icall (cfg, mono_array_new_1, sp);
10166                                 else if (fsig->param_count == 2)
10167                                         alloc = mono_emit_jit_icall (cfg, mono_array_new_2, sp);
10168                                 else if (fsig->param_count == 3)
10169                                         alloc = mono_emit_jit_icall (cfg, mono_array_new_3, sp);
10170                                 else if (fsig->param_count == 4)
10171                                         alloc = mono_emit_jit_icall (cfg, mono_array_new_4, sp);
10172                                 else
10173                                         alloc = handle_array_new (cfg, fsig->param_count, sp, ip);
10174                         } else if (cmethod->string_ctor) {
10175                                 g_assert (!context_used);
10176                                 g_assert (!vtable_arg);
10177                                 /* we simply pass a null pointer */
10178                                 EMIT_NEW_PCONST (cfg, *sp, NULL); 
10179                                 /* now call the string ctor */
10180                                 alloc = mono_emit_method_call_full (cfg, cmethod, fsig, FALSE, sp, NULL, NULL, NULL);
10181                         } else {
10182                                 if (cmethod->klass->valuetype) {
10183                                         iargs [0] = mono_compile_create_var (cfg, &cmethod->klass->byval_arg, OP_LOCAL);
10184                                         emit_init_rvar (cfg, iargs [0]->dreg, &cmethod->klass->byval_arg);
10185                                         EMIT_NEW_TEMPLOADA (cfg, *sp, iargs [0]->inst_c0);
10186
10187                                         alloc = NULL;
10188
10189                                         /* 
10190                                          * The code generated by mini_emit_virtual_call () expects
10191                                          * iargs [0] to be a boxed instance, but luckily the vcall
10192                                          * will be transformed into a normal call there.
10193                                          */
10194                                 } else if (context_used) {
10195                                         alloc = handle_alloc (cfg, cmethod->klass, FALSE, context_used);
10196                                         *sp = alloc;
10197                                 } else {
10198                                         MonoVTable *vtable = NULL;
10199
10200                                         if (!cfg->compile_aot)
10201                                                 vtable = mono_class_vtable (cfg->domain, cmethod->klass);
10202                                         CHECK_TYPELOAD (cmethod->klass);
10203
10204                                         /*
10205                                          * TypeInitializationExceptions thrown from the mono_runtime_class_init
10206                                          * call in mono_jit_runtime_invoke () can abort the finalizer thread.
10207                                          * As a workaround, we call class cctors before allocating objects.
10208                                          */
10209                                         if (mini_field_access_needs_cctor_run (cfg, method, cmethod->klass, vtable) && !(g_slist_find (class_inits, cmethod->klass))) {
10210                                                 emit_class_init (cfg, cmethod->klass);
10211                                                 if (cfg->verbose_level > 2)
10212                                                         printf ("class %s.%s needs init call for ctor\n", cmethod->klass->name_space, cmethod->klass->name);
10213                                                 class_inits = g_slist_prepend (class_inits, cmethod->klass);
10214                                         }
10215
10216                                         alloc = handle_alloc (cfg, cmethod->klass, FALSE, 0);
10217                                         *sp = alloc;
10218                                 }
10219                                 CHECK_CFG_EXCEPTION; /*for handle_alloc*/
10220
10221                                 if (alloc)
10222                                         MONO_EMIT_NEW_UNALU (cfg, OP_NOT_NULL, -1, alloc->dreg);
10223
10224                                 /* Now call the actual ctor */
10225                                 handle_ctor_call (cfg, cmethod, fsig, context_used, sp, ip, &inline_costs);
10226                                 CHECK_CFG_EXCEPTION;
10227                         }
10228
10229                         if (alloc == NULL) {
10230                                 /* Valuetype */
10231                                 EMIT_NEW_TEMPLOAD (cfg, ins, iargs [0]->inst_c0);
10232                                 type_to_eval_stack_type (cfg, &ins->klass->byval_arg, ins);
10233                                 *sp++= ins;
10234                         } else {
10235                                 *sp++ = alloc;
10236                         }
10237                         
10238                         ip += 5;
10239                         inline_costs += 5;
10240                         if (!(seq_point_locs && mono_bitset_test_fast (seq_point_locs, ip - header->code)))
10241                                 emit_seq_point (cfg, method, ip, FALSE, TRUE);
10242                         break;
10243                 }
10244                 case CEE_CASTCLASS:
10245                 case CEE_ISINST: {
10246                         CHECK_STACK (1);
10247                         --sp;
10248                         CHECK_OPSIZE (5);
10249                         token = read32 (ip + 1);
10250                         klass = mini_get_class (method, token, generic_context);
10251                         CHECK_TYPELOAD (klass);
10252                         if (sp [0]->type != STACK_OBJ)
10253                                 UNVERIFIED;
10254
10255                         MONO_INST_NEW (cfg, ins, *ip == CEE_ISINST ? OP_ISINST : OP_CASTCLASS);
10256                         ins->dreg = alloc_preg (cfg);
10257                         ins->sreg1 = (*sp)->dreg;
10258                         ins->klass = klass;
10259                         ins->type = STACK_OBJ;
10260                         MONO_ADD_INS (cfg->cbb, ins);
10261
10262                         CHECK_CFG_EXCEPTION;
10263                         *sp++ = ins;
10264                         ip += 5;
10265
10266                         cfg->flags |= MONO_CFG_HAS_TYPE_CHECK;
10267                         break;
10268                 }
10269                 case CEE_UNBOX_ANY: {
10270                         MonoInst *res, *addr;
10271
10272                         CHECK_STACK (1);
10273                         --sp;
10274                         CHECK_OPSIZE (5);
10275                         token = read32 (ip + 1);
10276                         klass = mini_get_class (method, token, generic_context);
10277                         CHECK_TYPELOAD (klass);
10278
10279                         mono_save_token_info (cfg, image, token, klass);
10280
10281                         context_used = mini_class_check_context_used (cfg, klass);
10282
10283                         if (mini_is_gsharedvt_klass (klass)) {
10284                                 res = handle_unbox_gsharedvt (cfg, klass, *sp);
10285                                 inline_costs += 2;
10286                         } else if (generic_class_is_reference_type (cfg, klass)) {
10287                                 if (MONO_INS_IS_PCONST_NULL (*sp)) {
10288                                         EMIT_NEW_PCONST (cfg, res, NULL);
10289                                         res->type = STACK_OBJ;
10290                                 } else {
10291                                         MONO_INST_NEW (cfg, res, OP_CASTCLASS);
10292                                         res->dreg = alloc_preg (cfg);
10293                                         res->sreg1 = (*sp)->dreg;
10294                                         res->klass = klass;
10295                                         res->type = STACK_OBJ;
10296                                         MONO_ADD_INS (cfg->cbb, res);
10297                                         cfg->flags |= MONO_CFG_HAS_TYPE_CHECK;
10298                                 }
10299                         } else if (mono_class_is_nullable (klass)) {
10300                                 res = handle_unbox_nullable (cfg, *sp, klass, context_used);
10301                         } else {
10302                                 addr = handle_unbox (cfg, klass, sp, context_used);
10303                                 /* LDOBJ */
10304                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr->dreg, 0);
10305                                 res = ins;
10306                                 inline_costs += 2;
10307                         }
10308
10309                         *sp ++ = res;
10310                         ip += 5;
10311                         break;
10312                 }
10313                 case CEE_BOX: {
10314                         MonoInst *val;
10315                         MonoClass *enum_class;
10316                         MonoMethod *has_flag;
10317
10318                         CHECK_STACK (1);
10319                         --sp;
10320                         val = *sp;
10321                         CHECK_OPSIZE (5);
10322                         token = read32 (ip + 1);
10323                         klass = mini_get_class (method, token, generic_context);
10324                         CHECK_TYPELOAD (klass);
10325
10326                         mono_save_token_info (cfg, image, token, klass);
10327
10328                         context_used = mini_class_check_context_used (cfg, klass);
10329
10330                         if (generic_class_is_reference_type (cfg, klass)) {
10331                                 *sp++ = val;
10332                                 ip += 5;
10333                                 break;
10334                         }
10335
10336                         if (klass == mono_defaults.void_class)
10337                                 UNVERIFIED;
10338                         if (target_type_is_incompatible (cfg, &klass->byval_arg, *sp))
10339                                 UNVERIFIED;
10340                         /* frequent check in generic code: box (struct), brtrue */
10341
10342                         /*
10343                          * Look for:
10344                          *
10345                          *   <push int/long ptr>
10346                          *   <push int/long>
10347                          *   box MyFlags
10348                          *   constrained. MyFlags
10349                          *   callvirt instace bool class [mscorlib] System.Enum::HasFlag (class [mscorlib] System.Enum)
10350                          *
10351                          * If we find this sequence and the operand types on box and constrained
10352                          * are equal, we can emit a specialized instruction sequence instead of
10353                          * the very slow HasFlag () call.
10354                          */
10355                         if ((cfg->opt & MONO_OPT_INTRINS) &&
10356                             /* Cheap checks first. */
10357                             ip + 5 + 6 + 5 < end &&
10358                             ip [5] == CEE_PREFIX1 &&
10359                             ip [6] == CEE_CONSTRAINED_ &&
10360                             ip [11] == CEE_CALLVIRT &&
10361                             ip_in_bb (cfg, cfg->cbb, ip + 5 + 6 + 5) &&
10362                             mono_class_is_enum (klass) &&
10363                             (enum_class = mini_get_class (method, read32 (ip + 7), generic_context)) &&
10364                             (has_flag = mini_get_method (cfg, method, read32 (ip + 12), NULL, generic_context)) &&
10365                             has_flag->klass == mono_defaults.enum_class &&
10366                             !strcmp (has_flag->name, "HasFlag") &&
10367                             has_flag->signature->hasthis &&
10368                             has_flag->signature->param_count == 1) {
10369                                 CHECK_TYPELOAD (enum_class);
10370
10371                                 if (enum_class == klass) {
10372                                         MonoInst *enum_this, *enum_flag;
10373
10374                                         ip += 5 + 6 + 5;
10375                                         --sp;
10376
10377                                         enum_this = sp [0];
10378                                         enum_flag = sp [1];
10379
10380                                         *sp++ = handle_enum_has_flag (cfg, klass, enum_this, enum_flag);
10381                                         break;
10382                                 }
10383                         }
10384
10385                         // FIXME: LLVM can't handle the inconsistent bb linking
10386                         if (!mono_class_is_nullable (klass) &&
10387                                 !mini_is_gsharedvt_klass (klass) &&
10388                                 ip + 5 < end && ip_in_bb (cfg, cfg->cbb, ip + 5) &&
10389                                 (ip [5] == CEE_BRTRUE || 
10390                                  ip [5] == CEE_BRTRUE_S ||
10391                                  ip [5] == CEE_BRFALSE ||
10392                                  ip [5] == CEE_BRFALSE_S)) {
10393                                 gboolean is_true = ip [5] == CEE_BRTRUE || ip [5] == CEE_BRTRUE_S;
10394                                 int dreg;
10395                                 MonoBasicBlock *true_bb, *false_bb;
10396
10397                                 ip += 5;
10398
10399                                 if (cfg->verbose_level > 3) {
10400                                         printf ("converting (in B%d: stack: %d) %s", cfg->cbb->block_num, (int)(sp - stack_start), mono_disasm_code_one (NULL, method, ip, NULL));
10401                                         printf ("<box+brtrue opt>\n");
10402                                 }
10403
10404                                 switch (*ip) {
10405                                 case CEE_BRTRUE_S:
10406                                 case CEE_BRFALSE_S:
10407                                         CHECK_OPSIZE (2);
10408                                         ip++;
10409                                         target = ip + 1 + (signed char)(*ip);
10410                                         ip++;
10411                                         break;
10412                                 case CEE_BRTRUE:
10413                                 case CEE_BRFALSE:
10414                                         CHECK_OPSIZE (5);
10415                                         ip++;
10416                                         target = ip + 4 + (gint)(read32 (ip));
10417                                         ip += 4;
10418                                         break;
10419                                 default:
10420                                         g_assert_not_reached ();
10421                                 }
10422
10423                                 /* 
10424                                  * We need to link both bblocks, since it is needed for handling stack
10425                                  * arguments correctly (See test_0_box_brtrue_opt_regress_81102).
10426                                  * Branching to only one of them would lead to inconsistencies, so
10427                                  * generate an ICONST+BRTRUE, the branch opts will get rid of them.
10428                                  */
10429                                 GET_BBLOCK (cfg, true_bb, target);
10430                                 GET_BBLOCK (cfg, false_bb, ip);
10431
10432                                 mono_link_bblock (cfg, cfg->cbb, true_bb);
10433                                 mono_link_bblock (cfg, cfg->cbb, false_bb);
10434
10435                                 if (sp != stack_start) {
10436                                         handle_stack_args (cfg, stack_start, sp - stack_start);
10437                                         sp = stack_start;
10438                                         CHECK_UNVERIFIABLE (cfg);
10439                                 }
10440
10441                                 if (COMPILE_LLVM (cfg)) {
10442                                         dreg = alloc_ireg (cfg);
10443                                         MONO_EMIT_NEW_ICONST (cfg, dreg, 0);
10444                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, dreg, is_true ? 0 : 1);
10445
10446                                         MONO_EMIT_NEW_BRANCH_BLOCK2 (cfg, OP_IBEQ, true_bb, false_bb);
10447                                 } else {
10448                                         /* The JIT can't eliminate the iconst+compare */
10449                                         MONO_INST_NEW (cfg, ins, OP_BR);
10450                                         ins->inst_target_bb = is_true ? true_bb : false_bb;
10451                                         MONO_ADD_INS (cfg->cbb, ins);
10452                                 }
10453
10454                                 start_new_bblock = 1;
10455                                 break;
10456                         }
10457
10458                         *sp++ = handle_box (cfg, val, klass, context_used);
10459
10460                         CHECK_CFG_EXCEPTION;
10461                         ip += 5;
10462                         inline_costs += 1;
10463                         break;
10464                 }
10465                 case CEE_UNBOX: {
10466                         CHECK_STACK (1);
10467                         --sp;
10468                         CHECK_OPSIZE (5);
10469                         token = read32 (ip + 1);
10470                         klass = mini_get_class (method, token, generic_context);
10471                         CHECK_TYPELOAD (klass);
10472
10473                         mono_save_token_info (cfg, image, token, klass);
10474
10475                         context_used = mini_class_check_context_used (cfg, klass);
10476
10477                         if (mono_class_is_nullable (klass)) {
10478                                 MonoInst *val;
10479
10480                                 val = handle_unbox_nullable (cfg, *sp, klass, context_used);
10481                                 EMIT_NEW_VARLOADA (cfg, ins, get_vreg_to_inst (cfg, val->dreg), &val->klass->byval_arg);
10482
10483                                 *sp++= ins;
10484                         } else {
10485                                 ins = handle_unbox (cfg, klass, sp, context_used);
10486                                 *sp++ = ins;
10487                         }
10488                         ip += 5;
10489                         inline_costs += 2;
10490                         break;
10491                 }
10492                 case CEE_LDFLD:
10493                 case CEE_LDFLDA:
10494                 case CEE_STFLD:
10495                 case CEE_LDSFLD:
10496                 case CEE_LDSFLDA:
10497                 case CEE_STSFLD: {
10498                         MonoClassField *field;
10499 #ifndef DISABLE_REMOTING
10500                         int costs;
10501 #endif
10502                         guint foffset;
10503                         gboolean is_instance;
10504                         int op;
10505                         gpointer addr = NULL;
10506                         gboolean is_special_static;
10507                         MonoType *ftype;
10508                         MonoInst *store_val = NULL;
10509                         MonoInst *thread_ins;
10510
10511                         op = *ip;
10512                         is_instance = (op == CEE_LDFLD || op == CEE_LDFLDA || op == CEE_STFLD);
10513                         if (is_instance) {
10514                                 if (op == CEE_STFLD) {
10515                                         CHECK_STACK (2);
10516                                         sp -= 2;
10517                                         store_val = sp [1];
10518                                 } else {
10519                                         CHECK_STACK (1);
10520                                         --sp;
10521                                 }
10522                                 if (sp [0]->type == STACK_I4 || sp [0]->type == STACK_I8 || sp [0]->type == STACK_R8)
10523                                         UNVERIFIED;
10524                                 if (*ip != CEE_LDFLD && sp [0]->type == STACK_VTYPE)
10525                                         UNVERIFIED;
10526                         } else {
10527                                 if (op == CEE_STSFLD) {
10528                                         CHECK_STACK (1);
10529                                         sp--;
10530                                         store_val = sp [0];
10531                                 }
10532                         }
10533
10534                         CHECK_OPSIZE (5);
10535                         token = read32 (ip + 1);
10536                         if (method->wrapper_type != MONO_WRAPPER_NONE) {
10537                                 field = (MonoClassField *)mono_method_get_wrapper_data (method, token);
10538                                 klass = field->parent;
10539                         }
10540                         else {
10541                                 field = mono_field_from_token_checked (image, token, &klass, generic_context, &cfg->error);
10542                                 CHECK_CFG_ERROR;
10543                         }
10544                         if (!dont_verify && !cfg->skip_visibility && !mono_method_can_access_field (method, field))
10545                                 FIELD_ACCESS_FAILURE (method, field);
10546                         mono_class_init (klass);
10547
10548                         /* if the class is Critical then transparent code cannot access it's fields */
10549                         if (!is_instance && mono_security_core_clr_enabled ())
10550                                 ensure_method_is_allowed_to_access_field (cfg, method, field);
10551
10552                         /* XXX this is technically required but, so far (SL2), no [SecurityCritical] types (not many exists) have
10553                            any visible *instance* field  (in fact there's a single case for a static field in Marshal) XXX
10554                         if (mono_security_core_clr_enabled ())
10555                                 ensure_method_is_allowed_to_access_field (cfg, method, field);
10556                         */
10557
10558                         ftype = mono_field_get_type (field);
10559
10560                         /*
10561                          * LDFLD etc. is usable on static fields as well, so convert those cases to
10562                          * the static case.
10563                          */
10564                         if (is_instance && ftype->attrs & FIELD_ATTRIBUTE_STATIC) {
10565                                 switch (op) {
10566                                 case CEE_LDFLD:
10567                                         op = CEE_LDSFLD;
10568                                         break;
10569                                 case CEE_STFLD:
10570                                         op = CEE_STSFLD;
10571                                         break;
10572                                 case CEE_LDFLDA:
10573                                         op = CEE_LDSFLDA;
10574                                         break;
10575                                 default:
10576                                         g_assert_not_reached ();
10577                                 }
10578                                 is_instance = FALSE;
10579                         }
10580
10581                         context_used = mini_class_check_context_used (cfg, klass);
10582
10583                         /* INSTANCE CASE */
10584
10585                         foffset = klass->valuetype? field->offset - sizeof (MonoObject): field->offset;
10586                         if (op == CEE_STFLD) {
10587                                 if (target_type_is_incompatible (cfg, field->type, sp [1]))
10588                                         UNVERIFIED;
10589 #ifndef DISABLE_REMOTING
10590                                 if ((mono_class_is_marshalbyref (klass) && !MONO_CHECK_THIS (sp [0])) || mono_class_is_contextbound (klass) || klass == mono_defaults.marshalbyrefobject_class) {
10591                                         MonoMethod *stfld_wrapper = mono_marshal_get_stfld_wrapper (field->type); 
10592                                         MonoInst *iargs [5];
10593
10594                                         GSHAREDVT_FAILURE (op);
10595
10596                                         iargs [0] = sp [0];
10597                                         EMIT_NEW_CLASSCONST (cfg, iargs [1], klass);
10598                                         EMIT_NEW_FIELDCONST (cfg, iargs [2], field);
10599                                         EMIT_NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) : 
10600                                                     field->offset);
10601                                         iargs [4] = sp [1];
10602
10603                                         if (cfg->opt & MONO_OPT_INLINE || cfg->compile_aot) {
10604                                                 costs = inline_method (cfg, stfld_wrapper, mono_method_signature (stfld_wrapper), 
10605                                                                                            iargs, ip, cfg->real_offset, TRUE);
10606                                                 CHECK_CFG_EXCEPTION;
10607                                                 g_assert (costs > 0);
10608                                                       
10609                                                 cfg->real_offset += 5;
10610
10611                                                 inline_costs += costs;
10612                                         } else {
10613                                                 mono_emit_method_call (cfg, stfld_wrapper, iargs, NULL);
10614                                         }
10615                                 } else
10616 #endif
10617                                 {
10618                                         MonoInst *store, *wbarrier_ptr_ins = NULL;
10619
10620                                         MONO_EMIT_NULL_CHECK (cfg, sp [0]->dreg);
10621
10622                                         if (ins_flag & MONO_INST_VOLATILE) {
10623                                                 /* Volatile stores have release semantics, see 12.6.7 in Ecma 335 */
10624                                                 mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_REL);
10625                                         }
10626
10627                                         if (mini_is_gsharedvt_klass (klass)) {
10628                                                 MonoInst *offset_ins;
10629
10630                                                 context_used = mini_class_check_context_used (cfg, klass);
10631
10632                                                 offset_ins = emit_get_gsharedvt_info (cfg, field, MONO_RGCTX_INFO_FIELD_OFFSET);
10633                                                 /* The value is offset by 1 */
10634                                                 EMIT_NEW_BIALU_IMM (cfg, ins, OP_PSUB_IMM, offset_ins->dreg, offset_ins->dreg, 1);
10635                                                 dreg = alloc_ireg_mp (cfg);
10636                                                 EMIT_NEW_BIALU (cfg, ins, OP_PADD, dreg, sp [0]->dreg, offset_ins->dreg);
10637                                                 wbarrier_ptr_ins = ins;
10638                                                 /* The decomposition will call mini_emit_stobj () which will emit a wbarrier if needed */
10639                                                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, store, field->type, dreg, 0, sp [1]->dreg);
10640                                         } else {
10641                                                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, store, field->type, sp [0]->dreg, foffset, sp [1]->dreg);
10642                                         }
10643                                         if (sp [0]->opcode != OP_LDADDR)
10644                                                 store->flags |= MONO_INST_FAULT;
10645
10646                                         if (cfg->gen_write_barriers && mini_type_to_stind (cfg, field->type) == CEE_STIND_REF && !MONO_INS_IS_PCONST_NULL (sp [1])) {
10647                                                 if (mini_is_gsharedvt_klass (klass)) {
10648                                                         g_assert (wbarrier_ptr_ins);
10649                                                         mini_emit_write_barrier (cfg, wbarrier_ptr_ins, sp [1]);
10650                                                 } else {
10651                                                         /* insert call to write barrier */
10652                                                         MonoInst *ptr;
10653                                                         int dreg;
10654
10655                                                         dreg = alloc_ireg_mp (cfg);
10656                                                         EMIT_NEW_BIALU_IMM (cfg, ptr, OP_PADD_IMM, dreg, sp [0]->dreg, foffset);
10657                                                         mini_emit_write_barrier (cfg, ptr, sp [1]);
10658                                                 }
10659                                         }
10660
10661                                         store->flags |= ins_flag;
10662                                 }
10663                                 ins_flag = 0;
10664                                 ip += 5;
10665                                 break;
10666                         }
10667
10668 #ifndef DISABLE_REMOTING
10669                         if (is_instance && ((mono_class_is_marshalbyref (klass) && !MONO_CHECK_THIS (sp [0])) || mono_class_is_contextbound (klass) || klass == mono_defaults.marshalbyrefobject_class)) {
10670                                 MonoMethod *wrapper = (op == CEE_LDFLDA) ? mono_marshal_get_ldflda_wrapper (field->type) : mono_marshal_get_ldfld_wrapper (field->type); 
10671                                 MonoInst *iargs [4];
10672
10673                                 GSHAREDVT_FAILURE (op);
10674
10675                                 iargs [0] = sp [0];
10676                                 EMIT_NEW_CLASSCONST (cfg, iargs [1], klass);
10677                                 EMIT_NEW_FIELDCONST (cfg, iargs [2], field);
10678                                 EMIT_NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) : field->offset);
10679                                 if (cfg->opt & MONO_OPT_INLINE || cfg->compile_aot) {
10680                                         costs = inline_method (cfg, wrapper, mono_method_signature (wrapper), 
10681                                                                                    iargs, ip, cfg->real_offset, TRUE);
10682                                         CHECK_CFG_EXCEPTION;
10683                                         g_assert (costs > 0);
10684                                                       
10685                                         cfg->real_offset += 5;
10686
10687                                         *sp++ = iargs [0];
10688
10689                                         inline_costs += costs;
10690                                 } else {
10691                                         ins = mono_emit_method_call (cfg, wrapper, iargs, NULL);
10692                                         *sp++ = ins;
10693                                 }
10694                         } else 
10695 #endif
10696                         if (is_instance) {
10697                                 if (sp [0]->type == STACK_VTYPE) {
10698                                         MonoInst *var;
10699
10700                                         /* Have to compute the address of the variable */
10701
10702                                         var = get_vreg_to_inst (cfg, sp [0]->dreg);
10703                                         if (!var)
10704                                                 var = mono_compile_create_var_for_vreg (cfg, &klass->byval_arg, OP_LOCAL, sp [0]->dreg);
10705                                         else
10706                                                 g_assert (var->klass == klass);
10707                                         
10708                                         EMIT_NEW_VARLOADA (cfg, ins, var, &var->klass->byval_arg);
10709                                         sp [0] = ins;
10710                                 }
10711
10712                                 if (op == CEE_LDFLDA) {
10713                                         if (sp [0]->type == STACK_OBJ) {
10714                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, sp [0]->dreg, 0);
10715                                                 MONO_EMIT_NEW_COND_EXC (cfg, EQ, "NullReferenceException");
10716                                         }
10717
10718                                         dreg = alloc_ireg_mp (cfg);
10719
10720                                         if (mini_is_gsharedvt_klass (klass)) {
10721                                                 MonoInst *offset_ins;
10722
10723                                                 offset_ins = emit_get_gsharedvt_info (cfg, field, MONO_RGCTX_INFO_FIELD_OFFSET);
10724                                                 /* The value is offset by 1 */
10725                                                 EMIT_NEW_BIALU_IMM (cfg, ins, OP_PSUB_IMM, offset_ins->dreg, offset_ins->dreg, 1);
10726                                                 EMIT_NEW_BIALU (cfg, ins, OP_PADD, dreg, sp [0]->dreg, offset_ins->dreg);
10727                                         } else {
10728                                                 EMIT_NEW_BIALU_IMM (cfg, ins, OP_PADD_IMM, dreg, sp [0]->dreg, foffset);
10729                                         }
10730                                         ins->klass = mono_class_from_mono_type (field->type);
10731                                         ins->type = STACK_MP;
10732                                         *sp++ = ins;
10733                                 } else {
10734                                         MonoInst *load;
10735
10736                                         MONO_EMIT_NULL_CHECK (cfg, sp [0]->dreg);
10737
10738                                         if (sp [0]->opcode == OP_LDADDR && klass->simd_type && cfg->opt & MONO_OPT_SIMD) {
10739                                                 ins = mono_emit_simd_field_load (cfg, field, sp [0]);
10740                                                 if (ins) {
10741                                                         *sp++ = ins;
10742                                                         ins_flag = 0;
10743                                                         ip += 5;
10744                                                         break;
10745                                                 }
10746                                         }
10747
10748                                         MonoInst *field_add_inst = sp [0];
10749                                         if (mini_is_gsharedvt_klass (klass)) {
10750                                                 MonoInst *offset_ins;
10751
10752                                                 offset_ins = emit_get_gsharedvt_info (cfg, field, MONO_RGCTX_INFO_FIELD_OFFSET);
10753                                                 /* The value is offset by 1 */
10754                                                 EMIT_NEW_BIALU_IMM (cfg, ins, OP_PSUB_IMM, offset_ins->dreg, offset_ins->dreg, 1);
10755                                                 EMIT_NEW_BIALU (cfg, field_add_inst, OP_PADD, alloc_ireg_mp (cfg), sp [0]->dreg, offset_ins->dreg);
10756                                                 foffset = 0;
10757                                         }
10758
10759                                         load = mini_emit_memory_load (cfg, field->type, field_add_inst, foffset, ins_flag);
10760
10761                                         if (sp [0]->opcode != OP_LDADDR)
10762                                                 load->flags |= MONO_INST_FAULT;
10763                                         *sp++ = load;
10764                                 }
10765                         }
10766
10767                         if (is_instance) {
10768                                 ins_flag = 0;
10769                                 ip += 5;
10770                                 break;
10771                         }
10772
10773                         /* STATIC CASE */
10774                         context_used = mini_class_check_context_used (cfg, klass);
10775
10776                         if (ftype->attrs & FIELD_ATTRIBUTE_LITERAL) {
10777                                 mono_error_set_field_load (&cfg->error, field->parent, field->name, "Using static instructions with literal field");
10778                                 CHECK_CFG_ERROR;
10779                         }
10780
10781                         /* The special_static_fields field is init'd in mono_class_vtable, so it needs
10782                          * to be called here.
10783                          */
10784                         if (!context_used && !(cfg->opt & MONO_OPT_SHARED)) {
10785                                 mono_class_vtable (cfg->domain, klass);
10786                                 CHECK_TYPELOAD (klass);
10787                         }
10788                         mono_domain_lock (cfg->domain);
10789                         if (cfg->domain->special_static_fields)
10790                                 addr = g_hash_table_lookup (cfg->domain->special_static_fields, field);
10791                         mono_domain_unlock (cfg->domain);
10792
10793                         is_special_static = mono_class_field_is_special_static (field);
10794
10795                         if (is_special_static && ((gsize)addr & 0x80000000) == 0)
10796                                 thread_ins = mono_create_tls_get (cfg, TLS_KEY_THREAD);
10797                         else
10798                                 thread_ins = NULL;
10799
10800                         /* Generate IR to compute the field address */
10801                         if (is_special_static && ((gsize)addr & 0x80000000) == 0 && thread_ins && !(cfg->opt & MONO_OPT_SHARED) && !context_used) {
10802                                 /*
10803                                  * Fast access to TLS data
10804                                  * Inline version of get_thread_static_data () in
10805                                  * threads.c.
10806                                  */
10807                                 guint32 offset;
10808                                 int idx, static_data_reg, array_reg, dreg;
10809
10810                                 if (context_used && cfg->gsharedvt && mini_is_gsharedvt_klass (klass))
10811                                         GSHAREDVT_FAILURE (op);
10812
10813                                 static_data_reg = alloc_ireg (cfg);
10814                                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, static_data_reg, thread_ins->dreg, MONO_STRUCT_OFFSET (MonoInternalThread, static_data));
10815
10816                                 if (cfg->compile_aot) {
10817                                         int offset_reg, offset2_reg, idx_reg;
10818
10819                                         /* For TLS variables, this will return the TLS offset */
10820                                         EMIT_NEW_SFLDACONST (cfg, ins, field);
10821                                         offset_reg = ins->dreg;
10822                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_IAND_IMM, offset_reg, offset_reg, 0x7fffffff);
10823                                         idx_reg = alloc_ireg (cfg);
10824                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_IAND_IMM, idx_reg, offset_reg, 0x3f);
10825                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ISHL_IMM, idx_reg, idx_reg, sizeof (gpointer) == 8 ? 3 : 2);
10826                                         MONO_EMIT_NEW_BIALU (cfg, OP_PADD, static_data_reg, static_data_reg, idx_reg);
10827                                         array_reg = alloc_ireg (cfg);
10828                                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, array_reg, static_data_reg, 0);
10829                                         offset2_reg = alloc_ireg (cfg);
10830                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ISHR_UN_IMM, offset2_reg, offset_reg, 6);
10831                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_IAND_IMM, offset2_reg, offset2_reg, 0x1ffffff);
10832                                         dreg = alloc_ireg (cfg);
10833                                         EMIT_NEW_BIALU (cfg, ins, OP_PADD, dreg, array_reg, offset2_reg);
10834                                 } else {
10835                                         offset = (gsize)addr & 0x7fffffff;
10836                                         idx = offset & 0x3f;
10837
10838                                         array_reg = alloc_ireg (cfg);
10839                                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, array_reg, static_data_reg, idx * sizeof (gpointer));
10840                                         dreg = alloc_ireg (cfg);
10841                                         EMIT_NEW_BIALU_IMM (cfg, ins, OP_ADD_IMM, dreg, array_reg, ((offset >> 6) & 0x1ffffff));
10842                                 }
10843                         } else if ((cfg->opt & MONO_OPT_SHARED) ||
10844                                         (cfg->compile_aot && is_special_static) ||
10845                                         (context_used && is_special_static)) {
10846                                 MonoInst *iargs [2];
10847
10848                                 g_assert (field->parent);
10849                                 EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
10850                                 if (context_used) {
10851                                         iargs [1] = emit_get_rgctx_field (cfg, context_used,
10852                                                 field, MONO_RGCTX_INFO_CLASS_FIELD);
10853                                 } else {
10854                                         EMIT_NEW_FIELDCONST (cfg, iargs [1], field);
10855                                 }
10856                                 ins = mono_emit_jit_icall (cfg, mono_class_static_field_address, iargs);
10857                         } else if (context_used) {
10858                                 MonoInst *static_data;
10859
10860                                 /*
10861                                 g_print ("sharing static field access in %s.%s.%s - depth %d offset %d\n",
10862                                         method->klass->name_space, method->klass->name, method->name,
10863                                         depth, field->offset);
10864                                 */
10865
10866                                 if (mono_class_needs_cctor_run (klass, method))
10867                                         emit_class_init (cfg, klass);
10868
10869                                 /*
10870                                  * The pointer we're computing here is
10871                                  *
10872                                  *   super_info.static_data + field->offset
10873                                  */
10874                                 static_data = mini_emit_get_rgctx_klass (cfg, context_used,
10875                                         klass, MONO_RGCTX_INFO_STATIC_DATA);
10876
10877                                 if (mini_is_gsharedvt_klass (klass)) {
10878                                         MonoInst *offset_ins;
10879
10880                                         offset_ins = emit_get_rgctx_field (cfg, context_used, field, MONO_RGCTX_INFO_FIELD_OFFSET);
10881                                         /* The value is offset by 1 */
10882                                         EMIT_NEW_BIALU_IMM (cfg, ins, OP_PSUB_IMM, offset_ins->dreg, offset_ins->dreg, 1);
10883                                         dreg = alloc_ireg_mp (cfg);
10884                                         EMIT_NEW_BIALU (cfg, ins, OP_PADD, dreg, static_data->dreg, offset_ins->dreg);
10885                                 } else if (field->offset == 0) {
10886                                         ins = static_data;
10887                                 } else {
10888                                         int addr_reg = mono_alloc_preg (cfg);
10889                                         EMIT_NEW_BIALU_IMM (cfg, ins, OP_PADD_IMM, addr_reg, static_data->dreg, field->offset);
10890                                 }
10891                         } else if ((cfg->opt & MONO_OPT_SHARED) || (cfg->compile_aot && addr)) {
10892                                 MonoInst *iargs [2];
10893
10894                                 g_assert (field->parent);
10895                                 EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
10896                                 EMIT_NEW_FIELDCONST (cfg, iargs [1], field);
10897                                 ins = mono_emit_jit_icall (cfg, mono_class_static_field_address, iargs);
10898                         } else {
10899                                 MonoVTable *vtable = NULL;
10900
10901                                 if (!cfg->compile_aot)
10902                                         vtable = mono_class_vtable (cfg->domain, klass);
10903                                 CHECK_TYPELOAD (klass);
10904
10905                                 if (!addr) {
10906                                         if (mini_field_access_needs_cctor_run (cfg, method, klass, vtable)) {
10907                                                 if (!(g_slist_find (class_inits, klass))) {
10908                                                         emit_class_init (cfg, klass);
10909                                                         if (cfg->verbose_level > 2)
10910                                                                 printf ("class %s.%s needs init call for %s\n", klass->name_space, klass->name, mono_field_get_name (field));
10911                                                         class_inits = g_slist_prepend (class_inits, klass);
10912                                                 }
10913                                         } else {
10914                                                 if (cfg->run_cctors) {
10915                                                         /* This makes so that inline cannot trigger */
10916                                                         /* .cctors: too many apps depend on them */
10917                                                         /* running with a specific order... */
10918                                                         g_assert (vtable);
10919                                                         if (! vtable->initialized)
10920                                                                 INLINE_FAILURE ("class init");
10921                                                         if (!mono_runtime_class_init_full (vtable, &cfg->error)) {
10922                                                                 mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
10923                                                                 goto exception_exit;
10924                                                         }
10925                                                 }
10926                                         }
10927                                         if (cfg->compile_aot)
10928                                                 EMIT_NEW_SFLDACONST (cfg, ins, field);
10929                                         else {
10930                                                 g_assert (vtable);
10931                                                 addr = (char*)mono_vtable_get_static_field_data (vtable) + field->offset;
10932                                                 g_assert (addr);
10933                                                 EMIT_NEW_PCONST (cfg, ins, addr);
10934                                         }
10935                                 } else {
10936                                         MonoInst *iargs [1];
10937                                         EMIT_NEW_ICONST (cfg, iargs [0], GPOINTER_TO_UINT (addr));
10938                                         ins = mono_emit_jit_icall (cfg, mono_get_special_static_data, iargs);
10939                                 }
10940                         }
10941
10942                         /* Generate IR to do the actual load/store operation */
10943
10944                         if ((op == CEE_STFLD || op == CEE_STSFLD) && (ins_flag & MONO_INST_VOLATILE)) {
10945                                 /* Volatile stores have release semantics, see 12.6.7 in Ecma 335 */
10946                                 mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_REL);
10947                         }
10948
10949                         if (op == CEE_LDSFLDA) {
10950                                 ins->klass = mono_class_from_mono_type (ftype);
10951                                 ins->type = STACK_PTR;
10952                                 *sp++ = ins;
10953                         } else if (op == CEE_STSFLD) {
10954                                 MonoInst *store;
10955
10956                                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, store, ftype, ins->dreg, 0, store_val->dreg);
10957                                 store->flags |= ins_flag;
10958                         } else {
10959                                 gboolean is_const = FALSE;
10960                                 MonoVTable *vtable = NULL;
10961                                 gpointer addr = NULL;
10962
10963                                 if (!context_used) {
10964                                         vtable = mono_class_vtable (cfg->domain, klass);
10965                                         CHECK_TYPELOAD (klass);
10966                                 }
10967                                 if ((ftype->attrs & FIELD_ATTRIBUTE_INIT_ONLY) && (((addr = mono_aot_readonly_field_override (field)) != NULL) ||
10968                                                 (!context_used && !((cfg->opt & MONO_OPT_SHARED) || cfg->compile_aot) && vtable->initialized))) {
10969                                         int ro_type = ftype->type;
10970                                         if (!addr)
10971                                                 addr = (char*)mono_vtable_get_static_field_data (vtable) + field->offset;
10972                                         if (ro_type == MONO_TYPE_VALUETYPE && ftype->data.klass->enumtype) {
10973                                                 ro_type = mono_class_enum_basetype (ftype->data.klass)->type;
10974                                         }
10975
10976                                         GSHAREDVT_FAILURE (op);
10977
10978                                         /* printf ("RO-FIELD %s.%s:%s\n", klass->name_space, klass->name, mono_field_get_name (field));*/
10979                                         is_const = TRUE;
10980                                         switch (ro_type) {
10981                                         case MONO_TYPE_BOOLEAN:
10982                                         case MONO_TYPE_U1:
10983                                                 EMIT_NEW_ICONST (cfg, *sp, *((guint8 *)addr));
10984                                                 sp++;
10985                                                 break;
10986                                         case MONO_TYPE_I1:
10987                                                 EMIT_NEW_ICONST (cfg, *sp, *((gint8 *)addr));
10988                                                 sp++;
10989                                                 break;                                          
10990                                         case MONO_TYPE_CHAR:
10991                                         case MONO_TYPE_U2:
10992                                                 EMIT_NEW_ICONST (cfg, *sp, *((guint16 *)addr));
10993                                                 sp++;
10994                                                 break;
10995                                         case MONO_TYPE_I2:
10996                                                 EMIT_NEW_ICONST (cfg, *sp, *((gint16 *)addr));
10997                                                 sp++;
10998                                                 break;
10999                                                 break;
11000                                         case MONO_TYPE_I4:
11001                                                 EMIT_NEW_ICONST (cfg, *sp, *((gint32 *)addr));
11002                                                 sp++;
11003                                                 break;                                          
11004                                         case MONO_TYPE_U4:
11005                                                 EMIT_NEW_ICONST (cfg, *sp, *((guint32 *)addr));
11006                                                 sp++;
11007                                                 break;
11008                                         case MONO_TYPE_I:
11009                                         case MONO_TYPE_U:
11010                                         case MONO_TYPE_PTR:
11011                                         case MONO_TYPE_FNPTR:
11012                                                 EMIT_NEW_PCONST (cfg, *sp, *((gpointer *)addr));
11013                                                 type_to_eval_stack_type ((cfg), field->type, *sp);
11014                                                 sp++;
11015                                                 break;
11016                                         case MONO_TYPE_STRING:
11017                                         case MONO_TYPE_OBJECT:
11018                                         case MONO_TYPE_CLASS:
11019                                         case MONO_TYPE_SZARRAY:
11020                                         case MONO_TYPE_ARRAY:
11021                                                 if (!mono_gc_is_moving ()) {
11022                                                         EMIT_NEW_PCONST (cfg, *sp, *((gpointer *)addr));
11023                                                         type_to_eval_stack_type ((cfg), field->type, *sp);
11024                                                         sp++;
11025                                                 } else {
11026                                                         is_const = FALSE;
11027                                                 }
11028                                                 break;
11029                                         case MONO_TYPE_I8:
11030                                         case MONO_TYPE_U8:
11031                                                 EMIT_NEW_I8CONST (cfg, *sp, *((gint64 *)addr));
11032                                                 sp++;
11033                                                 break;
11034                                         case MONO_TYPE_R4:
11035                                         case MONO_TYPE_R8:
11036                                         case MONO_TYPE_VALUETYPE:
11037                                         default:
11038                                                 is_const = FALSE;
11039                                                 break;
11040                                         }
11041                                 }
11042
11043                                 if (!is_const) {
11044                                         MonoInst *load;
11045
11046                                         CHECK_STACK_OVF (1);
11047
11048                                         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, load, field->type, ins->dreg, 0);
11049                                         load->flags |= ins_flag;
11050                                         ins_flag = 0;
11051                                         *sp++ = load;
11052                                 }
11053                         }
11054
11055                         if ((op == CEE_LDFLD || op == CEE_LDSFLD) && (ins_flag & MONO_INST_VOLATILE)) {
11056                                 /* Volatile loads have acquire semantics, see 12.6.7 in Ecma 335 */
11057                                 mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_ACQ);
11058                         }
11059
11060                         ins_flag = 0;
11061                         ip += 5;
11062                         break;
11063                 }
11064                 case CEE_STOBJ:
11065                         CHECK_STACK (2);
11066                         sp -= 2;
11067                         CHECK_OPSIZE (5);
11068                         token = read32 (ip + 1);
11069                         klass = mini_get_class (method, token, generic_context);
11070                         CHECK_TYPELOAD (klass);
11071
11072                         /* FIXME: should check item at sp [1] is compatible with the type of the store. */
11073                         mini_emit_memory_store (cfg, &klass->byval_arg, sp [0], sp [1], ins_flag);
11074                         ins_flag = 0;
11075                         ip += 5;
11076                         inline_costs += 1;
11077                         break;
11078
11079                         /*
11080                          * Array opcodes
11081                          */
11082                 case CEE_NEWARR: {
11083                         MonoInst *len_ins;
11084                         const char *data_ptr;
11085                         int data_size = 0;
11086                         guint32 field_token;
11087
11088                         CHECK_STACK (1);
11089                         --sp;
11090
11091                         CHECK_OPSIZE (5);
11092                         token = read32 (ip + 1);
11093
11094                         klass = mini_get_class (method, token, generic_context);
11095                         CHECK_TYPELOAD (klass);
11096                         if (klass->byval_arg.type == MONO_TYPE_VOID)
11097                                 UNVERIFIED;
11098
11099                         context_used = mini_class_check_context_used (cfg, klass);
11100
11101                         if (sp [0]->type == STACK_I8 || (SIZEOF_VOID_P == 8 && sp [0]->type == STACK_PTR)) {
11102                                 MONO_INST_NEW (cfg, ins, OP_LCONV_TO_OVF_U4);
11103                                 ins->sreg1 = sp [0]->dreg;
11104                                 ins->type = STACK_I4;
11105                                 ins->dreg = alloc_ireg (cfg);
11106                                 MONO_ADD_INS (cfg->cbb, ins);
11107                                 *sp = mono_decompose_opcode (cfg, ins);
11108                         }
11109
11110                         if (context_used) {
11111                                 MonoInst *args [3];
11112                                 MonoClass *array_class = mono_array_class_get (klass, 1);
11113                                 MonoMethod *managed_alloc = mono_gc_get_managed_array_allocator (array_class);
11114
11115                                 /* FIXME: Use OP_NEWARR and decompose later to help abcrem */
11116
11117                                 /* vtable */
11118                                 args [0] = mini_emit_get_rgctx_klass (cfg, context_used,
11119                                         array_class, MONO_RGCTX_INFO_VTABLE);
11120                                 /* array len */
11121                                 args [1] = sp [0];
11122
11123                                 if (managed_alloc)
11124                                         ins = mono_emit_method_call (cfg, managed_alloc, args, NULL);
11125                                 else
11126                                         ins = mono_emit_jit_icall (cfg, ves_icall_array_new_specific, args);
11127                         } else {
11128                                 if (cfg->opt & MONO_OPT_SHARED) {
11129                                         /* Decompose now to avoid problems with references to the domainvar */
11130                                         MonoInst *iargs [3];
11131
11132                                         EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
11133                                         EMIT_NEW_CLASSCONST (cfg, iargs [1], klass);
11134                                         iargs [2] = sp [0];
11135
11136                                         ins = mono_emit_jit_icall (cfg, ves_icall_array_new, iargs);
11137                                 } else {
11138                                         /* Decompose later since it is needed by abcrem */
11139                                         MonoClass *array_type = mono_array_class_get (klass, 1);
11140                                         mono_class_vtable (cfg->domain, array_type);
11141                                         CHECK_TYPELOAD (array_type);
11142
11143                                         MONO_INST_NEW (cfg, ins, OP_NEWARR);
11144                                         ins->dreg = alloc_ireg_ref (cfg);
11145                                         ins->sreg1 = sp [0]->dreg;
11146                                         ins->inst_newa_class = klass;
11147                                         ins->type = STACK_OBJ;
11148                                         ins->klass = array_type;
11149                                         MONO_ADD_INS (cfg->cbb, ins);
11150                                         cfg->flags |= MONO_CFG_HAS_ARRAY_ACCESS;
11151                                         cfg->cbb->has_array_access = TRUE;
11152
11153                                         /* Needed so mono_emit_load_get_addr () gets called */
11154                                         mono_get_got_var (cfg);
11155                                 }
11156                         }
11157
11158                         len_ins = sp [0];
11159                         ip += 5;
11160                         *sp++ = ins;
11161                         inline_costs += 1;
11162
11163                         /* 
11164                          * we inline/optimize the initialization sequence if possible.
11165                          * we should also allocate the array as not cleared, since we spend as much time clearing to 0 as initializing
11166                          * for small sizes open code the memcpy
11167                          * ensure the rva field is big enough
11168                          */
11169                         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))) {
11170                                 MonoMethod *memcpy_method = mini_get_memcpy_method ();
11171                                 MonoInst *iargs [3];
11172                                 int add_reg = alloc_ireg_mp (cfg);
11173
11174                                 EMIT_NEW_BIALU_IMM (cfg, iargs [0], OP_PADD_IMM, add_reg, ins->dreg, MONO_STRUCT_OFFSET (MonoArray, vector));
11175                                 if (cfg->compile_aot) {
11176                                         EMIT_NEW_AOTCONST_TOKEN (cfg, iargs [1], MONO_PATCH_INFO_RVA, method->klass->image, GPOINTER_TO_UINT(field_token), STACK_PTR, NULL);
11177                                 } else {
11178                                         EMIT_NEW_PCONST (cfg, iargs [1], (char*)data_ptr);
11179                                 }
11180                                 EMIT_NEW_ICONST (cfg, iargs [2], data_size);
11181                                 mono_emit_method_call (cfg, memcpy_method, iargs, NULL);
11182                                 ip += 11;
11183                         }
11184
11185                         break;
11186                 }
11187                 case CEE_LDLEN:
11188                         CHECK_STACK (1);
11189                         --sp;
11190                         if (sp [0]->type != STACK_OBJ)
11191                                 UNVERIFIED;
11192
11193                         MONO_INST_NEW (cfg, ins, OP_LDLEN);
11194                         ins->dreg = alloc_preg (cfg);
11195                         ins->sreg1 = sp [0]->dreg;
11196                         ins->type = STACK_I4;
11197                         /* This flag will be inherited by the decomposition */
11198                         ins->flags |= MONO_INST_FAULT;
11199                         MONO_ADD_INS (cfg->cbb, ins);
11200                         cfg->flags |= MONO_CFG_HAS_ARRAY_ACCESS;
11201                         cfg->cbb->has_array_access = TRUE;
11202                         ip ++;
11203                         *sp++ = ins;
11204                         break;
11205                 case CEE_LDELEMA:
11206                         CHECK_STACK (2);
11207                         sp -= 2;
11208                         CHECK_OPSIZE (5);
11209                         if (sp [0]->type != STACK_OBJ)
11210                                 UNVERIFIED;
11211
11212                         cfg->flags |= MONO_CFG_HAS_LDELEMA;
11213
11214                         klass = mini_get_class (method, read32 (ip + 1), generic_context);
11215                         CHECK_TYPELOAD (klass);
11216                         /* we need to make sure that this array is exactly the type it needs
11217                          * to be for correctness. the wrappers are lax with their usage
11218                          * so we need to ignore them here
11219                          */
11220                         if (!klass->valuetype && method->wrapper_type == MONO_WRAPPER_NONE && !readonly) {
11221                                 MonoClass *array_class = mono_array_class_get (klass, 1);
11222                                 mini_emit_check_array_type (cfg, sp [0], array_class);
11223                                 CHECK_TYPELOAD (array_class);
11224                         }
11225
11226                         readonly = FALSE;
11227                         ins = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1], TRUE);
11228                         *sp++ = ins;
11229                         ip += 5;
11230                         break;
11231                 case CEE_LDELEM:
11232                 case CEE_LDELEM_I1:
11233                 case CEE_LDELEM_U1:
11234                 case CEE_LDELEM_I2:
11235                 case CEE_LDELEM_U2:
11236                 case CEE_LDELEM_I4:
11237                 case CEE_LDELEM_U4:
11238                 case CEE_LDELEM_I8:
11239                 case CEE_LDELEM_I:
11240                 case CEE_LDELEM_R4:
11241                 case CEE_LDELEM_R8:
11242                 case CEE_LDELEM_REF: {
11243                         MonoInst *addr;
11244
11245                         CHECK_STACK (2);
11246                         sp -= 2;
11247
11248                         if (*ip == CEE_LDELEM) {
11249                                 CHECK_OPSIZE (5);
11250                                 token = read32 (ip + 1);
11251                                 klass = mini_get_class (method, token, generic_context);
11252                                 CHECK_TYPELOAD (klass);
11253                                 mono_class_init (klass);
11254                         }
11255                         else
11256                                 klass = array_access_to_klass (*ip);
11257
11258                         if (sp [0]->type != STACK_OBJ)
11259                                 UNVERIFIED;
11260
11261                         cfg->flags |= MONO_CFG_HAS_LDELEMA;
11262
11263                         if (mini_is_gsharedvt_variable_klass (klass)) {
11264                                 // FIXME-VT: OP_ICONST optimization
11265                                 addr = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1], TRUE);
11266                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr->dreg, 0);
11267                                 ins->opcode = OP_LOADV_MEMBASE;
11268                         } else if (sp [1]->opcode == OP_ICONST) {
11269                                 int array_reg = sp [0]->dreg;
11270                                 int index_reg = sp [1]->dreg;
11271                                 int offset = (mono_class_array_element_size (klass) * sp [1]->inst_c0) + MONO_STRUCT_OFFSET (MonoArray, vector);
11272
11273                                 if (SIZEOF_REGISTER == 8 && COMPILE_LLVM (cfg))
11274                                         MONO_EMIT_NEW_UNALU (cfg, OP_ZEXT_I4, index_reg, index_reg);
11275
11276                                 MONO_EMIT_BOUNDS_CHECK (cfg, array_reg, MonoArray, max_length, index_reg);
11277                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, array_reg, offset);
11278                         } else {
11279                                 addr = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1], TRUE);
11280                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr->dreg, 0);
11281                         }
11282                         *sp++ = ins;
11283                         if (*ip == CEE_LDELEM)
11284                                 ip += 5;
11285                         else
11286                                 ++ip;
11287                         break;
11288                 }
11289                 case CEE_STELEM_I:
11290                 case CEE_STELEM_I1:
11291                 case CEE_STELEM_I2:
11292                 case CEE_STELEM_I4:
11293                 case CEE_STELEM_I8:
11294                 case CEE_STELEM_R4:
11295                 case CEE_STELEM_R8:
11296                 case CEE_STELEM_REF:
11297                 case CEE_STELEM: {
11298                         CHECK_STACK (3);
11299                         sp -= 3;
11300
11301                         cfg->flags |= MONO_CFG_HAS_LDELEMA;
11302
11303                         if (*ip == CEE_STELEM) {
11304                                 CHECK_OPSIZE (5);
11305                                 token = read32 (ip + 1);
11306                                 klass = mini_get_class (method, token, generic_context);
11307                                 CHECK_TYPELOAD (klass);
11308                                 mono_class_init (klass);
11309                         }
11310                         else
11311                                 klass = array_access_to_klass (*ip);
11312
11313                         if (sp [0]->type != STACK_OBJ)
11314                                 UNVERIFIED;
11315
11316                         emit_array_store (cfg, klass, sp, TRUE);
11317
11318                         if (*ip == CEE_STELEM)
11319                                 ip += 5;
11320                         else
11321                                 ++ip;
11322                         inline_costs += 1;
11323                         break;
11324                 }
11325                 case CEE_CKFINITE: {
11326                         CHECK_STACK (1);
11327                         --sp;
11328
11329                         if (cfg->llvm_only) {
11330                                 MonoInst *iargs [1];
11331
11332                                 iargs [0] = sp [0];
11333                                 *sp++ = mono_emit_jit_icall (cfg, mono_ckfinite, iargs);
11334                         } else  {
11335                                 MONO_INST_NEW (cfg, ins, OP_CKFINITE);
11336                                 ins->sreg1 = sp [0]->dreg;
11337                                 ins->dreg = alloc_freg (cfg);
11338                                 ins->type = STACK_R8;
11339                                 MONO_ADD_INS (cfg->cbb, ins);
11340
11341                                 *sp++ = mono_decompose_opcode (cfg, ins);
11342                         }
11343
11344                         ++ip;
11345                         break;
11346                 }
11347                 case CEE_REFANYVAL: {
11348                         MonoInst *src_var, *src;
11349
11350                         int klass_reg = alloc_preg (cfg);
11351                         int dreg = alloc_preg (cfg);
11352
11353                         GSHAREDVT_FAILURE (*ip);
11354
11355                         CHECK_STACK (1);
11356                         MONO_INST_NEW (cfg, ins, *ip);
11357                         --sp;
11358                         CHECK_OPSIZE (5);
11359                         klass = mini_get_class (method, read32 (ip + 1), generic_context);
11360                         CHECK_TYPELOAD (klass);
11361
11362                         context_used = mini_class_check_context_used (cfg, klass);
11363
11364                         // FIXME:
11365                         src_var = get_vreg_to_inst (cfg, sp [0]->dreg);
11366                         if (!src_var)
11367                                 src_var = mono_compile_create_var_for_vreg (cfg, &mono_defaults.typed_reference_class->byval_arg, OP_LOCAL, sp [0]->dreg);
11368                         EMIT_NEW_VARLOADA (cfg, src, src_var, src_var->inst_vtype);
11369                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, src->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, klass));
11370
11371                         if (context_used) {
11372                                 MonoInst *klass_ins;
11373
11374                                 klass_ins = mini_emit_get_rgctx_klass (cfg, context_used,
11375                                                 klass, MONO_RGCTX_INFO_KLASS);
11376
11377                                 // FIXME:
11378                                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, klass_reg, klass_ins->dreg);
11379                                 MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "InvalidCastException");
11380                         } else {
11381                                 mini_emit_class_check (cfg, klass_reg, klass);
11382                         }
11383                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, dreg, src->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, value));
11384                         ins->type = STACK_MP;
11385                         ins->klass = klass;
11386                         *sp++ = ins;
11387                         ip += 5;
11388                         break;
11389                 }
11390                 case CEE_MKREFANY: {
11391                         MonoInst *loc, *addr;
11392
11393                         GSHAREDVT_FAILURE (*ip);
11394
11395                         CHECK_STACK (1);
11396                         MONO_INST_NEW (cfg, ins, *ip);
11397                         --sp;
11398                         CHECK_OPSIZE (5);
11399                         klass = mini_get_class (method, read32 (ip + 1), generic_context);
11400                         CHECK_TYPELOAD (klass);
11401
11402                         context_used = mini_class_check_context_used (cfg, klass);
11403
11404                         loc = mono_compile_create_var (cfg, &mono_defaults.typed_reference_class->byval_arg, OP_LOCAL);
11405                         EMIT_NEW_TEMPLOADA (cfg, addr, loc->inst_c0);
11406
11407                         if (context_used) {
11408                                 MonoInst *const_ins;
11409                                 int type_reg = alloc_preg (cfg);
11410
11411                                 const_ins = mini_emit_get_rgctx_klass (cfg, context_used, klass, MONO_RGCTX_INFO_KLASS);
11412                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, klass), const_ins->dreg);
11413                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ADD_IMM, type_reg, const_ins->dreg, MONO_STRUCT_OFFSET (MonoClass, byval_arg));
11414                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, type), type_reg);
11415                         } else {
11416                                 int const_reg = alloc_preg (cfg);
11417                                 int type_reg = alloc_preg (cfg);
11418
11419                                 MONO_EMIT_NEW_CLASSCONST (cfg, const_reg, klass);
11420                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, klass), const_reg);
11421                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ADD_IMM, type_reg, const_reg, MONO_STRUCT_OFFSET (MonoClass, byval_arg));
11422                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, type), type_reg);
11423                         }
11424                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, value), sp [0]->dreg);
11425
11426                         EMIT_NEW_TEMPLOAD (cfg, ins, loc->inst_c0);
11427                         ins->type = STACK_VTYPE;
11428                         ins->klass = mono_defaults.typed_reference_class;
11429                         *sp++ = ins;
11430                         ip += 5;
11431                         break;
11432                 }
11433                 case CEE_LDTOKEN: {
11434                         gpointer handle;
11435                         MonoClass *handle_class;
11436
11437                         CHECK_STACK_OVF (1);
11438
11439                         CHECK_OPSIZE (5);
11440                         n = read32 (ip + 1);
11441
11442                         if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD ||
11443                                         method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED) {
11444                                 handle = mono_method_get_wrapper_data (method, n);
11445                                 handle_class = (MonoClass *)mono_method_get_wrapper_data (method, n + 1);
11446                                 if (handle_class == mono_defaults.typehandle_class)
11447                                         handle = &((MonoClass*)handle)->byval_arg;
11448                         }
11449                         else {
11450                                 handle = mono_ldtoken_checked (image, n, &handle_class, generic_context, &cfg->error);
11451                                 CHECK_CFG_ERROR;
11452                         }
11453                         if (!handle)
11454                                 LOAD_ERROR;
11455                         mono_class_init (handle_class);
11456                         if (cfg->gshared) {
11457                                 if (mono_metadata_token_table (n) == MONO_TABLE_TYPEDEF ||
11458                                                 mono_metadata_token_table (n) == MONO_TABLE_TYPEREF) {
11459                                         /* This case handles ldtoken
11460                                            of an open type, like for
11461                                            typeof(Gen<>). */
11462                                         context_used = 0;
11463                                 } else if (handle_class == mono_defaults.typehandle_class) {
11464                                         context_used = mini_class_check_context_used (cfg, mono_class_from_mono_type ((MonoType *)handle));
11465                                 } else if (handle_class == mono_defaults.fieldhandle_class)
11466                                         context_used = mini_class_check_context_used (cfg, ((MonoClassField*)handle)->parent);
11467                                 else if (handle_class == mono_defaults.methodhandle_class)
11468                                         context_used = mini_method_check_context_used (cfg, (MonoMethod *)handle);
11469                                 else
11470                                         g_assert_not_reached ();
11471                         }
11472
11473                         if ((cfg->opt & MONO_OPT_SHARED) &&
11474                                         method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD &&
11475                                         method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED) {
11476                                 MonoInst *addr, *vtvar, *iargs [3];
11477                                 int method_context_used;
11478
11479                                 method_context_used = mini_method_check_context_used (cfg, method);
11480
11481                                 vtvar = mono_compile_create_var (cfg, &handle_class->byval_arg, OP_LOCAL); 
11482
11483                                 EMIT_NEW_IMAGECONST (cfg, iargs [0], image);
11484                                 EMIT_NEW_ICONST (cfg, iargs [1], n);
11485                                 if (method_context_used) {
11486                                         iargs [2] = emit_get_rgctx_method (cfg, method_context_used,
11487                                                 method, MONO_RGCTX_INFO_METHOD);
11488                                         ins = mono_emit_jit_icall (cfg, mono_ldtoken_wrapper_generic_shared, iargs);
11489                                 } else {
11490                                         EMIT_NEW_PCONST (cfg, iargs [2], generic_context);
11491                                         ins = mono_emit_jit_icall (cfg, mono_ldtoken_wrapper, iargs);
11492                                 }
11493                                 EMIT_NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
11494
11495                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, addr->dreg, 0, ins->dreg);
11496
11497                                 EMIT_NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
11498                         } else {
11499                                 if ((ip + 5 < end) && ip_in_bb (cfg, cfg->cbb, ip + 5) && 
11500                                         ((ip [5] == CEE_CALL) || (ip [5] == CEE_CALLVIRT)) && 
11501                                         (cmethod = mini_get_method (cfg, method, read32 (ip + 6), NULL, generic_context)) &&
11502                                         (cmethod->klass == mono_defaults.systemtype_class) &&
11503                                         (strcmp (cmethod->name, "GetTypeFromHandle") == 0)) {
11504                                         MonoClass *tclass = mono_class_from_mono_type ((MonoType *)handle);
11505
11506                                         mono_class_init (tclass);
11507                                         if (context_used) {
11508                                                 ins = mini_emit_get_rgctx_klass (cfg, context_used,
11509                                                         tclass, MONO_RGCTX_INFO_REFLECTION_TYPE);
11510                                         } else if (cfg->compile_aot) {
11511                                                 if (method->wrapper_type) {
11512                                                         error_init (&error); //got to do it since there are multiple conditionals below
11513                                                         if (mono_class_get_checked (tclass->image, tclass->type_token, &error) == tclass && !generic_context) {
11514                                                                 /* Special case for static synchronized wrappers */
11515                                                                 EMIT_NEW_TYPE_FROM_HANDLE_CONST (cfg, ins, tclass->image, tclass->type_token, generic_context);
11516                                                         } else {
11517                                                                 mono_error_cleanup (&error); /* FIXME don't swallow the error */
11518                                                                 /* FIXME: n is not a normal token */
11519                                                                 DISABLE_AOT (cfg);
11520                                                                 EMIT_NEW_PCONST (cfg, ins, NULL);
11521                                                         }
11522                                                 } else {
11523                                                         EMIT_NEW_TYPE_FROM_HANDLE_CONST (cfg, ins, image, n, generic_context);
11524                                                 }
11525                                         } else {
11526                                                 MonoReflectionType *rt = mono_type_get_object_checked (cfg->domain, (MonoType *)handle, &cfg->error);
11527                                                 CHECK_CFG_ERROR;
11528                                                 EMIT_NEW_PCONST (cfg, ins, rt);
11529                                         }
11530                                         ins->type = STACK_OBJ;
11531                                         ins->klass = cmethod->klass;
11532                                         ip += 5;
11533                                 } else {
11534                                         MonoInst *addr, *vtvar;
11535
11536                                         vtvar = mono_compile_create_var (cfg, &handle_class->byval_arg, OP_LOCAL);
11537
11538                                         if (context_used) {
11539                                                 if (handle_class == mono_defaults.typehandle_class) {
11540                                                         ins = mini_emit_get_rgctx_klass (cfg, context_used,
11541                                                                         mono_class_from_mono_type ((MonoType *)handle),
11542                                                                         MONO_RGCTX_INFO_TYPE);
11543                                                 } else if (handle_class == mono_defaults.methodhandle_class) {
11544                                                         ins = emit_get_rgctx_method (cfg, context_used,
11545                                                                         (MonoMethod *)handle, MONO_RGCTX_INFO_METHOD);
11546                                                 } else if (handle_class == mono_defaults.fieldhandle_class) {
11547                                                         ins = emit_get_rgctx_field (cfg, context_used,
11548                                                                         (MonoClassField *)handle, MONO_RGCTX_INFO_CLASS_FIELD);
11549                                                 } else {
11550                                                         g_assert_not_reached ();
11551                                                 }
11552                                         } else if (cfg->compile_aot) {
11553                                                 EMIT_NEW_LDTOKENCONST (cfg, ins, image, n, generic_context);
11554                                         } else {
11555                                                 EMIT_NEW_PCONST (cfg, ins, handle);
11556                                         }
11557                                         EMIT_NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
11558                                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, addr->dreg, 0, ins->dreg);
11559                                         EMIT_NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
11560                                 }
11561                         }
11562
11563                         *sp++ = ins;
11564                         ip += 5;
11565                         break;
11566                 }
11567                 case CEE_THROW:
11568                         CHECK_STACK (1);
11569                         if (sp [-1]->type != STACK_OBJ)
11570                                 UNVERIFIED;
11571
11572                         MONO_INST_NEW (cfg, ins, OP_THROW);
11573                         --sp;
11574                         ins->sreg1 = sp [0]->dreg;
11575                         ip++;
11576                         cfg->cbb->out_of_line = TRUE;
11577                         MONO_ADD_INS (cfg->cbb, ins);
11578                         MONO_INST_NEW (cfg, ins, OP_NOT_REACHED);
11579                         MONO_ADD_INS (cfg->cbb, ins);
11580                         sp = stack_start;
11581                         
11582                         link_bblock (cfg, cfg->cbb, end_bblock);
11583                         start_new_bblock = 1;
11584                         /* This can complicate code generation for llvm since the return value might not be defined */
11585                         if (COMPILE_LLVM (cfg))
11586                                 INLINE_FAILURE ("throw");
11587                         break;
11588                 case CEE_ENDFINALLY:
11589                         if (!ip_in_finally_clause (cfg, ip - header->code))
11590                                 UNVERIFIED;
11591                         /* mono_save_seq_point_info () depends on this */
11592                         if (sp != stack_start)
11593                                 emit_seq_point (cfg, method, ip, FALSE, FALSE);
11594                         MONO_INST_NEW (cfg, ins, OP_ENDFINALLY);
11595                         MONO_ADD_INS (cfg->cbb, ins);
11596                         ip++;
11597                         start_new_bblock = 1;
11598
11599                         /*
11600                          * Control will leave the method so empty the stack, otherwise
11601                          * the next basic block will start with a nonempty stack.
11602                          */
11603                         while (sp != stack_start) {
11604                                 sp--;
11605                         }
11606                         break;
11607                 case CEE_LEAVE:
11608                 case CEE_LEAVE_S: {
11609                         GList *handlers;
11610
11611                         if (*ip == CEE_LEAVE) {
11612                                 CHECK_OPSIZE (5);
11613                                 target = ip + 5 + (gint32)read32(ip + 1);
11614                         } else {
11615                                 CHECK_OPSIZE (2);
11616                                 target = ip + 2 + (signed char)(ip [1]);
11617                         }
11618
11619                         /* empty the stack */
11620                         while (sp != stack_start) {
11621                                 sp--;
11622                         }
11623
11624                         /* 
11625                          * If this leave statement is in a catch block, check for a
11626                          * pending exception, and rethrow it if necessary.
11627                          * We avoid doing this in runtime invoke wrappers, since those are called
11628                          * by native code which excepts the wrapper to catch all exceptions.
11629                          */
11630                         for (i = 0; i < header->num_clauses; ++i) {
11631                                 MonoExceptionClause *clause = &header->clauses [i];
11632
11633                                 /* 
11634                                  * Use <= in the final comparison to handle clauses with multiple
11635                                  * leave statements, like in bug #78024.
11636                                  * The ordering of the exception clauses guarantees that we find the
11637                                  * innermost clause.
11638                                  */
11639                                 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) {
11640                                         MonoInst *exc_ins;
11641                                         MonoBasicBlock *dont_throw;
11642
11643                                         /*
11644                                           MonoInst *load;
11645
11646                                           NEW_TEMPLOAD (cfg, load, mono_find_exvar_for_offset (cfg, clause->handler_offset)->inst_c0);
11647                                         */
11648
11649                                         exc_ins = mono_emit_jit_icall (cfg, mono_thread_get_undeniable_exception, NULL);
11650
11651                                         NEW_BBLOCK (cfg, dont_throw);
11652
11653                                         /*
11654                                          * Currently, we always rethrow the abort exception, despite the 
11655                                          * fact that this is not correct. See thread6.cs for an example. 
11656                                          * But propagating the abort exception is more important than 
11657                                          * getting the sematics right.
11658                                          */
11659                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, exc_ins->dreg, 0);
11660                                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, dont_throw);
11661                                         MONO_EMIT_NEW_UNALU (cfg, OP_THROW, -1, exc_ins->dreg);
11662
11663                                         MONO_START_BB (cfg, dont_throw);
11664                                 }
11665                         }
11666
11667 #ifdef ENABLE_LLVM
11668                         cfg->cbb->try_end = (intptr_t)(ip - header->code);
11669 #endif
11670
11671                         if ((handlers = mono_find_final_block (cfg, ip, target, MONO_EXCEPTION_CLAUSE_FINALLY))) {
11672                                 GList *tmp;
11673                                 MonoExceptionClause *clause;
11674
11675                                 for (tmp = handlers; tmp; tmp = tmp->next) {
11676                                         clause = (MonoExceptionClause *)tmp->data;
11677                                         tblock = cfg->cil_offset_to_bb [clause->handler_offset];
11678                                         g_assert (tblock);
11679                                         link_bblock (cfg, cfg->cbb, tblock);
11680                                         MONO_INST_NEW (cfg, ins, OP_CALL_HANDLER);
11681                                         ins->inst_target_bb = tblock;
11682                                         ins->inst_eh_block = clause;
11683                                         MONO_ADD_INS (cfg->cbb, ins);
11684                                         cfg->cbb->has_call_handler = 1;
11685                                         if (COMPILE_LLVM (cfg)) {
11686                                                 MonoBasicBlock *target_bb;
11687
11688                                                 /* 
11689                                                  * Link the finally bblock with the target, since it will
11690                                                  * conceptually branch there.
11691                                                  */
11692                                                 GET_BBLOCK (cfg, tblock, cfg->cil_start + clause->handler_offset + clause->handler_len - 1);
11693                                                 GET_BBLOCK (cfg, target_bb, target);
11694                                                 link_bblock (cfg, tblock, target_bb);
11695                                         }
11696                                 }
11697                                 g_list_free (handlers);
11698                         } 
11699
11700                         MONO_INST_NEW (cfg, ins, OP_BR);
11701                         MONO_ADD_INS (cfg->cbb, ins);
11702                         GET_BBLOCK (cfg, tblock, target);
11703                         link_bblock (cfg, cfg->cbb, tblock);
11704                         ins->inst_target_bb = tblock;
11705
11706                         start_new_bblock = 1;
11707
11708                         if (*ip == CEE_LEAVE)
11709                                 ip += 5;
11710                         else
11711                                 ip += 2;
11712
11713                         break;
11714                 }
11715
11716                         /*
11717                          * Mono specific opcodes
11718                          */
11719                 case MONO_CUSTOM_PREFIX: {
11720
11721                         g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
11722
11723                         CHECK_OPSIZE (2);
11724                         switch (ip [1]) {
11725                         case CEE_MONO_ICALL: {
11726                                 gpointer func;
11727                                 MonoJitICallInfo *info;
11728
11729                                 token = read32 (ip + 2);
11730                                 func = mono_method_get_wrapper_data (method, token);
11731                                 info = mono_find_jit_icall_by_addr (func);
11732                                 if (!info)
11733                                         g_error ("Could not find icall address in wrapper %s", mono_method_full_name (method, 1));
11734                                 g_assert (info);
11735
11736                                 CHECK_STACK (info->sig->param_count);
11737                                 sp -= info->sig->param_count;
11738
11739                                 ins = mono_emit_jit_icall (cfg, info->func, sp);
11740                                 if (!MONO_TYPE_IS_VOID (info->sig->ret))
11741                                         *sp++ = ins;
11742
11743                                 ip += 6;
11744                                 inline_costs += 10 * num_calls++;
11745
11746                                 break;
11747                         }
11748                         case CEE_MONO_LDPTR_CARD_TABLE:
11749                         case CEE_MONO_LDPTR_NURSERY_START:
11750                         case CEE_MONO_LDPTR_NURSERY_BITS:
11751                         case CEE_MONO_LDPTR_INT_REQ_FLAG: {
11752                                 CHECK_STACK_OVF (1);
11753
11754                                 switch (ip [1]) {
11755                                         case CEE_MONO_LDPTR_CARD_TABLE:
11756                                                 ins = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_GC_CARD_TABLE_ADDR, NULL);
11757                                                 break;
11758                                         case CEE_MONO_LDPTR_NURSERY_START:
11759                                                 ins = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_GC_NURSERY_START, NULL);
11760                                                 break;
11761                                         case CEE_MONO_LDPTR_NURSERY_BITS:
11762                                                 ins = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_GC_NURSERY_BITS, NULL);
11763                                                 break;
11764                                         case CEE_MONO_LDPTR_INT_REQ_FLAG:
11765                                                 ins = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG, NULL);
11766                                                 break;
11767                                 }
11768
11769                                 *sp++ = ins;
11770                                 ip += 2;
11771                                 inline_costs += 10 * num_calls++;
11772                                 break;
11773                         }
11774                         case CEE_MONO_LDPTR: {
11775                                 gpointer ptr;
11776
11777                                 CHECK_STACK_OVF (1);
11778                                 CHECK_OPSIZE (6);
11779                                 token = read32 (ip + 2);
11780
11781                                 ptr = mono_method_get_wrapper_data (method, token);
11782                                 EMIT_NEW_PCONST (cfg, ins, ptr);
11783                                 *sp++ = ins;
11784                                 ip += 6;
11785                                 inline_costs += 10 * num_calls++;
11786                                 /* Can't embed random pointers into AOT code */
11787                                 DISABLE_AOT (cfg);
11788                                 break;
11789                         }
11790                         case CEE_MONO_JIT_ICALL_ADDR: {
11791                                 MonoJitICallInfo *callinfo;
11792                                 gpointer ptr;
11793
11794                                 CHECK_STACK_OVF (1);
11795                                 CHECK_OPSIZE (6);
11796                                 token = read32 (ip + 2);
11797
11798                                 ptr = mono_method_get_wrapper_data (method, token);
11799                                 callinfo = mono_find_jit_icall_by_addr (ptr);
11800                                 g_assert (callinfo);
11801                                 EMIT_NEW_JIT_ICALL_ADDRCONST (cfg, ins, (char*)callinfo->name);
11802                                 *sp++ = ins;
11803                                 ip += 6;
11804                                 inline_costs += 10 * num_calls++;
11805                                 break;
11806                         }
11807                         case CEE_MONO_ICALL_ADDR: {
11808                                 MonoMethod *cmethod;
11809                                 gpointer ptr;
11810
11811                                 CHECK_STACK_OVF (1);
11812                                 CHECK_OPSIZE (6);
11813                                 token = read32 (ip + 2);
11814
11815                                 cmethod = (MonoMethod *)mono_method_get_wrapper_data (method, token);
11816
11817                                 if (cfg->compile_aot) {
11818                                         if (cfg->direct_pinvoke && ip + 6 < end && (ip [6] == CEE_POP)) {
11819                                                 /*
11820                                                  * This is generated by emit_native_wrapper () to resolve the pinvoke address
11821                                                  * before the call, its not needed when using direct pinvoke.
11822                                                  * This is not an optimization, but its used to avoid looking up pinvokes
11823                                                  * on platforms which don't support dlopen ().
11824                                                  */
11825                                                 EMIT_NEW_PCONST (cfg, ins, NULL);
11826                                         } else {
11827                                                 EMIT_NEW_AOTCONST (cfg, ins, MONO_PATCH_INFO_ICALL_ADDR, cmethod);
11828                                         }
11829                                 } else {
11830                                         ptr = mono_lookup_internal_call (cmethod);
11831                                         g_assert (ptr);
11832                                         EMIT_NEW_PCONST (cfg, ins, ptr);
11833                                 }
11834                                 *sp++ = ins;
11835                                 ip += 6;
11836                                 break;
11837                         }
11838                         case CEE_MONO_VTADDR: {
11839                                 MonoInst *src_var, *src;
11840
11841                                 CHECK_STACK (1);
11842                                 --sp;
11843
11844                                 // FIXME:
11845                                 src_var = get_vreg_to_inst (cfg, sp [0]->dreg);
11846                                 EMIT_NEW_VARLOADA ((cfg), (src), src_var, src_var->inst_vtype);
11847                                 *sp++ = src;
11848                                 ip += 2;
11849                                 break;
11850                         }
11851                         case CEE_MONO_NEWOBJ: {
11852                                 MonoInst *iargs [2];
11853
11854                                 CHECK_STACK_OVF (1);
11855                                 CHECK_OPSIZE (6);
11856                                 token = read32 (ip + 2);
11857                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
11858                                 mono_class_init (klass);
11859                                 NEW_DOMAINCONST (cfg, iargs [0]);
11860                                 MONO_ADD_INS (cfg->cbb, iargs [0]);
11861                                 NEW_CLASSCONST (cfg, iargs [1], klass);
11862                                 MONO_ADD_INS (cfg->cbb, iargs [1]);
11863                                 *sp++ = mono_emit_jit_icall (cfg, ves_icall_object_new, iargs);
11864                                 ip += 6;
11865                                 inline_costs += 10 * num_calls++;
11866                                 break;
11867                         }
11868                         case CEE_MONO_OBJADDR:
11869                                 CHECK_STACK (1);
11870                                 --sp;
11871                                 MONO_INST_NEW (cfg, ins, OP_MOVE);
11872                                 ins->dreg = alloc_ireg_mp (cfg);
11873                                 ins->sreg1 = sp [0]->dreg;
11874                                 ins->type = STACK_MP;
11875                                 MONO_ADD_INS (cfg->cbb, ins);
11876                                 *sp++ = ins;
11877                                 ip += 2;
11878                                 break;
11879                         case CEE_MONO_LDNATIVEOBJ:
11880                                 /*
11881                                  * Similar to LDOBJ, but instead load the unmanaged 
11882                                  * representation of the vtype to the stack.
11883                                  */
11884                                 CHECK_STACK (1);
11885                                 CHECK_OPSIZE (6);
11886                                 --sp;
11887                                 token = read32 (ip + 2);
11888                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
11889                                 g_assert (klass->valuetype);
11890                                 mono_class_init (klass);
11891
11892                                 {
11893                                         MonoInst *src, *dest, *temp;
11894
11895                                         src = sp [0];
11896                                         temp = mono_compile_create_var (cfg, &klass->byval_arg, OP_LOCAL);
11897                                         temp->backend.is_pinvoke = 1;
11898                                         EMIT_NEW_TEMPLOADA (cfg, dest, temp->inst_c0);
11899                                         mini_emit_stobj (cfg, dest, src, klass, TRUE);
11900
11901                                         EMIT_NEW_TEMPLOAD (cfg, dest, temp->inst_c0);
11902                                         dest->type = STACK_VTYPE;
11903                                         dest->klass = klass;
11904
11905                                         *sp ++ = dest;
11906                                         ip += 6;
11907                                 }
11908                                 break;
11909                         case CEE_MONO_RETOBJ: {
11910                                 /*
11911                                  * Same as RET, but return the native representation of a vtype
11912                                  * to the caller.
11913                                  */
11914                                 g_assert (cfg->ret);
11915                                 g_assert (mono_method_signature (method)->pinvoke); 
11916                                 CHECK_STACK (1);
11917                                 --sp;
11918                                 
11919                                 CHECK_OPSIZE (6);
11920                                 token = read32 (ip + 2);    
11921                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
11922
11923                                 if (!cfg->vret_addr) {
11924                                         g_assert (cfg->ret_var_is_local);
11925
11926                                         EMIT_NEW_VARLOADA (cfg, ins, cfg->ret, cfg->ret->inst_vtype);
11927                                 } else {
11928                                         EMIT_NEW_RETLOADA (cfg, ins);
11929                                 }
11930                                 mini_emit_stobj (cfg, ins, sp [0], klass, TRUE);
11931                                 
11932                                 if (sp != stack_start)
11933                                         UNVERIFIED;
11934                                 
11935                                 MONO_INST_NEW (cfg, ins, OP_BR);
11936                                 ins->inst_target_bb = end_bblock;
11937                                 MONO_ADD_INS (cfg->cbb, ins);
11938                                 link_bblock (cfg, cfg->cbb, end_bblock);
11939                                 start_new_bblock = 1;
11940                                 ip += 6;
11941                                 break;
11942                         }
11943                         case CEE_MONO_SAVE_LMF:
11944                         case CEE_MONO_RESTORE_LMF:
11945                                 ip += 2;
11946                                 break;
11947                         case CEE_MONO_CLASSCONST:
11948                                 CHECK_STACK_OVF (1);
11949                                 CHECK_OPSIZE (6);
11950                                 token = read32 (ip + 2);
11951                                 EMIT_NEW_CLASSCONST (cfg, ins, mono_method_get_wrapper_data (method, token));
11952                                 *sp++ = ins;
11953                                 ip += 6;
11954                                 inline_costs += 10 * num_calls++;
11955                                 break;
11956                         case CEE_MONO_NOT_TAKEN:
11957                                 cfg->cbb->out_of_line = TRUE;
11958                                 ip += 2;
11959                                 break;
11960                         case CEE_MONO_TLS: {
11961                                 MonoTlsKey key;
11962
11963                                 CHECK_STACK_OVF (1);
11964                                 CHECK_OPSIZE (6);
11965                                 key = (MonoTlsKey)read32 (ip + 2);
11966                                 g_assert (key < TLS_KEY_NUM);
11967
11968                                 ins = mono_create_tls_get (cfg, key);
11969                                 g_assert (ins);
11970                                 ins->type = STACK_PTR;
11971                                 *sp++ = ins;
11972                                 ip += 6;
11973                                 break;
11974                         }
11975                         case CEE_MONO_DYN_CALL: {
11976                                 MonoCallInst *call;
11977
11978                                 /* It would be easier to call a trampoline, but that would put an
11979                                  * extra frame on the stack, confusing exception handling. So
11980                                  * implement it inline using an opcode for now.
11981                                  */
11982
11983                                 if (!cfg->dyn_call_var) {
11984                                         cfg->dyn_call_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
11985                                         /* prevent it from being register allocated */
11986                                         cfg->dyn_call_var->flags |= MONO_INST_VOLATILE;
11987                                 }
11988
11989                                 /* Has to use a call inst since it local regalloc expects it */
11990                                 MONO_INST_NEW_CALL (cfg, call, OP_DYN_CALL);
11991                                 ins = (MonoInst*)call;
11992                                 sp -= 2;
11993                                 ins->sreg1 = sp [0]->dreg;
11994                                 ins->sreg2 = sp [1]->dreg;
11995                                 MONO_ADD_INS (cfg->cbb, ins);
11996
11997                                 cfg->param_area = MAX (cfg->param_area, cfg->backend->dyn_call_param_area);
11998
11999                                 ip += 2;
12000                                 inline_costs += 10 * num_calls++;
12001
12002                                 break;
12003                         }
12004                         case CEE_MONO_MEMORY_BARRIER: {
12005                                 CHECK_OPSIZE (6);
12006                                 mini_emit_memory_barrier (cfg, (int)read32 (ip + 2));
12007                                 ip += 6;
12008                                 break;
12009                         }
12010                         case CEE_MONO_ATOMIC_STORE_I4: {
12011                                 g_assert (mono_arch_opcode_supported (OP_ATOMIC_STORE_I4));
12012
12013                                 CHECK_OPSIZE (6);
12014                                 CHECK_STACK (2);
12015                                 sp -= 2;
12016
12017                                 MONO_INST_NEW (cfg, ins, OP_ATOMIC_STORE_I4);
12018                                 ins->dreg = sp [0]->dreg;
12019                                 ins->sreg1 = sp [1]->dreg;
12020                                 ins->backend.memory_barrier_kind = (int) read32 (ip + 2);
12021                                 MONO_ADD_INS (cfg->cbb, ins);
12022
12023                                 ip += 6;
12024                                 break;
12025                         }
12026                         case CEE_MONO_JIT_ATTACH: {
12027                                 MonoInst *args [16], *domain_ins;
12028                                 MonoInst *ad_ins, *jit_tls_ins;
12029                                 MonoBasicBlock *next_bb = NULL, *call_bb = NULL;
12030
12031                                 g_assert (!mono_threads_is_coop_enabled ());
12032
12033                                 cfg->orig_domain_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
12034
12035                                 EMIT_NEW_PCONST (cfg, ins, NULL);
12036                                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, cfg->orig_domain_var->dreg, ins->dreg);
12037
12038                                 ad_ins = mono_create_tls_get (cfg, TLS_KEY_DOMAIN);
12039                                 jit_tls_ins = mono_create_tls_get (cfg, TLS_KEY_JIT_TLS);
12040
12041                                 if (ad_ins && jit_tls_ins) {
12042                                         NEW_BBLOCK (cfg, next_bb);
12043                                         NEW_BBLOCK (cfg, call_bb);
12044
12045                                         if (cfg->compile_aot) {
12046                                                 /* AOT code is only used in the root domain */
12047                                                 EMIT_NEW_PCONST (cfg, domain_ins, NULL);
12048                                         } else {
12049                                                 EMIT_NEW_PCONST (cfg, domain_ins, cfg->domain);
12050                                         }
12051                                         MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, ad_ins->dreg, domain_ins->dreg);
12052                                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, call_bb);
12053
12054                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, jit_tls_ins->dreg, 0);
12055                                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, call_bb);
12056
12057                                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, next_bb);
12058                                         MONO_START_BB (cfg, call_bb);
12059                                 }
12060
12061                                 /* AOT code is only used in the root domain */
12062                                 EMIT_NEW_PCONST (cfg, args [0], cfg->compile_aot ? NULL : cfg->domain);
12063                                 if (cfg->compile_aot) {
12064                                         MonoInst *addr;
12065
12066                                         /*
12067                                          * This is called on unattached threads, so it cannot go through the trampoline
12068                                          * infrastructure. Use an indirect call through a got slot initialized at load time
12069                                          * instead.
12070                                          */
12071                                         EMIT_NEW_AOTCONST (cfg, addr, MONO_PATCH_INFO_JIT_THREAD_ATTACH, NULL);
12072                                         ins = mini_emit_calli (cfg, helper_sig_jit_thread_attach, args, addr, NULL, NULL);
12073                                 } else {
12074                                         ins = mono_emit_jit_icall (cfg, mono_jit_thread_attach, args);
12075                                 }
12076                                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, cfg->orig_domain_var->dreg, ins->dreg);
12077
12078                                 if (next_bb)
12079                                         MONO_START_BB (cfg, next_bb);
12080
12081                                 ip += 2;
12082                                 break;
12083                         }
12084                         case CEE_MONO_JIT_DETACH: {
12085                                 MonoInst *args [16];
12086
12087                                 /* Restore the original domain */
12088                                 dreg = alloc_ireg (cfg);
12089                                 EMIT_NEW_UNALU (cfg, args [0], OP_MOVE, dreg, cfg->orig_domain_var->dreg);
12090                                 mono_emit_jit_icall (cfg, mono_jit_set_domain, args);
12091                                 ip += 2;
12092                                 break;
12093                         }
12094                         case CEE_MONO_CALLI_EXTRA_ARG: {
12095                                 MonoInst *addr;
12096                                 MonoMethodSignature *fsig;
12097                                 MonoInst *arg;
12098
12099                                 /*
12100                                  * This is the same as CEE_CALLI, but passes an additional argument
12101                                  * to the called method in llvmonly mode.
12102                                  * This is only used by delegate invoke wrappers to call the
12103                                  * actual delegate method.
12104                                  */
12105                                 g_assert (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE);
12106
12107                                 CHECK_OPSIZE (6);
12108                                 token = read32 (ip + 2);
12109
12110                                 ins = NULL;
12111
12112                                 cmethod = NULL;
12113                                 CHECK_STACK (1);
12114                                 --sp;
12115                                 addr = *sp;
12116                                 fsig = mini_get_signature (method, token, generic_context, &cfg->error);
12117                                 CHECK_CFG_ERROR;
12118
12119                                 if (cfg->llvm_only)
12120                                         cfg->signatures = g_slist_prepend_mempool (cfg->mempool, cfg->signatures, fsig);
12121
12122                                 n = fsig->param_count + fsig->hasthis + 1;
12123
12124                                 CHECK_STACK (n);
12125
12126                                 sp -= n;
12127                                 arg = sp [n - 1];
12128
12129                                 if (cfg->llvm_only) {
12130                                         /*
12131                                          * The lowest bit of 'arg' determines whenever the callee uses the gsharedvt
12132                                          * cconv. This is set by mono_init_delegate ().
12133                                          */
12134                                         if (cfg->gsharedvt && mini_is_gsharedvt_variable_signature (fsig)) {
12135                                                 MonoInst *callee = addr;
12136                                                 MonoInst *call, *localloc_ins;
12137                                                 MonoBasicBlock *is_gsharedvt_bb, *end_bb;
12138                                                 int low_bit_reg = alloc_preg (cfg);
12139
12140                                                 NEW_BBLOCK (cfg, is_gsharedvt_bb);
12141                                                 NEW_BBLOCK (cfg, end_bb);
12142
12143                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PAND_IMM, low_bit_reg, arg->dreg, 1);
12144                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, low_bit_reg, 0);
12145                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, is_gsharedvt_bb);
12146
12147                                                 /* Normal case: callee uses a normal cconv, have to add an out wrapper */
12148                                                 addr = emit_get_rgctx_sig (cfg, context_used,
12149                                                                                                    fsig, MONO_RGCTX_INFO_SIG_GSHAREDVT_OUT_TRAMPOLINE_CALLI);
12150                                                 /*
12151                                                  * ADDR points to a gsharedvt-out wrapper, have to pass <callee, arg> as an extra arg.
12152                                                  */
12153                                                 MONO_INST_NEW (cfg, ins, OP_LOCALLOC_IMM);
12154                                                 ins->dreg = alloc_preg (cfg);
12155                                                 ins->inst_imm = 2 * SIZEOF_VOID_P;
12156                                                 MONO_ADD_INS (cfg->cbb, ins);
12157                                                 localloc_ins = ins;
12158                                                 cfg->flags |= MONO_CFG_HAS_ALLOCA;
12159                                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, localloc_ins->dreg, 0, callee->dreg);
12160                                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, localloc_ins->dreg, SIZEOF_VOID_P, arg->dreg);
12161
12162                                                 call = emit_extra_arg_calli (cfg, fsig, sp, localloc_ins->dreg, addr);
12163                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
12164
12165                                                 /* Gsharedvt case: callee uses a gsharedvt cconv, no conversion is needed */
12166                                                 MONO_START_BB (cfg, is_gsharedvt_bb);
12167                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PXOR_IMM, arg->dreg, arg->dreg, 1);
12168                                                 ins = emit_extra_arg_calli (cfg, fsig, sp, arg->dreg, callee);
12169                                                 ins->dreg = call->dreg;
12170
12171                                                 MONO_START_BB (cfg, end_bb);
12172                                         } else {
12173                                                 /* Caller uses a normal calling conv */
12174
12175                                                 MonoInst *callee = addr;
12176                                                 MonoInst *call, *localloc_ins;
12177                                                 MonoBasicBlock *is_gsharedvt_bb, *end_bb;
12178                                                 int low_bit_reg = alloc_preg (cfg);
12179
12180                                                 NEW_BBLOCK (cfg, is_gsharedvt_bb);
12181                                                 NEW_BBLOCK (cfg, end_bb);
12182
12183                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PAND_IMM, low_bit_reg, arg->dreg, 1);
12184                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, low_bit_reg, 0);
12185                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, is_gsharedvt_bb);
12186
12187                                                 /* Normal case: callee uses a normal cconv, no conversion is needed */
12188                                                 call = emit_extra_arg_calli (cfg, fsig, sp, arg->dreg, callee);
12189                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
12190                                                 /* Gsharedvt case: callee uses a gsharedvt cconv, have to add an in wrapper */
12191                                                 MONO_START_BB (cfg, is_gsharedvt_bb);
12192                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PXOR_IMM, arg->dreg, arg->dreg, 1);
12193                                                 NEW_AOTCONST (cfg, addr, MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER, fsig);
12194                                                 MONO_ADD_INS (cfg->cbb, addr);
12195                                                 /*
12196                                                  * ADDR points to a gsharedvt-in wrapper, have to pass <callee, arg> as an extra arg.
12197                                                  */
12198                                                 MONO_INST_NEW (cfg, ins, OP_LOCALLOC_IMM);
12199                                                 ins->dreg = alloc_preg (cfg);
12200                                                 ins->inst_imm = 2 * SIZEOF_VOID_P;
12201                                                 MONO_ADD_INS (cfg->cbb, ins);
12202                                                 localloc_ins = ins;
12203                                                 cfg->flags |= MONO_CFG_HAS_ALLOCA;
12204                                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, localloc_ins->dreg, 0, callee->dreg);
12205                                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, localloc_ins->dreg, SIZEOF_VOID_P, arg->dreg);
12206
12207                                                 ins = emit_extra_arg_calli (cfg, fsig, sp, localloc_ins->dreg, addr);
12208                                                 ins->dreg = call->dreg;
12209                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
12210
12211                                                 MONO_START_BB (cfg, end_bb);
12212                                         }
12213                                 } else {
12214                                         /* Same as CEE_CALLI */
12215                                         if (cfg->gsharedvt && mini_is_gsharedvt_signature (fsig)) {
12216                                                 /*
12217                                                  * We pass the address to the gsharedvt trampoline in the rgctx reg
12218                                                  */
12219                                                 MonoInst *callee = addr;
12220
12221                                                 addr = emit_get_rgctx_sig (cfg, context_used,
12222                                                                                                    fsig, MONO_RGCTX_INFO_SIG_GSHAREDVT_OUT_TRAMPOLINE_CALLI);
12223                                                 ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, NULL, callee);
12224                                         } else {
12225                                                 ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
12226                                         }
12227                                 }
12228
12229                                 if (!MONO_TYPE_IS_VOID (fsig->ret))
12230                                         *sp++ = mono_emit_widen_call_res (cfg, ins, fsig);
12231
12232                                 CHECK_CFG_EXCEPTION;
12233
12234                                 ip += 6;
12235                                 ins_flag = 0;
12236                                 constrained_class = NULL;
12237                                 break;
12238                         }
12239                         case CEE_MONO_LDDOMAIN:
12240                                 CHECK_STACK_OVF (1);
12241                                 EMIT_NEW_PCONST (cfg, ins, cfg->compile_aot ? NULL : cfg->domain);
12242                                 ip += 2;
12243                                 *sp++ = ins;
12244                                 break;
12245                         case CEE_MONO_GET_LAST_ERROR:
12246                                 CHECK_OPSIZE (2);
12247                                 CHECK_STACK_OVF (1);
12248
12249                                 MONO_INST_NEW (cfg, ins, OP_GET_LAST_ERROR);
12250                                 ins->dreg = alloc_dreg (cfg, STACK_I4);
12251                                 ins->type = STACK_I4;
12252                                 MONO_ADD_INS (cfg->cbb, ins);
12253
12254                                 ip += 2;
12255                                 *sp++ = ins;
12256                                 break;
12257                         case CEE_MONO_GET_RGCTX_ARG:
12258                                 CHECK_OPSIZE (2);
12259                                 CHECK_STACK_OVF (1);
12260
12261                                 mono_create_rgctx_var (cfg);
12262
12263                                 MONO_INST_NEW (cfg, ins, OP_MOVE);
12264                                 ins->dreg = alloc_dreg (cfg, STACK_PTR);
12265                                 ins->sreg1 = cfg->rgctx_var->dreg;
12266                                 ins->type = STACK_PTR;
12267                                 MONO_ADD_INS (cfg->cbb, ins);
12268
12269                                 ip += 2;
12270                                 *sp++ = ins;
12271                                 break;
12272                         default:
12273                                 g_error ("opcode 0x%02x 0x%02x not handled", MONO_CUSTOM_PREFIX, ip [1]);
12274                                 break;
12275                         }
12276                         break;
12277                 }
12278
12279                 case CEE_PREFIX1: {
12280                         CHECK_OPSIZE (2);
12281                         switch (ip [1]) {
12282                         case CEE_ARGLIST: {
12283                                 /* somewhat similar to LDTOKEN */
12284                                 MonoInst *addr, *vtvar;
12285                                 CHECK_STACK_OVF (1);
12286                                 vtvar = mono_compile_create_var (cfg, &mono_defaults.argumenthandle_class->byval_arg, OP_LOCAL); 
12287
12288                                 EMIT_NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
12289                                 EMIT_NEW_UNALU (cfg, ins, OP_ARGLIST, -1, addr->dreg);
12290
12291                                 EMIT_NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
12292                                 ins->type = STACK_VTYPE;
12293                                 ins->klass = mono_defaults.argumenthandle_class;
12294                                 *sp++ = ins;
12295                                 ip += 2;
12296                                 break;
12297                         }
12298                         case CEE_CEQ:
12299                         case CEE_CGT:
12300                         case CEE_CGT_UN:
12301                         case CEE_CLT:
12302                         case CEE_CLT_UN: {
12303                                 MonoInst *cmp, *arg1, *arg2;
12304
12305                                 CHECK_STACK (2);
12306                                 sp -= 2;
12307                                 arg1 = sp [0];
12308                                 arg2 = sp [1];
12309
12310                                 /*
12311                                  * The following transforms:
12312                                  *    CEE_CEQ    into OP_CEQ
12313                                  *    CEE_CGT    into OP_CGT
12314                                  *    CEE_CGT_UN into OP_CGT_UN
12315                                  *    CEE_CLT    into OP_CLT
12316                                  *    CEE_CLT_UN into OP_CLT_UN
12317                                  */
12318                                 MONO_INST_NEW (cfg, cmp, (OP_CEQ - CEE_CEQ) + ip [1]);
12319
12320                                 MONO_INST_NEW (cfg, ins, cmp->opcode);
12321                                 cmp->sreg1 = arg1->dreg;
12322                                 cmp->sreg2 = arg2->dreg;
12323                                 type_from_op (cfg, cmp, arg1, arg2);
12324                                 CHECK_TYPE (cmp);
12325                                 add_widen_op (cfg, cmp, &arg1, &arg2);
12326                                 if ((arg1->type == STACK_I8) || ((SIZEOF_VOID_P == 8) && ((arg1->type == STACK_PTR) || (arg1->type == STACK_OBJ) || (arg1->type == STACK_MP))))
12327                                         cmp->opcode = OP_LCOMPARE;
12328                                 else if (arg1->type == STACK_R4)
12329                                         cmp->opcode = OP_RCOMPARE;
12330                                 else if (arg1->type == STACK_R8)
12331                                         cmp->opcode = OP_FCOMPARE;
12332                                 else
12333                                         cmp->opcode = OP_ICOMPARE;
12334                                 MONO_ADD_INS (cfg->cbb, cmp);
12335                                 ins->type = STACK_I4;
12336                                 ins->dreg = alloc_dreg (cfg, (MonoStackType)ins->type);
12337                                 type_from_op (cfg, ins, arg1, arg2);
12338
12339                                 if (cmp->opcode == OP_FCOMPARE || cmp->opcode == OP_RCOMPARE) {
12340                                         /*
12341                                          * The backends expect the fceq opcodes to do the
12342                                          * comparison too.
12343                                          */
12344                                         ins->sreg1 = cmp->sreg1;
12345                                         ins->sreg2 = cmp->sreg2;
12346                                         NULLIFY_INS (cmp);
12347                                 }
12348                                 MONO_ADD_INS (cfg->cbb, ins);
12349                                 *sp++ = ins;
12350                                 ip += 2;
12351                                 break;
12352                         }
12353                         case CEE_LDFTN: {
12354                                 MonoInst *argconst;
12355                                 MonoMethod *cil_method;
12356
12357                                 CHECK_STACK_OVF (1);
12358                                 CHECK_OPSIZE (6);
12359                                 n = read32 (ip + 2);
12360                                 cmethod = mini_get_method (cfg, method, n, NULL, generic_context);
12361                                 CHECK_CFG_ERROR;
12362
12363                                 mono_class_init (cmethod->klass);
12364
12365                                 mono_save_token_info (cfg, image, n, cmethod);
12366
12367                                 context_used = mini_method_check_context_used (cfg, cmethod);
12368
12369                                 cil_method = cmethod;
12370                                 if (!dont_verify && !cfg->skip_visibility && !mono_method_can_access_method (method, cmethod))
12371                                         emit_method_access_failure (cfg, method, cil_method);
12372
12373                                 if (mono_security_core_clr_enabled ())
12374                                         ensure_method_is_allowed_to_call_method (cfg, method, cmethod);
12375
12376                                 /* 
12377                                  * Optimize the common case of ldftn+delegate creation
12378                                  */
12379                                 if ((sp > stack_start) && (ip + 6 + 5 < end) && ip_in_bb (cfg, cfg->cbb, ip + 6) && (ip [6] == CEE_NEWOBJ)) {
12380                                         MonoMethod *ctor_method = mini_get_method (cfg, method, read32 (ip + 7), NULL, generic_context);
12381                                         if (ctor_method && (ctor_method->klass->parent == mono_defaults.multicastdelegate_class)) {
12382                                                 MonoInst *target_ins, *handle_ins;
12383                                                 MonoMethod *invoke;
12384                                                 int invoke_context_used;
12385
12386                                                 invoke = mono_get_delegate_invoke (ctor_method->klass);
12387                                                 if (!invoke || !mono_method_signature (invoke))
12388                                                         LOAD_ERROR;
12389
12390                                                 invoke_context_used = mini_method_check_context_used (cfg, invoke);
12391
12392                                                 target_ins = sp [-1];
12393
12394                                                 if (mono_security_core_clr_enabled ())
12395                                                         ensure_method_is_allowed_to_call_method (cfg, method, ctor_method);
12396
12397                                                 if (!(cmethod->flags & METHOD_ATTRIBUTE_STATIC)) {
12398                                                         /*LAME IMPL: We must not add a null check for virtual invoke delegates.*/
12399                                                         if (mono_method_signature (invoke)->param_count == mono_method_signature (cmethod)->param_count) {
12400                                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, target_ins->dreg, 0);
12401                                                                 MONO_EMIT_NEW_COND_EXC (cfg, EQ, "ArgumentException");
12402                                                         }
12403                                                 }
12404
12405                                                 /* FIXME: SGEN support */
12406                                                 if (invoke_context_used == 0 || cfg->llvm_only) {
12407                                                         ip += 6;
12408                                                         if (cfg->verbose_level > 3)
12409                                                                 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));
12410                                                         if ((handle_ins = handle_delegate_ctor (cfg, ctor_method->klass, target_ins, cmethod, context_used, FALSE))) {
12411                                                                 sp --;
12412                                                                 *sp = handle_ins;
12413                                                                 CHECK_CFG_EXCEPTION;
12414                                                                 ip += 5;
12415                                                                 sp ++;
12416                                                                 break;
12417                                                         }
12418                                                         ip -= 6;
12419                                                 }
12420                                         }
12421                                 }
12422
12423                                 argconst = emit_get_rgctx_method (cfg, context_used, cmethod, MONO_RGCTX_INFO_METHOD);
12424                                 ins = mono_emit_jit_icall (cfg, mono_ldftn, &argconst);
12425                                 *sp++ = ins;
12426                                 
12427                                 ip += 6;
12428                                 inline_costs += 10 * num_calls++;
12429                                 break;
12430                         }
12431                         case CEE_LDVIRTFTN: {
12432                                 MonoInst *args [2];
12433
12434                                 CHECK_STACK (1);
12435                                 CHECK_OPSIZE (6);
12436                                 n = read32 (ip + 2);
12437                                 cmethod = mini_get_method (cfg, method, n, NULL, generic_context);
12438                                 CHECK_CFG_ERROR;
12439
12440                                 mono_class_init (cmethod->klass);
12441  
12442                                 context_used = mini_method_check_context_used (cfg, cmethod);
12443
12444                                 if (mono_security_core_clr_enabled ())
12445                                         ensure_method_is_allowed_to_call_method (cfg, method, cmethod);
12446
12447                                 /*
12448                                  * Optimize the common case of ldvirtftn+delegate creation
12449                                  */
12450                                 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)) {
12451                                         MonoMethod *ctor_method = mini_get_method (cfg, method, read32 (ip + 7), NULL, generic_context);
12452                                         if (ctor_method && (ctor_method->klass->parent == mono_defaults.multicastdelegate_class)) {
12453                                                 MonoInst *target_ins, *handle_ins;
12454                                                 MonoMethod *invoke;
12455                                                 int invoke_context_used;
12456                                                 gboolean is_virtual = cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL;
12457
12458                                                 invoke = mono_get_delegate_invoke (ctor_method->klass);
12459                                                 if (!invoke || !mono_method_signature (invoke))
12460                                                         LOAD_ERROR;
12461
12462                                                 invoke_context_used = mini_method_check_context_used (cfg, invoke);
12463
12464                                                 target_ins = sp [-1];
12465
12466                                                 if (mono_security_core_clr_enabled ())
12467                                                         ensure_method_is_allowed_to_call_method (cfg, method, ctor_method);
12468
12469                                                 /* FIXME: SGEN support */
12470                                                 if (invoke_context_used == 0 || cfg->llvm_only) {
12471                                                         ip += 6;
12472                                                         if (cfg->verbose_level > 3)
12473                                                                 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));
12474                                                         if ((handle_ins = handle_delegate_ctor (cfg, ctor_method->klass, target_ins, cmethod, context_used, is_virtual))) {
12475                                                                 sp -= 2;
12476                                                                 *sp = handle_ins;
12477                                                                 CHECK_CFG_EXCEPTION;
12478                                                                 ip += 5;
12479                                                                 sp ++;
12480                                                                 break;
12481                                                         }
12482                                                         ip -= 6;
12483                                                 }
12484                                         }
12485                                 }
12486
12487                                 --sp;
12488                                 args [0] = *sp;
12489
12490                                 args [1] = emit_get_rgctx_method (cfg, context_used,
12491                                                                                                   cmethod, MONO_RGCTX_INFO_METHOD);
12492
12493                                 if (context_used)
12494                                         *sp++ = mono_emit_jit_icall (cfg, mono_ldvirtfn_gshared, args);
12495                                 else
12496                                         *sp++ = mono_emit_jit_icall (cfg, mono_ldvirtfn, args);
12497
12498                                 ip += 6;
12499                                 inline_costs += 10 * num_calls++;
12500                                 break;
12501                         }
12502                         case CEE_LDARG:
12503                                 CHECK_STACK_OVF (1);
12504                                 CHECK_OPSIZE (4);
12505                                 n = read16 (ip + 2);
12506                                 CHECK_ARG (n);
12507                                 EMIT_NEW_ARGLOAD (cfg, ins, n);
12508                                 *sp++ = ins;
12509                                 ip += 4;
12510                                 break;
12511                         case CEE_LDARGA:
12512                                 CHECK_STACK_OVF (1);
12513                                 CHECK_OPSIZE (4);
12514                                 n = read16 (ip + 2);
12515                                 CHECK_ARG (n);
12516                                 NEW_ARGLOADA (cfg, ins, n);
12517                                 MONO_ADD_INS (cfg->cbb, ins);
12518                                 *sp++ = ins;
12519                                 ip += 4;
12520                                 break;
12521                         case CEE_STARG:
12522                                 CHECK_STACK (1);
12523                                 --sp;
12524                                 CHECK_OPSIZE (4);
12525                                 n = read16 (ip + 2);
12526                                 CHECK_ARG (n);
12527                                 if (!dont_verify_stloc && target_type_is_incompatible (cfg, param_types [n], *sp))
12528                                         UNVERIFIED;
12529                                 EMIT_NEW_ARGSTORE (cfg, ins, n, *sp);
12530                                 ip += 4;
12531                                 break;
12532                         case CEE_LDLOC:
12533                                 CHECK_STACK_OVF (1);
12534                                 CHECK_OPSIZE (4);
12535                                 n = read16 (ip + 2);
12536                                 CHECK_LOCAL (n);
12537                                 EMIT_NEW_LOCLOAD (cfg, ins, n);
12538                                 *sp++ = ins;
12539                                 ip += 4;
12540                                 break;
12541                         case CEE_LDLOCA: {
12542                                 unsigned char *tmp_ip;
12543                                 CHECK_STACK_OVF (1);
12544                                 CHECK_OPSIZE (4);
12545                                 n = read16 (ip + 2);
12546                                 CHECK_LOCAL (n);
12547
12548                                 if ((tmp_ip = emit_optimized_ldloca_ir (cfg, ip, end, 2))) {
12549                                         ip = tmp_ip;
12550                                         inline_costs += 1;
12551                                         break;
12552                                 }                       
12553                                 
12554                                 EMIT_NEW_LOCLOADA (cfg, ins, n);
12555                                 *sp++ = ins;
12556                                 ip += 4;
12557                                 break;
12558                         }
12559                         case CEE_STLOC:
12560                                 CHECK_STACK (1);
12561                                 --sp;
12562                                 CHECK_OPSIZE (4);
12563                                 n = read16 (ip + 2);
12564                                 CHECK_LOCAL (n);
12565                                 if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [n], *sp))
12566                                         UNVERIFIED;
12567                                 emit_stloc_ir (cfg, sp, header, n);
12568                                 ip += 4;
12569                                 inline_costs += 1;
12570                                 break;
12571                         case CEE_LOCALLOC: {
12572                                 CHECK_STACK (1);
12573                                 MonoBasicBlock *non_zero_bb, *end_bb;
12574                                 int alloc_ptr = alloc_preg (cfg);
12575                                 --sp;
12576                                 if (sp != stack_start) 
12577                                         UNVERIFIED;
12578                                 if (cfg->method != method) 
12579                                         /* 
12580                                          * Inlining this into a loop in a parent could lead to 
12581                                          * stack overflows which is different behavior than the
12582                                          * non-inlined case, thus disable inlining in this case.
12583                                          */
12584                                         INLINE_FAILURE("localloc");
12585
12586                                 NEW_BBLOCK (cfg, non_zero_bb);
12587                                 NEW_BBLOCK (cfg, end_bb);
12588
12589                                 /* if size != zero */
12590                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, sp [0]->dreg, 0);
12591                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, non_zero_bb);
12592
12593                                 //size is zero, so result is NULL
12594                                 MONO_EMIT_NEW_PCONST (cfg, alloc_ptr, NULL);
12595                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
12596
12597                                 MONO_START_BB (cfg, non_zero_bb);
12598                                 MONO_INST_NEW (cfg, ins, OP_LOCALLOC);
12599                                 ins->dreg = alloc_ptr;
12600                                 ins->sreg1 = sp [0]->dreg;
12601                                 ins->type = STACK_PTR;
12602                                 MONO_ADD_INS (cfg->cbb, ins);
12603
12604                                 cfg->flags |= MONO_CFG_HAS_ALLOCA;
12605                                 if (init_locals)
12606                                         ins->flags |= MONO_INST_INIT;
12607
12608                                 MONO_START_BB (cfg, end_bb);
12609                                 EMIT_NEW_UNALU (cfg, ins, OP_MOVE, alloc_preg (cfg), alloc_ptr);
12610                                 ins->type = STACK_PTR;
12611
12612                                 *sp++ = ins;
12613                                 ip += 2;
12614                                 break;
12615                         }
12616                         case CEE_ENDFILTER: {
12617                                 MonoExceptionClause *clause, *nearest;
12618                                 int cc;
12619
12620                                 CHECK_STACK (1);
12621                                 --sp;
12622                                 if ((sp != stack_start) || (sp [0]->type != STACK_I4)) 
12623                                         UNVERIFIED;
12624                                 MONO_INST_NEW (cfg, ins, OP_ENDFILTER);
12625                                 ins->sreg1 = (*sp)->dreg;
12626                                 MONO_ADD_INS (cfg->cbb, ins);
12627                                 start_new_bblock = 1;
12628                                 ip += 2;
12629
12630                                 nearest = NULL;
12631                                 for (cc = 0; cc < header->num_clauses; ++cc) {
12632                                         clause = &header->clauses [cc];
12633                                         if ((clause->flags & MONO_EXCEPTION_CLAUSE_FILTER) &&
12634                                                 ((ip - header->code) > clause->data.filter_offset && (ip - header->code) <= clause->handler_offset) &&
12635                                             (!nearest || (clause->data.filter_offset < nearest->data.filter_offset)))
12636                                                 nearest = clause;
12637                                 }
12638                                 g_assert (nearest);
12639                                 if ((ip - header->code) != nearest->handler_offset)
12640                                         UNVERIFIED;
12641
12642                                 break;
12643                         }
12644                         case CEE_UNALIGNED_:
12645                                 ins_flag |= MONO_INST_UNALIGNED;
12646                                 /* FIXME: record alignment? we can assume 1 for now */
12647                                 CHECK_OPSIZE (3);
12648                                 ip += 3;
12649                                 break;
12650                         case CEE_VOLATILE_:
12651                                 ins_flag |= MONO_INST_VOLATILE;
12652                                 ip += 2;
12653                                 break;
12654                         case CEE_TAIL_:
12655                                 ins_flag   |= MONO_INST_TAILCALL;
12656                                 cfg->flags |= MONO_CFG_HAS_TAIL;
12657                                 /* Can't inline tail calls at this time */
12658                                 inline_costs += 100000;
12659                                 ip += 2;
12660                                 break;
12661                         case CEE_INITOBJ:
12662                                 CHECK_STACK (1);
12663                                 --sp;
12664                                 CHECK_OPSIZE (6);
12665                                 token = read32 (ip + 2);
12666                                 klass = mini_get_class (method, token, generic_context);
12667                                 CHECK_TYPELOAD (klass);
12668                                 if (generic_class_is_reference_type (cfg, klass))
12669                                         MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STORE_MEMBASE_IMM, sp [0]->dreg, 0, 0);
12670                                 else
12671                                         mini_emit_initobj (cfg, *sp, NULL, klass);
12672                                 ip += 6;
12673                                 inline_costs += 1;
12674                                 break;
12675                         case CEE_CONSTRAINED_:
12676                                 CHECK_OPSIZE (6);
12677                                 token = read32 (ip + 2);
12678                                 constrained_class = mini_get_class (method, token, generic_context);
12679                                 CHECK_TYPELOAD (constrained_class);
12680                                 ip += 6;
12681                                 break;
12682                         case CEE_CPBLK:
12683                                 CHECK_STACK (3);
12684                                 sp -= 3;
12685                                 mini_emit_memory_copy_bytes (cfg, sp [0], sp [1], sp [2], ins_flag);
12686                                 ip += 2;
12687                                 ins_flag = 0;
12688                                 inline_costs += 1;
12689                                 break;
12690                         case CEE_INITBLK:
12691                                 CHECK_STACK (3);
12692                                 sp -= 3;
12693                                 mini_emit_memory_init_bytes (cfg, sp [0], sp [1], sp [2], ins_flag);
12694                                 ip += 2;
12695                                 ins_flag = 0;
12696                                 inline_costs += 1;
12697                                 break;
12698                         case CEE_NO_:
12699                                 CHECK_OPSIZE (3);
12700                                 if (ip [2] & 0x1)
12701                                         ins_flag |= MONO_INST_NOTYPECHECK;
12702                                 if (ip [2] & 0x2)
12703                                         ins_flag |= MONO_INST_NORANGECHECK;
12704                                 /* we ignore the no-nullcheck for now since we
12705                                  * really do it explicitly only when doing callvirt->call
12706                                  */
12707                                 ip += 3;
12708                                 break;
12709                         case CEE_RETHROW: {
12710                                 MonoInst *load;
12711                                 int handler_offset = -1;
12712
12713                                 for (i = 0; i < header->num_clauses; ++i) {
12714                                         MonoExceptionClause *clause = &header->clauses [i];
12715                                         if (MONO_OFFSET_IN_HANDLER (clause, ip - header->code) && !(clause->flags & MONO_EXCEPTION_CLAUSE_FINALLY)) {
12716                                                 handler_offset = clause->handler_offset;
12717                                                 break;
12718                                         }
12719                                 }
12720
12721                                 cfg->cbb->flags |= BB_EXCEPTION_UNSAFE;
12722
12723                                 if (handler_offset == -1)
12724                                         UNVERIFIED;
12725
12726                                 EMIT_NEW_TEMPLOAD (cfg, load, mono_find_exvar_for_offset (cfg, handler_offset)->inst_c0);
12727                                 MONO_INST_NEW (cfg, ins, OP_RETHROW);
12728                                 ins->sreg1 = load->dreg;
12729                                 MONO_ADD_INS (cfg->cbb, ins);
12730
12731                                 MONO_INST_NEW (cfg, ins, OP_NOT_REACHED);
12732                                 MONO_ADD_INS (cfg->cbb, ins);
12733
12734                                 sp = stack_start;
12735                                 link_bblock (cfg, cfg->cbb, end_bblock);
12736                                 start_new_bblock = 1;
12737                                 ip += 2;
12738                                 break;
12739                         }
12740                         case CEE_SIZEOF: {
12741                                 guint32 val;
12742                                 int ialign;
12743
12744                                 CHECK_STACK_OVF (1);
12745                                 CHECK_OPSIZE (6);
12746                                 token = read32 (ip + 2);
12747                                 if (mono_metadata_token_table (token) == MONO_TABLE_TYPESPEC && !image_is_dynamic (method->klass->image) && !generic_context) {
12748                                         MonoType *type = mono_type_create_from_typespec_checked (image, token, &cfg->error);
12749                                         CHECK_CFG_ERROR;
12750
12751                                         val = mono_type_size (type, &ialign);
12752                                 } else {
12753                                         MonoClass *klass = mini_get_class (method, token, generic_context);
12754                                         CHECK_TYPELOAD (klass);
12755
12756                                         val = mono_type_size (&klass->byval_arg, &ialign);
12757
12758                                         if (mini_is_gsharedvt_klass (klass))
12759                                                 GSHAREDVT_FAILURE (*ip);
12760                                 }
12761                                 EMIT_NEW_ICONST (cfg, ins, val);
12762                                 *sp++= ins;
12763                                 ip += 6;
12764                                 break;
12765                         }
12766                         case CEE_REFANYTYPE: {
12767                                 MonoInst *src_var, *src;
12768
12769                                 GSHAREDVT_FAILURE (*ip);
12770
12771                                 CHECK_STACK (1);
12772                                 --sp;
12773
12774                                 // FIXME:
12775                                 src_var = get_vreg_to_inst (cfg, sp [0]->dreg);
12776                                 if (!src_var)
12777                                         src_var = mono_compile_create_var_for_vreg (cfg, &mono_defaults.typed_reference_class->byval_arg, OP_LOCAL, sp [0]->dreg);
12778                                 EMIT_NEW_VARLOADA (cfg, src, src_var, src_var->inst_vtype);
12779                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &mono_defaults.typehandle_class->byval_arg, src->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, type));
12780                                 *sp++ = ins;
12781                                 ip += 2;
12782                                 break;
12783                         }
12784                         case CEE_READONLY_:
12785                                 readonly = TRUE;
12786                                 ip += 2;
12787                                 break;
12788
12789                         case CEE_UNUSED56:
12790                         case CEE_UNUSED57:
12791                         case CEE_UNUSED70:
12792                         case CEE_UNUSED:
12793                         case CEE_UNUSED99:
12794                                 UNVERIFIED;
12795                                 
12796                         default:
12797                                 g_warning ("opcode 0xfe 0x%02x not handled", ip [1]);
12798                                 UNVERIFIED;
12799                         }
12800                         break;
12801                 }
12802                 case CEE_UNUSED58:
12803                 case CEE_UNUSED1:
12804                         UNVERIFIED;
12805
12806                 default:
12807                         g_warning ("opcode 0x%02x not handled", *ip);
12808                         UNVERIFIED;
12809                 }
12810         }
12811         if (start_new_bblock != 1)
12812                 UNVERIFIED;
12813
12814         cfg->cbb->cil_length = ip - cfg->cbb->cil_code;
12815         if (cfg->cbb->next_bb) {
12816                 /* This could already be set because of inlining, #693905 */
12817                 MonoBasicBlock *bb = cfg->cbb;
12818
12819                 while (bb->next_bb)
12820                         bb = bb->next_bb;
12821                 bb->next_bb = end_bblock;
12822         } else {
12823                 cfg->cbb->next_bb = end_bblock;
12824         }
12825
12826         if (cfg->method == method && cfg->domainvar) {
12827                 MonoInst *store;
12828                 MonoInst *get_domain;
12829
12830                 cfg->cbb = init_localsbb;
12831
12832                 get_domain = mono_create_tls_get (cfg, TLS_KEY_DOMAIN);
12833                 NEW_TEMPSTORE (cfg, store, cfg->domainvar->inst_c0, get_domain);
12834                 MONO_ADD_INS (cfg->cbb, store);
12835         }
12836
12837 #if defined(TARGET_POWERPC) || defined(TARGET_X86)
12838         if (cfg->compile_aot)
12839                 /* FIXME: The plt slots require a GOT var even if the method doesn't use it */
12840                 mono_get_got_var (cfg);
12841 #endif
12842
12843         if (cfg->method == method && cfg->got_var)
12844                 mono_emit_load_got_addr (cfg);
12845
12846         if (init_localsbb) {
12847                 cfg->cbb = init_localsbb;
12848                 cfg->ip = NULL;
12849                 for (i = 0; i < header->num_locals; ++i) {
12850                         emit_init_local (cfg, i, header->locals [i], init_locals);
12851                 }
12852         }
12853
12854         if (cfg->init_ref_vars && cfg->method == method) {
12855                 /* Emit initialization for ref vars */
12856                 // FIXME: Avoid duplication initialization for IL locals.
12857                 for (i = 0; i < cfg->num_varinfo; ++i) {
12858                         MonoInst *ins = cfg->varinfo [i];
12859
12860                         if (ins->opcode == OP_LOCAL && ins->type == STACK_OBJ)
12861                                 MONO_EMIT_NEW_PCONST (cfg, ins->dreg, NULL);
12862                 }
12863         }
12864
12865         if (cfg->lmf_var && cfg->method == method && !cfg->llvm_only) {
12866                 cfg->cbb = init_localsbb;
12867                 emit_push_lmf (cfg);
12868         }
12869
12870         cfg->cbb = init_localsbb;
12871         emit_instrumentation_call (cfg, mono_profiler_method_enter);
12872
12873         if (seq_points) {
12874                 MonoBasicBlock *bb;
12875
12876                 /*
12877                  * Make seq points at backward branch targets interruptable.
12878                  */
12879                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
12880                         if (bb->code && bb->in_count > 1 && bb->code->opcode == OP_SEQ_POINT)
12881                                 bb->code->flags |= MONO_INST_SINGLE_STEP_LOC;
12882         }
12883
12884         /* Add a sequence point for method entry/exit events */
12885         if (seq_points && cfg->gen_sdb_seq_points) {
12886                 NEW_SEQ_POINT (cfg, ins, METHOD_ENTRY_IL_OFFSET, FALSE);
12887                 MONO_ADD_INS (init_localsbb, ins);
12888                 NEW_SEQ_POINT (cfg, ins, METHOD_EXIT_IL_OFFSET, FALSE);
12889                 MONO_ADD_INS (cfg->bb_exit, ins);
12890         }
12891
12892         /*
12893          * Add seq points for IL offsets which have line number info, but wasn't generated a seq point during JITting because
12894          * the code they refer to was dead (#11880).
12895          */
12896         if (sym_seq_points) {
12897                 for (i = 0; i < header->code_size; ++i) {
12898                         if (mono_bitset_test_fast (seq_point_locs, i) && !mono_bitset_test_fast (seq_point_set_locs, i)) {
12899                                 MonoInst *ins;
12900
12901                                 NEW_SEQ_POINT (cfg, ins, i, FALSE);
12902                                 mono_add_seq_point (cfg, NULL, ins, SEQ_POINT_NATIVE_OFFSET_DEAD_CODE);
12903                         }
12904                 }
12905         }
12906
12907         cfg->ip = NULL;
12908
12909         if (cfg->method == method) {
12910                 MonoBasicBlock *bb;
12911                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
12912                         if (bb == cfg->bb_init)
12913                                 bb->region = -1;
12914                         else
12915                                 bb->region = mono_find_block_region (cfg, bb->real_offset);
12916                         if (cfg->spvars)
12917                                 mono_create_spvar_for_region (cfg, bb->region);
12918                         if (cfg->verbose_level > 2)
12919                                 printf ("REGION BB%d IL_%04x ID_%08X\n", bb->block_num, bb->real_offset, bb->region);
12920                 }
12921         } else {
12922                 MonoBasicBlock *bb;
12923                 /* get_most_deep_clause () in mini-llvm.c depends on this for inlined bblocks */
12924                 for (bb = start_bblock; bb != end_bblock; bb  = bb->next_bb) {
12925                         bb->real_offset = inline_offset;
12926                 }
12927         }
12928
12929         if (inline_costs < 0) {
12930                 char *mname;
12931
12932                 /* Method is too large */
12933                 mname = mono_method_full_name (method, TRUE);
12934                 mono_cfg_set_exception_invalid_program (cfg, g_strdup_printf ("Method %s is too complex.", mname));
12935                 g_free (mname);
12936         }
12937
12938         if ((cfg->verbose_level > 2) && (cfg->method == method)) 
12939                 mono_print_code (cfg, "AFTER METHOD-TO-IR");
12940
12941         goto cleanup;
12942
12943 mono_error_exit:
12944         g_assert (!mono_error_ok (&cfg->error));
12945         goto cleanup;
12946  
12947  exception_exit:
12948         g_assert (cfg->exception_type != MONO_EXCEPTION_NONE);
12949         goto cleanup;
12950
12951  unverified:
12952         set_exception_type_from_invalid_il (cfg, method, ip);
12953         goto cleanup;
12954
12955  cleanup:
12956         g_slist_free (class_inits);
12957         mono_basic_block_free (original_bb);
12958         cfg->dont_inline = g_list_remove (cfg->dont_inline, method);
12959         if (cfg->exception_type)
12960                 return -1;
12961         else
12962                 return inline_costs;
12963 }
12964
12965 static int
12966 store_membase_reg_to_store_membase_imm (int opcode)
12967 {
12968         switch (opcode) {
12969         case OP_STORE_MEMBASE_REG:
12970                 return OP_STORE_MEMBASE_IMM;
12971         case OP_STOREI1_MEMBASE_REG:
12972                 return OP_STOREI1_MEMBASE_IMM;
12973         case OP_STOREI2_MEMBASE_REG:
12974                 return OP_STOREI2_MEMBASE_IMM;
12975         case OP_STOREI4_MEMBASE_REG:
12976                 return OP_STOREI4_MEMBASE_IMM;
12977         case OP_STOREI8_MEMBASE_REG:
12978                 return OP_STOREI8_MEMBASE_IMM;
12979         default:
12980                 g_assert_not_reached ();
12981         }
12982
12983         return -1;
12984 }               
12985
12986 int
12987 mono_op_to_op_imm (int opcode)
12988 {
12989         switch (opcode) {
12990         case OP_IADD:
12991                 return OP_IADD_IMM;
12992         case OP_ISUB:
12993                 return OP_ISUB_IMM;
12994         case OP_IDIV:
12995                 return OP_IDIV_IMM;
12996         case OP_IDIV_UN:
12997                 return OP_IDIV_UN_IMM;
12998         case OP_IREM:
12999                 return OP_IREM_IMM;
13000         case OP_IREM_UN:
13001                 return OP_IREM_UN_IMM;
13002         case OP_IMUL:
13003                 return OP_IMUL_IMM;
13004         case OP_IAND:
13005                 return OP_IAND_IMM;
13006         case OP_IOR:
13007                 return OP_IOR_IMM;
13008         case OP_IXOR:
13009                 return OP_IXOR_IMM;
13010         case OP_ISHL:
13011                 return OP_ISHL_IMM;
13012         case OP_ISHR:
13013                 return OP_ISHR_IMM;
13014         case OP_ISHR_UN:
13015                 return OP_ISHR_UN_IMM;
13016
13017         case OP_LADD:
13018                 return OP_LADD_IMM;
13019         case OP_LSUB:
13020                 return OP_LSUB_IMM;
13021         case OP_LAND:
13022                 return OP_LAND_IMM;
13023         case OP_LOR:
13024                 return OP_LOR_IMM;
13025         case OP_LXOR:
13026                 return OP_LXOR_IMM;
13027         case OP_LSHL:
13028                 return OP_LSHL_IMM;
13029         case OP_LSHR:
13030                 return OP_LSHR_IMM;
13031         case OP_LSHR_UN:
13032                 return OP_LSHR_UN_IMM;
13033 #if SIZEOF_REGISTER == 8
13034         case OP_LREM:
13035                 return OP_LREM_IMM;
13036 #endif
13037
13038         case OP_COMPARE:
13039                 return OP_COMPARE_IMM;
13040         case OP_ICOMPARE:
13041                 return OP_ICOMPARE_IMM;
13042         case OP_LCOMPARE:
13043                 return OP_LCOMPARE_IMM;
13044
13045         case OP_STORE_MEMBASE_REG:
13046                 return OP_STORE_MEMBASE_IMM;
13047         case OP_STOREI1_MEMBASE_REG:
13048                 return OP_STOREI1_MEMBASE_IMM;
13049         case OP_STOREI2_MEMBASE_REG:
13050                 return OP_STOREI2_MEMBASE_IMM;
13051         case OP_STOREI4_MEMBASE_REG:
13052                 return OP_STOREI4_MEMBASE_IMM;
13053
13054 #if defined(TARGET_X86) || defined (TARGET_AMD64)
13055         case OP_X86_PUSH:
13056                 return OP_X86_PUSH_IMM;
13057         case OP_X86_COMPARE_MEMBASE_REG:
13058                 return OP_X86_COMPARE_MEMBASE_IMM;
13059 #endif
13060 #if defined(TARGET_AMD64)
13061         case OP_AMD64_ICOMPARE_MEMBASE_REG:
13062                 return OP_AMD64_ICOMPARE_MEMBASE_IMM;
13063 #endif
13064         case OP_VOIDCALL_REG:
13065                 return OP_VOIDCALL;
13066         case OP_CALL_REG:
13067                 return OP_CALL;
13068         case OP_LCALL_REG:
13069                 return OP_LCALL;
13070         case OP_FCALL_REG:
13071                 return OP_FCALL;
13072         case OP_LOCALLOC:
13073                 return OP_LOCALLOC_IMM;
13074         }
13075
13076         return -1;
13077 }
13078
13079 static int
13080 ldind_to_load_membase (int opcode)
13081 {
13082         switch (opcode) {
13083         case CEE_LDIND_I1:
13084                 return OP_LOADI1_MEMBASE;
13085         case CEE_LDIND_U1:
13086                 return OP_LOADU1_MEMBASE;
13087         case CEE_LDIND_I2:
13088                 return OP_LOADI2_MEMBASE;
13089         case CEE_LDIND_U2:
13090                 return OP_LOADU2_MEMBASE;
13091         case CEE_LDIND_I4:
13092                 return OP_LOADI4_MEMBASE;
13093         case CEE_LDIND_U4:
13094                 return OP_LOADU4_MEMBASE;
13095         case CEE_LDIND_I:
13096                 return OP_LOAD_MEMBASE;
13097         case CEE_LDIND_REF:
13098                 return OP_LOAD_MEMBASE;
13099         case CEE_LDIND_I8:
13100                 return OP_LOADI8_MEMBASE;
13101         case CEE_LDIND_R4:
13102                 return OP_LOADR4_MEMBASE;
13103         case CEE_LDIND_R8:
13104                 return OP_LOADR8_MEMBASE;
13105         default:
13106                 g_assert_not_reached ();
13107         }
13108
13109         return -1;
13110 }
13111
13112 static int
13113 stind_to_store_membase (int opcode)
13114 {
13115         switch (opcode) {
13116         case CEE_STIND_I1:
13117                 return OP_STOREI1_MEMBASE_REG;
13118         case CEE_STIND_I2:
13119                 return OP_STOREI2_MEMBASE_REG;
13120         case CEE_STIND_I4:
13121                 return OP_STOREI4_MEMBASE_REG;
13122         case CEE_STIND_I:
13123         case CEE_STIND_REF:
13124                 return OP_STORE_MEMBASE_REG;
13125         case CEE_STIND_I8:
13126                 return OP_STOREI8_MEMBASE_REG;
13127         case CEE_STIND_R4:
13128                 return OP_STORER4_MEMBASE_REG;
13129         case CEE_STIND_R8:
13130                 return OP_STORER8_MEMBASE_REG;
13131         default:
13132                 g_assert_not_reached ();
13133         }
13134
13135         return -1;
13136 }
13137
13138 int
13139 mono_load_membase_to_load_mem (int opcode)
13140 {
13141         // FIXME: Add a MONO_ARCH_HAVE_LOAD_MEM macro
13142 #if defined(TARGET_X86) || defined(TARGET_AMD64)
13143         switch (opcode) {
13144         case OP_LOAD_MEMBASE:
13145                 return OP_LOAD_MEM;
13146         case OP_LOADU1_MEMBASE:
13147                 return OP_LOADU1_MEM;
13148         case OP_LOADU2_MEMBASE:
13149                 return OP_LOADU2_MEM;
13150         case OP_LOADI4_MEMBASE:
13151                 return OP_LOADI4_MEM;
13152         case OP_LOADU4_MEMBASE:
13153                 return OP_LOADU4_MEM;
13154 #if SIZEOF_REGISTER == 8
13155         case OP_LOADI8_MEMBASE:
13156                 return OP_LOADI8_MEM;
13157 #endif
13158         }
13159 #endif
13160
13161         return -1;
13162 }
13163
13164 static inline int
13165 op_to_op_dest_membase (int store_opcode, int opcode)
13166 {
13167 #if defined(TARGET_X86)
13168         if (!((store_opcode == OP_STORE_MEMBASE_REG) || (store_opcode == OP_STOREI4_MEMBASE_REG)))
13169                 return -1;
13170
13171         switch (opcode) {
13172         case OP_IADD:
13173                 return OP_X86_ADD_MEMBASE_REG;
13174         case OP_ISUB:
13175                 return OP_X86_SUB_MEMBASE_REG;
13176         case OP_IAND:
13177                 return OP_X86_AND_MEMBASE_REG;
13178         case OP_IOR:
13179                 return OP_X86_OR_MEMBASE_REG;
13180         case OP_IXOR:
13181                 return OP_X86_XOR_MEMBASE_REG;
13182         case OP_ADD_IMM:
13183         case OP_IADD_IMM:
13184                 return OP_X86_ADD_MEMBASE_IMM;
13185         case OP_SUB_IMM:
13186         case OP_ISUB_IMM:
13187                 return OP_X86_SUB_MEMBASE_IMM;
13188         case OP_AND_IMM:
13189         case OP_IAND_IMM:
13190                 return OP_X86_AND_MEMBASE_IMM;
13191         case OP_OR_IMM:
13192         case OP_IOR_IMM:
13193                 return OP_X86_OR_MEMBASE_IMM;
13194         case OP_XOR_IMM:
13195         case OP_IXOR_IMM:
13196                 return OP_X86_XOR_MEMBASE_IMM;
13197         case OP_MOVE:
13198                 return OP_NOP;
13199         }
13200 #endif
13201
13202 #if defined(TARGET_AMD64)
13203         if (!((store_opcode == OP_STORE_MEMBASE_REG) || (store_opcode == OP_STOREI4_MEMBASE_REG) || (store_opcode == OP_STOREI8_MEMBASE_REG)))
13204                 return -1;
13205
13206         switch (opcode) {
13207         case OP_IADD:
13208                 return OP_X86_ADD_MEMBASE_REG;
13209         case OP_ISUB:
13210                 return OP_X86_SUB_MEMBASE_REG;
13211         case OP_IAND:
13212                 return OP_X86_AND_MEMBASE_REG;
13213         case OP_IOR:
13214                 return OP_X86_OR_MEMBASE_REG;
13215         case OP_IXOR:
13216                 return OP_X86_XOR_MEMBASE_REG;
13217         case OP_IADD_IMM:
13218                 return OP_X86_ADD_MEMBASE_IMM;
13219         case OP_ISUB_IMM:
13220                 return OP_X86_SUB_MEMBASE_IMM;
13221         case OP_IAND_IMM:
13222                 return OP_X86_AND_MEMBASE_IMM;
13223         case OP_IOR_IMM:
13224                 return OP_X86_OR_MEMBASE_IMM;
13225         case OP_IXOR_IMM:
13226                 return OP_X86_XOR_MEMBASE_IMM;
13227         case OP_LADD:
13228                 return OP_AMD64_ADD_MEMBASE_REG;
13229         case OP_LSUB:
13230                 return OP_AMD64_SUB_MEMBASE_REG;
13231         case OP_LAND:
13232                 return OP_AMD64_AND_MEMBASE_REG;
13233         case OP_LOR:
13234                 return OP_AMD64_OR_MEMBASE_REG;
13235         case OP_LXOR:
13236                 return OP_AMD64_XOR_MEMBASE_REG;
13237         case OP_ADD_IMM:
13238         case OP_LADD_IMM:
13239                 return OP_AMD64_ADD_MEMBASE_IMM;
13240         case OP_SUB_IMM:
13241         case OP_LSUB_IMM:
13242                 return OP_AMD64_SUB_MEMBASE_IMM;
13243         case OP_AND_IMM:
13244         case OP_LAND_IMM:
13245                 return OP_AMD64_AND_MEMBASE_IMM;
13246         case OP_OR_IMM:
13247         case OP_LOR_IMM:
13248                 return OP_AMD64_OR_MEMBASE_IMM;
13249         case OP_XOR_IMM:
13250         case OP_LXOR_IMM:
13251                 return OP_AMD64_XOR_MEMBASE_IMM;
13252         case OP_MOVE:
13253                 return OP_NOP;
13254         }
13255 #endif
13256
13257         return -1;
13258 }
13259
13260 static inline int
13261 op_to_op_store_membase (int store_opcode, int opcode)
13262 {
13263 #if defined(TARGET_X86) || defined(TARGET_AMD64)
13264         switch (opcode) {
13265         case OP_ICEQ:
13266                 if (store_opcode == OP_STOREI1_MEMBASE_REG)
13267                         return OP_X86_SETEQ_MEMBASE;
13268         case OP_CNE:
13269                 if (store_opcode == OP_STOREI1_MEMBASE_REG)
13270                         return OP_X86_SETNE_MEMBASE;
13271         }
13272 #endif
13273
13274         return -1;
13275 }
13276
13277 static inline int
13278 op_to_op_src1_membase (MonoCompile *cfg, int load_opcode, int opcode)
13279 {
13280 #ifdef TARGET_X86
13281         /* FIXME: This has sign extension issues */
13282         /*
13283         if ((opcode == OP_ICOMPARE_IMM) && (load_opcode == OP_LOADU1_MEMBASE))
13284                 return OP_X86_COMPARE_MEMBASE8_IMM;
13285         */
13286
13287         if (!((load_opcode == OP_LOAD_MEMBASE) || (load_opcode == OP_LOADI4_MEMBASE) || (load_opcode == OP_LOADU4_MEMBASE)))
13288                 return -1;
13289
13290         switch (opcode) {
13291         case OP_X86_PUSH:
13292                 return OP_X86_PUSH_MEMBASE;
13293         case OP_COMPARE_IMM:
13294         case OP_ICOMPARE_IMM:
13295                 return OP_X86_COMPARE_MEMBASE_IMM;
13296         case OP_COMPARE:
13297         case OP_ICOMPARE:
13298                 return OP_X86_COMPARE_MEMBASE_REG;
13299         }
13300 #endif
13301
13302 #ifdef TARGET_AMD64
13303         /* FIXME: This has sign extension issues */
13304         /*
13305         if ((opcode == OP_ICOMPARE_IMM) && (load_opcode == OP_LOADU1_MEMBASE))
13306                 return OP_X86_COMPARE_MEMBASE8_IMM;
13307         */
13308
13309         switch (opcode) {
13310         case OP_X86_PUSH:
13311                 if ((load_opcode == OP_LOAD_MEMBASE && !cfg->backend->ilp32) || (load_opcode == OP_LOADI8_MEMBASE))
13312                         return OP_X86_PUSH_MEMBASE;
13313                 break;
13314                 /* FIXME: This only works for 32 bit immediates
13315         case OP_COMPARE_IMM:
13316         case OP_LCOMPARE_IMM:
13317                 if ((load_opcode == OP_LOAD_MEMBASE) || (load_opcode == OP_LOADI8_MEMBASE))
13318                         return OP_AMD64_COMPARE_MEMBASE_IMM;
13319                 */
13320         case OP_ICOMPARE_IMM:
13321                 if ((load_opcode == OP_LOADI4_MEMBASE) || (load_opcode == OP_LOADU4_MEMBASE))
13322                         return OP_AMD64_ICOMPARE_MEMBASE_IMM;
13323                 break;
13324         case OP_COMPARE:
13325         case OP_LCOMPARE:
13326                 if (cfg->backend->ilp32 && load_opcode == OP_LOAD_MEMBASE)
13327                         return OP_AMD64_ICOMPARE_MEMBASE_REG;
13328                 if ((load_opcode == OP_LOAD_MEMBASE && !cfg->backend->ilp32) || (load_opcode == OP_LOADI8_MEMBASE))
13329                         return OP_AMD64_COMPARE_MEMBASE_REG;
13330                 break;
13331         case OP_ICOMPARE:
13332                 if ((load_opcode == OP_LOADI4_MEMBASE) || (load_opcode == OP_LOADU4_MEMBASE))
13333                         return OP_AMD64_ICOMPARE_MEMBASE_REG;
13334                 break;
13335         }
13336 #endif
13337
13338         return -1;
13339 }
13340
13341 static inline int
13342 op_to_op_src2_membase (MonoCompile *cfg, int load_opcode, int opcode)
13343 {
13344 #ifdef TARGET_X86
13345         if (!((load_opcode == OP_LOAD_MEMBASE) || (load_opcode == OP_LOADI4_MEMBASE) || (load_opcode == OP_LOADU4_MEMBASE)))
13346                 return -1;
13347         
13348         switch (opcode) {
13349         case OP_COMPARE:
13350         case OP_ICOMPARE:
13351                 return OP_X86_COMPARE_REG_MEMBASE;
13352         case OP_IADD:
13353                 return OP_X86_ADD_REG_MEMBASE;
13354         case OP_ISUB:
13355                 return OP_X86_SUB_REG_MEMBASE;
13356         case OP_IAND:
13357                 return OP_X86_AND_REG_MEMBASE;
13358         case OP_IOR:
13359                 return OP_X86_OR_REG_MEMBASE;
13360         case OP_IXOR:
13361                 return OP_X86_XOR_REG_MEMBASE;
13362         }
13363 #endif
13364
13365 #ifdef TARGET_AMD64
13366         if ((load_opcode == OP_LOADI4_MEMBASE) || (load_opcode == OP_LOADU4_MEMBASE) || (load_opcode == OP_LOAD_MEMBASE && cfg->backend->ilp32)) {
13367                 switch (opcode) {
13368                 case OP_ICOMPARE:
13369                         return OP_AMD64_ICOMPARE_REG_MEMBASE;
13370                 case OP_IADD:
13371                         return OP_X86_ADD_REG_MEMBASE;
13372                 case OP_ISUB:
13373                         return OP_X86_SUB_REG_MEMBASE;
13374                 case OP_IAND:
13375                         return OP_X86_AND_REG_MEMBASE;
13376                 case OP_IOR:
13377                         return OP_X86_OR_REG_MEMBASE;
13378                 case OP_IXOR:
13379                         return OP_X86_XOR_REG_MEMBASE;
13380                 }
13381         } else if ((load_opcode == OP_LOADI8_MEMBASE) || (load_opcode == OP_LOAD_MEMBASE && !cfg->backend->ilp32)) {
13382                 switch (opcode) {
13383                 case OP_COMPARE:
13384                 case OP_LCOMPARE:
13385                         return OP_AMD64_COMPARE_REG_MEMBASE;
13386                 case OP_LADD:
13387                         return OP_AMD64_ADD_REG_MEMBASE;
13388                 case OP_LSUB:
13389                         return OP_AMD64_SUB_REG_MEMBASE;
13390                 case OP_LAND:
13391                         return OP_AMD64_AND_REG_MEMBASE;
13392                 case OP_LOR:
13393                         return OP_AMD64_OR_REG_MEMBASE;
13394                 case OP_LXOR:
13395                         return OP_AMD64_XOR_REG_MEMBASE;
13396                 }
13397         }
13398 #endif
13399
13400         return -1;
13401 }
13402
13403 int
13404 mono_op_to_op_imm_noemul (int opcode)
13405 {
13406         switch (opcode) {
13407 #if SIZEOF_REGISTER == 4 && !defined(MONO_ARCH_NO_EMULATE_LONG_SHIFT_OPS)
13408         case OP_LSHR:
13409         case OP_LSHL:
13410         case OP_LSHR_UN:
13411                 return -1;
13412 #endif
13413 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_EMULATE_DIV)
13414         case OP_IDIV:
13415         case OP_IDIV_UN:
13416         case OP_IREM:
13417         case OP_IREM_UN:
13418                 return -1;
13419 #endif
13420 #if defined(MONO_ARCH_EMULATE_MUL_DIV)
13421         case OP_IMUL:
13422                 return -1;
13423 #endif
13424         default:
13425                 return mono_op_to_op_imm (opcode);
13426         }
13427 }
13428
13429 /**
13430  * mono_handle_global_vregs:
13431  *
13432  *   Make vregs used in more than one bblock 'global', i.e. allocate a variable
13433  * for them.
13434  */
13435 void
13436 mono_handle_global_vregs (MonoCompile *cfg)
13437 {
13438         gint32 *vreg_to_bb;
13439         MonoBasicBlock *bb;
13440         int i, pos;
13441
13442         vreg_to_bb = (gint32 *)mono_mempool_alloc0 (cfg->mempool, sizeof (gint32*) * cfg->next_vreg + 1);
13443
13444 #ifdef MONO_ARCH_SIMD_INTRINSICS
13445         if (cfg->uses_simd_intrinsics)
13446                 mono_simd_simplify_indirection (cfg);
13447 #endif
13448
13449         /* Find local vregs used in more than one bb */
13450         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
13451                 MonoInst *ins = bb->code;       
13452                 int block_num = bb->block_num;
13453
13454                 if (cfg->verbose_level > 2)
13455                         printf ("\nHANDLE-GLOBAL-VREGS BLOCK %d:\n", bb->block_num);
13456
13457                 cfg->cbb = bb;
13458                 for (; ins; ins = ins->next) {
13459                         const char *spec = INS_INFO (ins->opcode);
13460                         int regtype = 0, regindex;
13461                         gint32 prev_bb;
13462
13463                         if (G_UNLIKELY (cfg->verbose_level > 2))
13464                                 mono_print_ins (ins);
13465
13466                         g_assert (ins->opcode >= MONO_CEE_LAST);
13467
13468                         for (regindex = 0; regindex < 4; regindex ++) {
13469                                 int vreg = 0;
13470
13471                                 if (regindex == 0) {
13472                                         regtype = spec [MONO_INST_DEST];
13473                                         if (regtype == ' ')
13474                                                 continue;
13475                                         vreg = ins->dreg;
13476                                 } else if (regindex == 1) {
13477                                         regtype = spec [MONO_INST_SRC1];
13478                                         if (regtype == ' ')
13479                                                 continue;
13480                                         vreg = ins->sreg1;
13481                                 } else if (regindex == 2) {
13482                                         regtype = spec [MONO_INST_SRC2];
13483                                         if (regtype == ' ')
13484                                                 continue;
13485                                         vreg = ins->sreg2;
13486                                 } else if (regindex == 3) {
13487                                         regtype = spec [MONO_INST_SRC3];
13488                                         if (regtype == ' ')
13489                                                 continue;
13490                                         vreg = ins->sreg3;
13491                                 }
13492
13493 #if SIZEOF_REGISTER == 4
13494                                 /* In the LLVM case, the long opcodes are not decomposed */
13495                                 if (regtype == 'l' && !COMPILE_LLVM (cfg)) {
13496                                         /*
13497                                          * Since some instructions reference the original long vreg,
13498                                          * and some reference the two component vregs, it is quite hard
13499                                          * to determine when it needs to be global. So be conservative.
13500                                          */
13501                                         if (!get_vreg_to_inst (cfg, vreg)) {
13502                                                 mono_compile_create_var_for_vreg (cfg, &mono_defaults.int64_class->byval_arg, OP_LOCAL, vreg);
13503
13504                                                 if (cfg->verbose_level > 2)
13505                                                         printf ("LONG VREG R%d made global.\n", vreg);
13506                                         }
13507
13508                                         /*
13509                                          * Make the component vregs volatile since the optimizations can
13510                                          * get confused otherwise.
13511                                          */
13512                                         get_vreg_to_inst (cfg, MONO_LVREG_LS (vreg))->flags |= MONO_INST_VOLATILE;
13513                                         get_vreg_to_inst (cfg, MONO_LVREG_MS (vreg))->flags |= MONO_INST_VOLATILE;
13514                                 }
13515 #endif
13516
13517                                 g_assert (vreg != -1);
13518
13519                                 prev_bb = vreg_to_bb [vreg];
13520                                 if (prev_bb == 0) {
13521                                         /* 0 is a valid block num */
13522                                         vreg_to_bb [vreg] = block_num + 1;
13523                                 } else if ((prev_bb != block_num + 1) && (prev_bb != -1)) {
13524                                         if (((regtype == 'i' && (vreg < MONO_MAX_IREGS))) || (regtype == 'f' && (vreg < MONO_MAX_FREGS)))
13525                                                 continue;
13526
13527                                         if (!get_vreg_to_inst (cfg, vreg)) {
13528                                                 if (G_UNLIKELY (cfg->verbose_level > 2))
13529                                                         printf ("VREG R%d used in BB%d and BB%d made global.\n", vreg, vreg_to_bb [vreg], block_num);
13530
13531                                                 switch (regtype) {
13532                                                 case 'i':
13533                                                         if (vreg_is_ref (cfg, vreg))
13534                                                                 mono_compile_create_var_for_vreg (cfg, &mono_defaults.object_class->byval_arg, OP_LOCAL, vreg);
13535                                                         else
13536                                                                 mono_compile_create_var_for_vreg (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL, vreg);
13537                                                         break;
13538                                                 case 'l':
13539                                                         mono_compile_create_var_for_vreg (cfg, &mono_defaults.int64_class->byval_arg, OP_LOCAL, vreg);
13540                                                         break;
13541                                                 case 'f':
13542                                                         mono_compile_create_var_for_vreg (cfg, &mono_defaults.double_class->byval_arg, OP_LOCAL, vreg);
13543                                                         break;
13544                                                 case 'v':
13545                                                 case 'x':
13546                                                         mono_compile_create_var_for_vreg (cfg, &ins->klass->byval_arg, OP_LOCAL, vreg);
13547                                                         break;
13548                                                 default:
13549                                                         g_assert_not_reached ();
13550                                                 }
13551                                         }
13552
13553                                         /* Flag as having been used in more than one bb */
13554                                         vreg_to_bb [vreg] = -1;
13555                                 }
13556                         }
13557                 }
13558         }
13559
13560         /* If a variable is used in only one bblock, convert it into a local vreg */
13561         for (i = 0; i < cfg->num_varinfo; i++) {
13562                 MonoInst *var = cfg->varinfo [i];
13563                 MonoMethodVar *vmv = MONO_VARINFO (cfg, i);
13564
13565                 switch (var->type) {
13566                 case STACK_I4:
13567                 case STACK_OBJ:
13568                 case STACK_PTR:
13569                 case STACK_MP:
13570                 case STACK_VTYPE:
13571 #if SIZEOF_REGISTER == 8
13572                 case STACK_I8:
13573 #endif
13574 #if !defined(TARGET_X86)
13575                 /* Enabling this screws up the fp stack on x86 */
13576                 case STACK_R8:
13577 #endif
13578                         if (mono_arch_is_soft_float ())
13579                                 break;
13580
13581                         /*
13582                         if (var->type == STACK_VTYPE && cfg->gsharedvt && mini_is_gsharedvt_variable_type (var->inst_vtype))
13583                                 break;
13584                         */
13585
13586                         /* Arguments are implicitly global */
13587                         /* Putting R4 vars into registers doesn't work currently */
13588                         /* The gsharedvt vars are implicitly referenced by ldaddr opcodes, but those opcodes are only generated later */
13589                         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) {
13590                                 /* 
13591                                  * Make that the variable's liveness interval doesn't contain a call, since
13592                                  * that would cause the lvreg to be spilled, making the whole optimization
13593                                  * useless.
13594                                  */
13595                                 /* This is too slow for JIT compilation */
13596 #if 0
13597                                 if (cfg->compile_aot && vreg_to_bb [var->dreg]) {
13598                                         MonoInst *ins;
13599                                         int def_index, call_index, ins_index;
13600                                         gboolean spilled = FALSE;
13601
13602                                         def_index = -1;
13603                                         call_index = -1;
13604                                         ins_index = 0;
13605                                         for (ins = vreg_to_bb [var->dreg]->code; ins; ins = ins->next) {
13606                                                 const char *spec = INS_INFO (ins->opcode);
13607
13608                                                 if ((spec [MONO_INST_DEST] != ' ') && (ins->dreg == var->dreg))
13609                                                         def_index = ins_index;
13610
13611                                                 if (((spec [MONO_INST_SRC1] != ' ') && (ins->sreg1 == var->dreg)) ||
13612                                                         ((spec [MONO_INST_SRC1] != ' ') && (ins->sreg1 == var->dreg))) {
13613                                                         if (call_index > def_index) {
13614                                                                 spilled = TRUE;
13615                                                                 break;
13616                                                         }
13617                                                 }
13618
13619                                                 if (MONO_IS_CALL (ins))
13620                                                         call_index = ins_index;
13621
13622                                                 ins_index ++;
13623                                         }
13624
13625                                         if (spilled)
13626                                                 break;
13627                                 }
13628 #endif
13629
13630                                 if (G_UNLIKELY (cfg->verbose_level > 2))
13631                                         printf ("CONVERTED R%d(%d) TO VREG.\n", var->dreg, vmv->idx);
13632                                 var->flags |= MONO_INST_IS_DEAD;
13633                                 cfg->vreg_to_inst [var->dreg] = NULL;
13634                         }
13635                         break;
13636                 }
13637         }
13638
13639         /* 
13640          * Compress the varinfo and vars tables so the liveness computation is faster and
13641          * takes up less space.
13642          */
13643         pos = 0;
13644         for (i = 0; i < cfg->num_varinfo; ++i) {
13645                 MonoInst *var = cfg->varinfo [i];
13646                 if (pos < i && cfg->locals_start == i)
13647                         cfg->locals_start = pos;
13648                 if (!(var->flags & MONO_INST_IS_DEAD)) {
13649                         if (pos < i) {
13650                                 cfg->varinfo [pos] = cfg->varinfo [i];
13651                                 cfg->varinfo [pos]->inst_c0 = pos;
13652                                 memcpy (&cfg->vars [pos], &cfg->vars [i], sizeof (MonoMethodVar));
13653                                 cfg->vars [pos].idx = pos;
13654 #if SIZEOF_REGISTER == 4
13655                                 if (cfg->varinfo [pos]->type == STACK_I8) {
13656                                         /* Modify the two component vars too */
13657                                         MonoInst *var1;
13658
13659                                         var1 = get_vreg_to_inst (cfg, MONO_LVREG_LS (cfg->varinfo [pos]->dreg));
13660                                         var1->inst_c0 = pos;
13661                                         var1 = get_vreg_to_inst (cfg, MONO_LVREG_MS (cfg->varinfo [pos]->dreg));
13662                                         var1->inst_c0 = pos;
13663                                 }
13664 #endif
13665                         }
13666                         pos ++;
13667                 }
13668         }
13669         cfg->num_varinfo = pos;
13670         if (cfg->locals_start > cfg->num_varinfo)
13671                 cfg->locals_start = cfg->num_varinfo;
13672 }
13673
13674 /*
13675  * mono_allocate_gsharedvt_vars:
13676  *
13677  *   Allocate variables with gsharedvt types to entries in the MonoGSharedVtMethodRuntimeInfo.entries array.
13678  * Initialize cfg->gsharedvt_vreg_to_idx with the mapping between vregs and indexes.
13679  */
13680 void
13681 mono_allocate_gsharedvt_vars (MonoCompile *cfg)
13682 {
13683         int i;
13684
13685         cfg->gsharedvt_vreg_to_idx = (int *)mono_mempool_alloc0 (cfg->mempool, sizeof (int) * cfg->next_vreg);
13686
13687         for (i = 0; i < cfg->num_varinfo; ++i) {
13688                 MonoInst *ins = cfg->varinfo [i];
13689                 int idx;
13690
13691                 if (mini_is_gsharedvt_variable_type (ins->inst_vtype)) {
13692                         if (i >= cfg->locals_start) {
13693                                 /* Local */
13694                                 idx = get_gsharedvt_info_slot (cfg, ins->inst_vtype, MONO_RGCTX_INFO_LOCAL_OFFSET);
13695                                 cfg->gsharedvt_vreg_to_idx [ins->dreg] = idx + 1;
13696                                 ins->opcode = OP_GSHAREDVT_LOCAL;
13697                                 ins->inst_imm = idx;
13698                         } else {
13699                                 /* Arg */
13700                                 cfg->gsharedvt_vreg_to_idx [ins->dreg] = -1;
13701                                 ins->opcode = OP_GSHAREDVT_ARG_REGOFFSET;
13702                         }
13703                 }
13704         }
13705 }
13706
13707 /**
13708  * mono_spill_global_vars:
13709  *
13710  *   Generate spill code for variables which are not allocated to registers, 
13711  * and replace vregs with their allocated hregs. *need_local_opts is set to TRUE if
13712  * code is generated which could be optimized by the local optimization passes.
13713  */
13714 void
13715 mono_spill_global_vars (MonoCompile *cfg, gboolean *need_local_opts)
13716 {
13717         MonoBasicBlock *bb;
13718         char spec2 [16];
13719         int orig_next_vreg;
13720         guint32 *vreg_to_lvreg;
13721         guint32 *lvregs;
13722         guint32 i, lvregs_len, lvregs_size;
13723         gboolean dest_has_lvreg = FALSE;
13724         MonoStackType stacktypes [128];
13725         MonoInst **live_range_start, **live_range_end;
13726         MonoBasicBlock **live_range_start_bb, **live_range_end_bb;
13727
13728         *need_local_opts = FALSE;
13729
13730         memset (spec2, 0, sizeof (spec2));
13731
13732         /* FIXME: Move this function to mini.c */
13733         stacktypes ['i'] = STACK_PTR;
13734         stacktypes ['l'] = STACK_I8;
13735         stacktypes ['f'] = STACK_R8;
13736 #ifdef MONO_ARCH_SIMD_INTRINSICS
13737         stacktypes ['x'] = STACK_VTYPE;
13738 #endif
13739
13740 #if SIZEOF_REGISTER == 4
13741         /* Create MonoInsts for longs */
13742         for (i = 0; i < cfg->num_varinfo; i++) {
13743                 MonoInst *ins = cfg->varinfo [i];
13744
13745                 if ((ins->opcode != OP_REGVAR) && !(ins->flags & MONO_INST_IS_DEAD)) {
13746                         switch (ins->type) {
13747                         case STACK_R8:
13748                         case STACK_I8: {
13749                                 MonoInst *tree;
13750
13751                                 if (ins->type == STACK_R8 && !COMPILE_SOFT_FLOAT (cfg))
13752                                         break;
13753
13754                                 g_assert (ins->opcode == OP_REGOFFSET);
13755
13756                                 tree = get_vreg_to_inst (cfg, MONO_LVREG_LS (ins->dreg));
13757                                 g_assert (tree);
13758                                 tree->opcode = OP_REGOFFSET;
13759                                 tree->inst_basereg = ins->inst_basereg;
13760                                 tree->inst_offset = ins->inst_offset + MINI_LS_WORD_OFFSET;
13761
13762                                 tree = get_vreg_to_inst (cfg, MONO_LVREG_MS (ins->dreg));
13763                                 g_assert (tree);
13764                                 tree->opcode = OP_REGOFFSET;
13765                                 tree->inst_basereg = ins->inst_basereg;
13766                                 tree->inst_offset = ins->inst_offset + MINI_MS_WORD_OFFSET;
13767                                 break;
13768                         }
13769                         default:
13770                                 break;
13771                         }
13772                 }
13773         }
13774 #endif
13775
13776         if (cfg->compute_gc_maps) {
13777                 /* registers need liveness info even for !non refs */
13778                 for (i = 0; i < cfg->num_varinfo; i++) {
13779                         MonoInst *ins = cfg->varinfo [i];
13780
13781                         if (ins->opcode == OP_REGVAR)
13782                                 ins->flags |= MONO_INST_GC_TRACK;
13783                 }
13784         }
13785                 
13786         /* FIXME: widening and truncation */
13787
13788         /*
13789          * As an optimization, when a variable allocated to the stack is first loaded into 
13790          * an lvreg, we will remember the lvreg and use it the next time instead of loading
13791          * the variable again.
13792          */
13793         orig_next_vreg = cfg->next_vreg;
13794         vreg_to_lvreg = (guint32 *)mono_mempool_alloc0 (cfg->mempool, sizeof (guint32) * cfg->next_vreg);
13795         lvregs_size = 1024;
13796         lvregs = (guint32 *)mono_mempool_alloc (cfg->mempool, sizeof (guint32) * lvregs_size);
13797         lvregs_len = 0;
13798
13799         /* 
13800          * These arrays contain the first and last instructions accessing a given
13801          * variable.
13802          * Since we emit bblocks in the same order we process them here, and we
13803          * don't split live ranges, these will precisely describe the live range of
13804          * the variable, i.e. the instruction range where a valid value can be found
13805          * in the variables location.
13806          * The live range is computed using the liveness info computed by the liveness pass.
13807          * We can't use vmv->range, since that is an abstract live range, and we need
13808          * one which is instruction precise.
13809          * FIXME: Variables used in out-of-line bblocks have a hole in their live range.
13810          */
13811         /* FIXME: Only do this if debugging info is requested */
13812         live_range_start = g_new0 (MonoInst*, cfg->next_vreg);
13813         live_range_end = g_new0 (MonoInst*, cfg->next_vreg);
13814         live_range_start_bb = g_new (MonoBasicBlock*, cfg->next_vreg);
13815         live_range_end_bb = g_new (MonoBasicBlock*, cfg->next_vreg);
13816         
13817         /* Add spill loads/stores */
13818         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
13819                 MonoInst *ins;
13820
13821                 if (cfg->verbose_level > 2)
13822                         printf ("\nSPILL BLOCK %d:\n", bb->block_num);
13823
13824                 /* Clear vreg_to_lvreg array */
13825                 for (i = 0; i < lvregs_len; i++)
13826                         vreg_to_lvreg [lvregs [i]] = 0;
13827                 lvregs_len = 0;
13828
13829                 cfg->cbb = bb;
13830                 MONO_BB_FOR_EACH_INS (bb, ins) {
13831                         const char *spec = INS_INFO (ins->opcode);
13832                         int regtype, srcindex, sreg, tmp_reg, prev_dreg, num_sregs;
13833                         gboolean store, no_lvreg;
13834                         int sregs [MONO_MAX_SRC_REGS];
13835
13836                         if (G_UNLIKELY (cfg->verbose_level > 2))
13837                                 mono_print_ins (ins);
13838
13839                         if (ins->opcode == OP_NOP)
13840                                 continue;
13841
13842                         /* 
13843                          * We handle LDADDR here as well, since it can only be decomposed
13844                          * when variable addresses are known.
13845                          */
13846                         if (ins->opcode == OP_LDADDR) {
13847                                 MonoInst *var = (MonoInst *)ins->inst_p0;
13848
13849                                 if (var->opcode == OP_VTARG_ADDR) {
13850                                         /* Happens on SPARC/S390 where vtypes are passed by reference */
13851                                         MonoInst *vtaddr = var->inst_left;
13852                                         if (vtaddr->opcode == OP_REGVAR) {
13853                                                 ins->opcode = OP_MOVE;
13854                                                 ins->sreg1 = vtaddr->dreg;
13855                                         }
13856                                         else if (var->inst_left->opcode == OP_REGOFFSET) {
13857                                                 ins->opcode = OP_LOAD_MEMBASE;
13858                                                 ins->inst_basereg = vtaddr->inst_basereg;
13859                                                 ins->inst_offset = vtaddr->inst_offset;
13860                                         } else
13861                                                 NOT_IMPLEMENTED;
13862                                 } else if (cfg->gsharedvt && cfg->gsharedvt_vreg_to_idx [var->dreg] < 0) {
13863                                         /* gsharedvt arg passed by ref */
13864                                         g_assert (var->opcode == OP_GSHAREDVT_ARG_REGOFFSET);
13865
13866                                         ins->opcode = OP_LOAD_MEMBASE;
13867                                         ins->inst_basereg = var->inst_basereg;
13868                                         ins->inst_offset = var->inst_offset;
13869                                 } else if (cfg->gsharedvt && cfg->gsharedvt_vreg_to_idx [var->dreg]) {
13870                                         MonoInst *load, *load2, *load3;
13871                                         int idx = cfg->gsharedvt_vreg_to_idx [var->dreg] - 1;
13872                                         int reg1, reg2, reg3;
13873                                         MonoInst *info_var = cfg->gsharedvt_info_var;
13874                                         MonoInst *locals_var = cfg->gsharedvt_locals_var;
13875
13876                                         /*
13877                                          * gsharedvt local.
13878                                          * Compute the address of the local as gsharedvt_locals_var + gsharedvt_info_var->locals_offsets [idx].
13879                                          */
13880
13881                                         g_assert (var->opcode == OP_GSHAREDVT_LOCAL);
13882
13883                                         g_assert (info_var);
13884                                         g_assert (locals_var);
13885
13886                                         /* Mark the instruction used to compute the locals var as used */
13887                                         cfg->gsharedvt_locals_var_ins = NULL;
13888
13889                                         /* Load the offset */
13890                                         if (info_var->opcode == OP_REGOFFSET) {
13891                                                 reg1 = alloc_ireg (cfg);
13892                                                 NEW_LOAD_MEMBASE (cfg, load, OP_LOAD_MEMBASE, reg1, info_var->inst_basereg, info_var->inst_offset);
13893                                         } else if (info_var->opcode == OP_REGVAR) {
13894                                                 load = NULL;
13895                                                 reg1 = info_var->dreg;
13896                                         } else {
13897                                                 g_assert_not_reached ();
13898                                         }
13899                                         reg2 = alloc_ireg (cfg);
13900                                         NEW_LOAD_MEMBASE (cfg, load2, OP_LOADI4_MEMBASE, reg2, reg1, MONO_STRUCT_OFFSET (MonoGSharedVtMethodRuntimeInfo, entries) + (idx * sizeof (gpointer)));
13901                                         /* Load the locals area address */
13902                                         reg3 = alloc_ireg (cfg);
13903                                         if (locals_var->opcode == OP_REGOFFSET) {
13904                                                 NEW_LOAD_MEMBASE (cfg, load3, OP_LOAD_MEMBASE, reg3, locals_var->inst_basereg, locals_var->inst_offset);
13905                                         } else if (locals_var->opcode == OP_REGVAR) {
13906                                                 NEW_UNALU (cfg, load3, OP_MOVE, reg3, locals_var->dreg);
13907                                         } else {
13908                                                 g_assert_not_reached ();
13909                                         }
13910                                         /* Compute the address */
13911                                         ins->opcode = OP_PADD;
13912                                         ins->sreg1 = reg3;
13913                                         ins->sreg2 = reg2;
13914
13915                                         mono_bblock_insert_before_ins (bb, ins, load3);
13916                                         mono_bblock_insert_before_ins (bb, load3, load2);
13917                                         if (load)
13918                                                 mono_bblock_insert_before_ins (bb, load2, load);
13919                                 } else {
13920                                         g_assert (var->opcode == OP_REGOFFSET);
13921
13922                                         ins->opcode = OP_ADD_IMM;
13923                                         ins->sreg1 = var->inst_basereg;
13924                                         ins->inst_imm = var->inst_offset;
13925                                 }
13926
13927                                 *need_local_opts = TRUE;
13928                                 spec = INS_INFO (ins->opcode);
13929                         }
13930
13931                         if (ins->opcode < MONO_CEE_LAST) {
13932                                 mono_print_ins (ins);
13933                                 g_assert_not_reached ();
13934                         }
13935
13936                         /*
13937                          * Store opcodes have destbasereg in the dreg, but in reality, it is an
13938                          * src register.
13939                          * FIXME:
13940                          */
13941                         if (MONO_IS_STORE_MEMBASE (ins)) {
13942                                 tmp_reg = ins->dreg;
13943                                 ins->dreg = ins->sreg2;
13944                                 ins->sreg2 = tmp_reg;
13945                                 store = TRUE;
13946
13947                                 spec2 [MONO_INST_DEST] = ' ';
13948                                 spec2 [MONO_INST_SRC1] = spec [MONO_INST_SRC1];
13949                                 spec2 [MONO_INST_SRC2] = spec [MONO_INST_DEST];
13950                                 spec2 [MONO_INST_SRC3] = ' ';
13951                                 spec = spec2;
13952                         } else if (MONO_IS_STORE_MEMINDEX (ins))
13953                                 g_assert_not_reached ();
13954                         else
13955                                 store = FALSE;
13956                         no_lvreg = FALSE;
13957
13958                         if (G_UNLIKELY (cfg->verbose_level > 2)) {
13959                                 printf ("\t %.3s %d", spec, ins->dreg);
13960                                 num_sregs = mono_inst_get_src_registers (ins, sregs);
13961                                 for (srcindex = 0; srcindex < num_sregs; ++srcindex)
13962                                         printf (" %d", sregs [srcindex]);
13963                                 printf ("\n");
13964                         }
13965
13966                         /***************/
13967                         /*    DREG     */
13968                         /***************/
13969                         regtype = spec [MONO_INST_DEST];
13970                         g_assert (((ins->dreg == -1) && (regtype == ' ')) || ((ins->dreg != -1) && (regtype != ' ')));
13971                         prev_dreg = -1;
13972
13973                         if ((ins->dreg != -1) && get_vreg_to_inst (cfg, ins->dreg)) {
13974                                 MonoInst *var = get_vreg_to_inst (cfg, ins->dreg);
13975                                 MonoInst *store_ins;
13976                                 int store_opcode;
13977                                 MonoInst *def_ins = ins;
13978                                 int dreg = ins->dreg; /* The original vreg */
13979
13980                                 store_opcode = mono_type_to_store_membase (cfg, var->inst_vtype);
13981
13982                                 if (var->opcode == OP_REGVAR) {
13983                                         ins->dreg = var->dreg;
13984                                 } 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)) {
13985                                         /* 
13986                                          * Instead of emitting a load+store, use a _membase opcode.
13987                                          */
13988                                         g_assert (var->opcode == OP_REGOFFSET);
13989                                         if (ins->opcode == OP_MOVE) {
13990                                                 NULLIFY_INS (ins);
13991                                                 def_ins = NULL;
13992                                         } else {
13993                                                 ins->opcode = op_to_op_dest_membase (store_opcode, ins->opcode);
13994                                                 ins->inst_basereg = var->inst_basereg;
13995                                                 ins->inst_offset = var->inst_offset;
13996                                                 ins->dreg = -1;
13997                                         }
13998                                         spec = INS_INFO (ins->opcode);
13999                                 } else {
14000                                         guint32 lvreg;
14001
14002                                         g_assert (var->opcode == OP_REGOFFSET);
14003
14004                                         prev_dreg = ins->dreg;
14005
14006                                         /* Invalidate any previous lvreg for this vreg */
14007                                         vreg_to_lvreg [ins->dreg] = 0;
14008
14009                                         lvreg = 0;
14010
14011                                         if (COMPILE_SOFT_FLOAT (cfg) && store_opcode == OP_STORER8_MEMBASE_REG) {
14012                                                 regtype = 'l';
14013                                                 store_opcode = OP_STOREI8_MEMBASE_REG;
14014                                         }
14015
14016                                         ins->dreg = alloc_dreg (cfg, stacktypes [regtype]);
14017
14018 #if SIZEOF_REGISTER != 8
14019                                         if (regtype == 'l') {
14020                                                 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));
14021                                                 mono_bblock_insert_after_ins (bb, ins, store_ins);
14022                                                 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));
14023                                                 mono_bblock_insert_after_ins (bb, ins, store_ins);
14024                                                 def_ins = store_ins;
14025                                         }
14026                                         else
14027 #endif
14028                                         {
14029                                                 g_assert (store_opcode != OP_STOREV_MEMBASE);
14030
14031                                                 /* Try to fuse the store into the instruction itself */
14032                                                 /* FIXME: Add more instructions */
14033                                                 if (!lvreg && ((ins->opcode == OP_ICONST) || ((ins->opcode == OP_I8CONST) && (ins->inst_c0 == 0)))) {
14034                                                         ins->opcode = store_membase_reg_to_store_membase_imm (store_opcode);
14035                                                         ins->inst_imm = ins->inst_c0;
14036                                                         ins->inst_destbasereg = var->inst_basereg;
14037                                                         ins->inst_offset = var->inst_offset;
14038                                                         spec = INS_INFO (ins->opcode);
14039                                                 } else if (!lvreg && ((ins->opcode == OP_MOVE) || (ins->opcode == OP_FMOVE) || (ins->opcode == OP_LMOVE) || (ins->opcode == OP_RMOVE))) {
14040                                                         ins->opcode = store_opcode;
14041                                                         ins->inst_destbasereg = var->inst_basereg;
14042                                                         ins->inst_offset = var->inst_offset;
14043
14044                                                         no_lvreg = TRUE;
14045
14046                                                         tmp_reg = ins->dreg;
14047                                                         ins->dreg = ins->sreg2;
14048                                                         ins->sreg2 = tmp_reg;
14049                                                         store = TRUE;
14050
14051                                                         spec2 [MONO_INST_DEST] = ' ';
14052                                                         spec2 [MONO_INST_SRC1] = spec [MONO_INST_SRC1];
14053                                                         spec2 [MONO_INST_SRC2] = spec [MONO_INST_DEST];
14054                                                         spec2 [MONO_INST_SRC3] = ' ';
14055                                                         spec = spec2;
14056                                                 } else if (!lvreg && (op_to_op_store_membase (store_opcode, ins->opcode) != -1)) {
14057                                                         // FIXME: The backends expect the base reg to be in inst_basereg
14058                                                         ins->opcode = op_to_op_store_membase (store_opcode, ins->opcode);
14059                                                         ins->dreg = -1;
14060                                                         ins->inst_basereg = var->inst_basereg;
14061                                                         ins->inst_offset = var->inst_offset;
14062                                                         spec = INS_INFO (ins->opcode);
14063                                                 } else {
14064                                                         /* printf ("INS: "); mono_print_ins (ins); */
14065                                                         /* Create a store instruction */
14066                                                         NEW_STORE_MEMBASE (cfg, store_ins, store_opcode, var->inst_basereg, var->inst_offset, ins->dreg);
14067
14068                                                         /* Insert it after the instruction */
14069                                                         mono_bblock_insert_after_ins (bb, ins, store_ins);
14070
14071                                                         def_ins = store_ins;
14072
14073                                                         /* 
14074                                                          * We can't assign ins->dreg to var->dreg here, since the
14075                                                          * sregs could use it. So set a flag, and do it after
14076                                                          * the sregs.
14077                                                          */
14078                                                         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)))
14079                                                                 dest_has_lvreg = TRUE;
14080                                                 }
14081                                         }
14082                                 }
14083
14084                                 if (def_ins && !live_range_start [dreg]) {
14085                                         live_range_start [dreg] = def_ins;
14086                                         live_range_start_bb [dreg] = bb;
14087                                 }
14088
14089                                 if (cfg->compute_gc_maps && def_ins && (var->flags & MONO_INST_GC_TRACK)) {
14090                                         MonoInst *tmp;
14091
14092                                         MONO_INST_NEW (cfg, tmp, OP_GC_LIVENESS_DEF);
14093                                         tmp->inst_c1 = dreg;
14094                                         mono_bblock_insert_after_ins (bb, def_ins, tmp);
14095                                 }
14096                         }
14097
14098                         /************/
14099                         /*  SREGS   */
14100                         /************/
14101                         num_sregs = mono_inst_get_src_registers (ins, sregs);
14102                         for (srcindex = 0; srcindex < 3; ++srcindex) {
14103                                 regtype = spec [MONO_INST_SRC1 + srcindex];
14104                                 sreg = sregs [srcindex];
14105
14106                                 g_assert (((sreg == -1) && (regtype == ' ')) || ((sreg != -1) && (regtype != ' ')));
14107                                 if ((sreg != -1) && get_vreg_to_inst (cfg, sreg)) {
14108                                         MonoInst *var = get_vreg_to_inst (cfg, sreg);
14109                                         MonoInst *use_ins = ins;
14110                                         MonoInst *load_ins;
14111                                         guint32 load_opcode;
14112
14113                                         if (var->opcode == OP_REGVAR) {
14114                                                 sregs [srcindex] = var->dreg;
14115                                                 //mono_inst_set_src_registers (ins, sregs);
14116                                                 live_range_end [sreg] = use_ins;
14117                                                 live_range_end_bb [sreg] = bb;
14118
14119                                                 if (cfg->compute_gc_maps && var->dreg < orig_next_vreg && (var->flags & MONO_INST_GC_TRACK)) {
14120                                                         MonoInst *tmp;
14121
14122                                                         MONO_INST_NEW (cfg, tmp, OP_GC_LIVENESS_USE);
14123                                                         /* var->dreg is a hreg */
14124                                                         tmp->inst_c1 = sreg;
14125                                                         mono_bblock_insert_after_ins (bb, ins, tmp);
14126                                                 }
14127
14128                                                 continue;
14129                                         }
14130
14131                                         g_assert (var->opcode == OP_REGOFFSET);
14132                                                 
14133                                         load_opcode = mono_type_to_load_membase (cfg, var->inst_vtype);
14134
14135                                         g_assert (load_opcode != OP_LOADV_MEMBASE);
14136
14137                                         if (vreg_to_lvreg [sreg]) {
14138                                                 g_assert (vreg_to_lvreg [sreg] != -1);
14139
14140                                                 /* The variable is already loaded to an lvreg */
14141                                                 if (G_UNLIKELY (cfg->verbose_level > 2))
14142                                                         printf ("\t\tUse lvreg R%d for R%d.\n", vreg_to_lvreg [sreg], sreg);
14143                                                 sregs [srcindex] = vreg_to_lvreg [sreg];
14144                                                 //mono_inst_set_src_registers (ins, sregs);
14145                                                 continue;
14146                                         }
14147
14148                                         /* Try to fuse the load into the instruction */
14149                                         if ((srcindex == 0) && (op_to_op_src1_membase (cfg, load_opcode, ins->opcode) != -1)) {
14150                                                 ins->opcode = op_to_op_src1_membase (cfg, load_opcode, ins->opcode);
14151                                                 sregs [0] = var->inst_basereg;
14152                                                 //mono_inst_set_src_registers (ins, sregs);
14153                                                 ins->inst_offset = var->inst_offset;
14154                                         } else if ((srcindex == 1) && (op_to_op_src2_membase (cfg, load_opcode, ins->opcode) != -1)) {
14155                                                 ins->opcode = op_to_op_src2_membase (cfg, load_opcode, ins->opcode);
14156                                                 sregs [1] = var->inst_basereg;
14157                                                 //mono_inst_set_src_registers (ins, sregs);
14158                                                 ins->inst_offset = var->inst_offset;
14159                                         } else {
14160                                                 if (MONO_IS_REAL_MOVE (ins)) {
14161                                                         ins->opcode = OP_NOP;
14162                                                         sreg = ins->dreg;
14163                                                 } else {
14164                                                         //printf ("%d ", srcindex); mono_print_ins (ins);
14165
14166                                                         sreg = alloc_dreg (cfg, stacktypes [regtype]);
14167
14168                                                         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) {
14169                                                                 if (var->dreg == prev_dreg) {
14170                                                                         /*
14171                                                                          * sreg refers to the value loaded by the load
14172                                                                          * emitted below, but we need to use ins->dreg
14173                                                                          * since it refers to the store emitted earlier.
14174                                                                          */
14175                                                                         sreg = ins->dreg;
14176                                                                 }
14177                                                                 g_assert (sreg != -1);
14178                                                                 vreg_to_lvreg [var->dreg] = sreg;
14179                                                                 if (lvregs_len >= lvregs_size) {
14180                                                                         guint32 *new_lvregs = mono_mempool_alloc0 (cfg->mempool, sizeof (guint32) * lvregs_size * 2);
14181                                                                         memcpy (new_lvregs, lvregs, sizeof (guint32) * lvregs_size);
14182                                                                         lvregs = new_lvregs;
14183                                                                         lvregs_size *= 2;
14184                                                                 }
14185                                                                 lvregs [lvregs_len ++] = var->dreg;
14186                                                         }
14187                                                 }
14188
14189                                                 sregs [srcindex] = sreg;
14190                                                 //mono_inst_set_src_registers (ins, sregs);
14191
14192 #if SIZEOF_REGISTER != 8
14193                                                 if (regtype == 'l') {
14194                                                         NEW_LOAD_MEMBASE (cfg, load_ins, OP_LOADI4_MEMBASE, MONO_LVREG_MS (sreg), var->inst_basereg, var->inst_offset + MINI_MS_WORD_OFFSET);
14195                                                         mono_bblock_insert_before_ins (bb, ins, load_ins);
14196                                                         NEW_LOAD_MEMBASE (cfg, load_ins, OP_LOADI4_MEMBASE, MONO_LVREG_LS (sreg), var->inst_basereg, var->inst_offset + MINI_LS_WORD_OFFSET);
14197                                                         mono_bblock_insert_before_ins (bb, ins, load_ins);
14198                                                         use_ins = load_ins;
14199                                                 }
14200                                                 else
14201 #endif
14202                                                 {
14203 #if SIZEOF_REGISTER == 4
14204                                                         g_assert (load_opcode != OP_LOADI8_MEMBASE);
14205 #endif
14206                                                         NEW_LOAD_MEMBASE (cfg, load_ins, load_opcode, sreg, var->inst_basereg, var->inst_offset);
14207                                                         mono_bblock_insert_before_ins (bb, ins, load_ins);
14208                                                         use_ins = load_ins;
14209                                                 }
14210                                         }
14211
14212                                         if (var->dreg < orig_next_vreg) {
14213                                                 live_range_end [var->dreg] = use_ins;
14214                                                 live_range_end_bb [var->dreg] = bb;
14215                                         }
14216
14217                                         if (cfg->compute_gc_maps && var->dreg < orig_next_vreg && (var->flags & MONO_INST_GC_TRACK)) {
14218                                                 MonoInst *tmp;
14219
14220                                                 MONO_INST_NEW (cfg, tmp, OP_GC_LIVENESS_USE);
14221                                                 tmp->inst_c1 = var->dreg;
14222                                                 mono_bblock_insert_after_ins (bb, ins, tmp);
14223                                         }
14224                                 }
14225                         }
14226                         mono_inst_set_src_registers (ins, sregs);
14227
14228                         if (dest_has_lvreg) {
14229                                 g_assert (ins->dreg != -1);
14230                                 vreg_to_lvreg [prev_dreg] = ins->dreg;
14231                                 if (lvregs_len >= lvregs_size) {
14232                                         guint32 *new_lvregs = mono_mempool_alloc0 (cfg->mempool, sizeof (guint32) * lvregs_size * 2);
14233                                         memcpy (new_lvregs, lvregs, sizeof (guint32) * lvregs_size);
14234                                         lvregs = new_lvregs;
14235                                         lvregs_size *= 2;
14236                                 }
14237                                 lvregs [lvregs_len ++] = prev_dreg;
14238                                 dest_has_lvreg = FALSE;
14239                         }
14240
14241                         if (store) {
14242                                 tmp_reg = ins->dreg;
14243                                 ins->dreg = ins->sreg2;
14244                                 ins->sreg2 = tmp_reg;
14245                         }
14246
14247                         if (MONO_IS_CALL (ins)) {
14248                                 /* Clear vreg_to_lvreg array */
14249                                 for (i = 0; i < lvregs_len; i++)
14250                                         vreg_to_lvreg [lvregs [i]] = 0;
14251                                 lvregs_len = 0;
14252                         } else if (ins->opcode == OP_NOP) {
14253                                 ins->dreg = -1;
14254                                 MONO_INST_NULLIFY_SREGS (ins);
14255                         }
14256
14257                         if (cfg->verbose_level > 2)
14258                                 mono_print_ins_index (1, ins);
14259                 }
14260
14261                 /* Extend the live range based on the liveness info */
14262                 if (cfg->compute_precise_live_ranges && bb->live_out_set && bb->code) {
14263                         for (i = 0; i < cfg->num_varinfo; i ++) {
14264                                 MonoMethodVar *vi = MONO_VARINFO (cfg, i);
14265
14266                                 if (vreg_is_volatile (cfg, vi->vreg))
14267                                         /* The liveness info is incomplete */
14268                                         continue;
14269
14270                                 if (mono_bitset_test_fast (bb->live_in_set, i) && !live_range_start [vi->vreg]) {
14271                                         /* Live from at least the first ins of this bb */
14272                                         live_range_start [vi->vreg] = bb->code;
14273                                         live_range_start_bb [vi->vreg] = bb;
14274                                 }
14275
14276                                 if (mono_bitset_test_fast (bb->live_out_set, i)) {
14277                                         /* Live at least until the last ins of this bb */
14278                                         live_range_end [vi->vreg] = bb->last_ins;
14279                                         live_range_end_bb [vi->vreg] = bb;
14280                                 }
14281                         }
14282                 }
14283         }
14284         
14285         /*
14286          * Emit LIVERANGE_START/LIVERANGE_END opcodes, the backend will implement them
14287          * by storing the current native offset into MonoMethodVar->live_range_start/end.
14288          */
14289         if (cfg->backend->have_liverange_ops && cfg->compute_precise_live_ranges && cfg->comp_done & MONO_COMP_LIVENESS) {
14290                 for (i = 0; i < cfg->num_varinfo; ++i) {
14291                         int vreg = MONO_VARINFO (cfg, i)->vreg;
14292                         MonoInst *ins;
14293
14294                         if (live_range_start [vreg]) {
14295                                 MONO_INST_NEW (cfg, ins, OP_LIVERANGE_START);
14296                                 ins->inst_c0 = i;
14297                                 ins->inst_c1 = vreg;
14298                                 mono_bblock_insert_after_ins (live_range_start_bb [vreg], live_range_start [vreg], ins);
14299                         }
14300                         if (live_range_end [vreg]) {
14301                                 MONO_INST_NEW (cfg, ins, OP_LIVERANGE_END);
14302                                 ins->inst_c0 = i;
14303                                 ins->inst_c1 = vreg;
14304                                 if (live_range_end [vreg] == live_range_end_bb [vreg]->last_ins)
14305                                         mono_add_ins_to_end (live_range_end_bb [vreg], ins);
14306                                 else
14307                                         mono_bblock_insert_after_ins (live_range_end_bb [vreg], live_range_end [vreg], ins);
14308                         }
14309                 }
14310         }
14311
14312         if (cfg->gsharedvt_locals_var_ins) {
14313                 /* Nullify if unused */
14314                 cfg->gsharedvt_locals_var_ins->opcode = OP_PCONST;
14315                 cfg->gsharedvt_locals_var_ins->inst_imm = 0;
14316         }
14317
14318         g_free (live_range_start);
14319         g_free (live_range_end);
14320         g_free (live_range_start_bb);
14321         g_free (live_range_end_bb);
14322 }
14323
14324
14325 /**
14326  * FIXME:
14327  * - use 'iadd' instead of 'int_add'
14328  * - handling ovf opcodes: decompose in method_to_ir.
14329  * - unify iregs/fregs
14330  *   -> partly done, the missing parts are:
14331  *   - a more complete unification would involve unifying the hregs as well, so
14332  *     code wouldn't need if (fp) all over the place. but that would mean the hregs
14333  *     would no longer map to the machine hregs, so the code generators would need to
14334  *     be modified. Also, on ia64 for example, niregs + nfregs > 256 -> bitmasks
14335  *     wouldn't work any more. Duplicating the code in mono_local_regalloc () into
14336  *     fp/non-fp branches speeds it up by about 15%.
14337  * - use sext/zext opcodes instead of shifts
14338  * - add OP_ICALL
14339  * - get rid of TEMPLOADs if possible and use vregs instead
14340  * - clean up usage of OP_P/OP_ opcodes
14341  * - cleanup usage of DUMMY_USE
14342  * - cleanup the setting of ins->type for MonoInst's which are pushed on the 
14343  *   stack
14344  * - set the stack type and allocate a dreg in the EMIT_NEW macros
14345  * - get rid of all the <foo>2 stuff when the new JIT is ready.
14346  * - make sure handle_stack_args () is called before the branch is emitted
14347  * - when the new IR is done, get rid of all unused stuff
14348  * - COMPARE/BEQ as separate instructions or unify them ?
14349  *   - keeping them separate allows specialized compare instructions like
14350  *     compare_imm, compare_membase
14351  *   - most back ends unify fp compare+branch, fp compare+ceq
14352  * - integrate mono_save_args into inline_method
14353  * - get rid of the empty bblocks created by MONO_EMIT_NEW_BRACH_BLOCK2
14354  * - handle long shift opts on 32 bit platforms somehow: they require 
14355  *   3 sregs (2 for arg1 and 1 for arg2)
14356  * - make byref a 'normal' type.
14357  * - use vregs for bb->out_stacks if possible, handle_global_vreg will make them a
14358  *   variable if needed.
14359  * - do not start a new IL level bblock when cfg->cbb is changed by a function call
14360  *   like inline_method.
14361  * - remove inlining restrictions
14362  * - fix LNEG and enable cfold of INEG
14363  * - generalize x86 optimizations like ldelema as a peephole optimization
14364  * - add store_mem_imm for amd64
14365  * - optimize the loading of the interruption flag in the managed->native wrappers
14366  * - avoid special handling of OP_NOP in passes
14367  * - move code inserting instructions into one function/macro.
14368  * - try a coalescing phase after liveness analysis
14369  * - add float -> vreg conversion + local optimizations on !x86
14370  * - figure out how to handle decomposed branches during optimizations, ie.
14371  *   compare+branch, op_jump_table+op_br etc.
14372  * - promote RuntimeXHandles to vregs
14373  * - vtype cleanups:
14374  *   - add a NEW_VARLOADA_VREG macro
14375  * - the vtype optimizations are blocked by the LDADDR opcodes generated for 
14376  *   accessing vtype fields.
14377  * - get rid of I8CONST on 64 bit platforms
14378  * - dealing with the increase in code size due to branches created during opcode
14379  *   decomposition:
14380  *   - use extended basic blocks
14381  *     - all parts of the JIT
14382  *     - handle_global_vregs () && local regalloc
14383  *   - avoid introducing global vregs during decomposition, like 'vtable' in isinst
14384  * - sources of increase in code size:
14385  *   - vtypes
14386  *   - long compares
14387  *   - isinst and castclass
14388  *   - lvregs not allocated to global registers even if used multiple times
14389  * - call cctors outside the JIT, to make -v output more readable and JIT timings more
14390  *   meaningful.
14391  * - check for fp stack leakage in other opcodes too. (-> 'exceptions' optimization)
14392  * - add all micro optimizations from the old JIT
14393  * - put tree optimizations into the deadce pass
14394  * - decompose op_start_handler/op_endfilter/op_endfinally earlier using an arch
14395  *   specific function.
14396  * - unify the float comparison opcodes with the other comparison opcodes, i.e.
14397  *   fcompare + branchCC.
14398  * - create a helper function for allocating a stack slot, taking into account 
14399  *   MONO_CFG_HAS_SPILLUP.
14400  * - merge r68207.
14401  * - optimize mono_regstate2_alloc_int/float.
14402  * - fix the pessimistic handling of variables accessed in exception handler blocks.
14403  * - need to write a tree optimization pass, but the creation of trees is difficult, i.e.
14404  *   parts of the tree could be separated by other instructions, killing the tree
14405  *   arguments, or stores killing loads etc. Also, should we fold loads into other
14406  *   instructions if the result of the load is used multiple times ?
14407  * - make the REM_IMM optimization in mini-x86.c arch-independent.
14408  * - LAST MERGE: 108395.
14409  * - when returning vtypes in registers, generate IR and append it to the end of the
14410  *   last bb instead of doing it in the epilog.
14411  * - change the store opcodes so they use sreg1 instead of dreg to store the base register.
14412  */
14413
14414 /*
14415
14416 NOTES
14417 -----
14418
14419 - When to decompose opcodes:
14420   - earlier: this makes some optimizations hard to implement, since the low level IR
14421   no longer contains the neccessary information. But it is easier to do.
14422   - later: harder to implement, enables more optimizations.
14423 - Branches inside bblocks:
14424   - created when decomposing complex opcodes. 
14425     - branches to another bblock: harmless, but not tracked by the branch 
14426       optimizations, so need to branch to a label at the start of the bblock.
14427     - branches to inside the same bblock: very problematic, trips up the local
14428       reg allocator. Can be fixed by spitting the current bblock, but that is a
14429       complex operation, since some local vregs can become global vregs etc.
14430 - Local/global vregs:
14431   - local vregs: temporary vregs used inside one bblock. Assigned to hregs by the
14432     local register allocator.
14433   - global vregs: used in more than one bblock. Have an associated MonoMethodVar
14434     structure, created by mono_create_var (). Assigned to hregs or the stack by
14435     the global register allocator.
14436 - When to do optimizations like alu->alu_imm:
14437   - earlier -> saves work later on since the IR will be smaller/simpler
14438   - later -> can work on more instructions
14439 - Handling of valuetypes:
14440   - When a vtype is pushed on the stack, a new temporary is created, an 
14441     instruction computing its address (LDADDR) is emitted and pushed on
14442     the stack. Need to optimize cases when the vtype is used immediately as in
14443     argument passing, stloc etc.
14444 - Instead of the to_end stuff in the old JIT, simply call the function handling
14445   the values on the stack before emitting the last instruction of the bb.
14446 */
14447
14448 #else /* !DISABLE_JIT */
14449
14450 void
14451 mono_set_break_policy (MonoBreakPolicyFunc policy_callback)
14452 {
14453 }
14454
14455 #endif /* !DISABLE_JIT */