Merge pull request #5439 from alexrp/master
[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 || cfg->llvm_only)
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 int
1768 ret_type_to_call_opcode (MonoCompile *cfg, MonoType *type, int calli, int virt)
1769 {
1770 handle_enum:
1771         type = mini_get_underlying_type (type);
1772         switch (type->type) {
1773         case MONO_TYPE_VOID:
1774                 return calli? OP_VOIDCALL_REG: virt? OP_VOIDCALL_MEMBASE: OP_VOIDCALL;
1775         case MONO_TYPE_I1:
1776         case MONO_TYPE_U1:
1777         case MONO_TYPE_I2:
1778         case MONO_TYPE_U2:
1779         case MONO_TYPE_I4:
1780         case MONO_TYPE_U4:
1781                 return calli? OP_CALL_REG: virt? OP_CALL_MEMBASE: OP_CALL;
1782         case MONO_TYPE_I:
1783         case MONO_TYPE_U:
1784         case MONO_TYPE_PTR:
1785         case MONO_TYPE_FNPTR:
1786                 return calli? OP_CALL_REG: virt? OP_CALL_MEMBASE: OP_CALL;
1787         case MONO_TYPE_CLASS:
1788         case MONO_TYPE_STRING:
1789         case MONO_TYPE_OBJECT:
1790         case MONO_TYPE_SZARRAY:
1791         case MONO_TYPE_ARRAY:    
1792                 return calli? OP_CALL_REG: virt? OP_CALL_MEMBASE: OP_CALL;
1793         case MONO_TYPE_I8:
1794         case MONO_TYPE_U8:
1795                 return calli? OP_LCALL_REG: virt? OP_LCALL_MEMBASE: OP_LCALL;
1796         case MONO_TYPE_R4:
1797                 if (cfg->r4fp)
1798                         return calli? OP_RCALL_REG: virt? OP_RCALL_MEMBASE: OP_RCALL;
1799                 else
1800                         return calli? OP_FCALL_REG: virt? OP_FCALL_MEMBASE: OP_FCALL;
1801         case MONO_TYPE_R8:
1802                 return calli? OP_FCALL_REG: virt? OP_FCALL_MEMBASE: OP_FCALL;
1803         case MONO_TYPE_VALUETYPE:
1804                 if (type->data.klass->enumtype) {
1805                         type = mono_class_enum_basetype (type->data.klass);
1806                         goto handle_enum;
1807                 } else
1808                         return calli? OP_VCALL_REG: virt? OP_VCALL_MEMBASE: OP_VCALL;
1809         case MONO_TYPE_TYPEDBYREF:
1810                 return calli? OP_VCALL_REG: virt? OP_VCALL_MEMBASE: OP_VCALL;
1811         case MONO_TYPE_GENERICINST:
1812                 type = &type->data.generic_class->container_class->byval_arg;
1813                 goto handle_enum;
1814         case MONO_TYPE_VAR:
1815         case MONO_TYPE_MVAR:
1816                 /* gsharedvt */
1817                 return calli? OP_VCALL_REG: virt? OP_VCALL_MEMBASE: OP_VCALL;
1818         default:
1819                 g_error ("unknown type 0x%02x in ret_type_to_call_opcode", type->type);
1820         }
1821         return -1;
1822 }
1823
1824 //XXX this ignores if t is byref
1825 #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)))))
1826
1827 /*
1828  * target_type_is_incompatible:
1829  * @cfg: MonoCompile context
1830  *
1831  * Check that the item @arg on the evaluation stack can be stored
1832  * in the target type (can be a local, or field, etc).
1833  * The cfg arg can be used to check if we need verification or just
1834  * validity checks.
1835  *
1836  * Returns: non-0 value if arg can't be stored on a target.
1837  */
1838 static int
1839 target_type_is_incompatible (MonoCompile *cfg, MonoType *target, MonoInst *arg)
1840 {
1841         MonoType *simple_type;
1842         MonoClass *klass;
1843
1844         if (target->byref) {
1845                 /* FIXME: check that the pointed to types match */
1846                 if (arg->type == STACK_MP) {
1847                         /* This is needed to handle gshared types + ldaddr. We lower the types so we can handle enums and other typedef-like types. */
1848                         MonoClass *target_class_lowered = mono_class_from_mono_type (mini_get_underlying_type (&mono_class_from_mono_type (target)->byval_arg));
1849                         MonoClass *source_class_lowered = mono_class_from_mono_type (mini_get_underlying_type (&arg->klass->byval_arg));
1850
1851                         /* if the target is native int& or same type */
1852                         if (target->type == MONO_TYPE_I || target_class_lowered == source_class_lowered)
1853                                 return 0;
1854
1855                         /* Both are primitive type byrefs and the source points to a larger type that the destination */
1856                         if (MONO_TYPE_IS_PRIMITIVE_SCALAR (&target_class_lowered->byval_arg) && MONO_TYPE_IS_PRIMITIVE_SCALAR (&source_class_lowered->byval_arg) &&
1857                                 mono_class_instance_size (target_class_lowered) <= mono_class_instance_size (source_class_lowered))
1858                                 return 0;
1859                         return 1;
1860                 }
1861                 if (arg->type == STACK_PTR)
1862                         return 0;
1863                 return 1;
1864         }
1865
1866         simple_type = mini_get_underlying_type (target);
1867         switch (simple_type->type) {
1868         case MONO_TYPE_VOID:
1869                 return 1;
1870         case MONO_TYPE_I1:
1871         case MONO_TYPE_U1:
1872         case MONO_TYPE_I2:
1873         case MONO_TYPE_U2:
1874         case MONO_TYPE_I4:
1875         case MONO_TYPE_U4:
1876                 if (arg->type != STACK_I4 && arg->type != STACK_PTR)
1877                         return 1;
1878                 return 0;
1879         case MONO_TYPE_PTR:
1880                 /* STACK_MP is needed when setting pinned locals */
1881                 if (arg->type != STACK_I4 && arg->type != STACK_PTR && arg->type != STACK_MP)
1882                         return 1;
1883                 return 0;
1884         case MONO_TYPE_I:
1885         case MONO_TYPE_U:
1886         case MONO_TYPE_FNPTR:
1887                 /* 
1888                  * Some opcodes like ldloca returns 'transient pointers' which can be stored in
1889                  * in native int. (#688008).
1890                  */
1891                 if (arg->type != STACK_I4 && arg->type != STACK_PTR && arg->type != STACK_MP)
1892                         return 1;
1893                 return 0;
1894         case MONO_TYPE_CLASS:
1895         case MONO_TYPE_STRING:
1896         case MONO_TYPE_OBJECT:
1897         case MONO_TYPE_SZARRAY:
1898         case MONO_TYPE_ARRAY:    
1899                 if (arg->type != STACK_OBJ)
1900                         return 1;
1901                 /* FIXME: check type compatibility */
1902                 return 0;
1903         case MONO_TYPE_I8:
1904         case MONO_TYPE_U8:
1905                 if (arg->type != STACK_I8)
1906                         return 1;
1907                 return 0;
1908         case MONO_TYPE_R4:
1909                 if (arg->type != cfg->r4_stack_type)
1910                         return 1;
1911                 return 0;
1912         case MONO_TYPE_R8:
1913                 if (arg->type != STACK_R8)
1914                         return 1;
1915                 return 0;
1916         case MONO_TYPE_VALUETYPE:
1917                 if (arg->type != STACK_VTYPE)
1918                         return 1;
1919                 klass = mono_class_from_mono_type (simple_type);
1920                 if (klass != arg->klass)
1921                         return 1;
1922                 return 0;
1923         case MONO_TYPE_TYPEDBYREF:
1924                 if (arg->type != STACK_VTYPE)
1925                         return 1;
1926                 klass = mono_class_from_mono_type (simple_type);
1927                 if (klass != arg->klass)
1928                         return 1;
1929                 return 0;
1930         case MONO_TYPE_GENERICINST:
1931                 if (mono_type_generic_inst_is_valuetype (simple_type)) {
1932                         MonoClass *target_class;
1933                         if (arg->type != STACK_VTYPE)
1934                                 return 1;
1935                         klass = mono_class_from_mono_type (simple_type);
1936                         target_class = mono_class_from_mono_type (target);
1937                         /* The second cases is needed when doing partial sharing */
1938                         if (klass != arg->klass && target_class != arg->klass && target_class != mono_class_from_mono_type (mini_get_underlying_type (&arg->klass->byval_arg)))
1939                                 return 1;
1940                         return 0;
1941                 } else {
1942                         if (arg->type != STACK_OBJ)
1943                                 return 1;
1944                         /* FIXME: check type compatibility */
1945                         return 0;
1946                 }
1947         case MONO_TYPE_VAR:
1948         case MONO_TYPE_MVAR:
1949                 g_assert (cfg->gshared);
1950                 if (mini_type_var_is_vt (simple_type)) {
1951                         if (arg->type != STACK_VTYPE)
1952                                 return 1;
1953                 } else {
1954                         if (arg->type != STACK_OBJ)
1955                                 return 1;
1956                 }
1957                 return 0;
1958         default:
1959                 g_error ("unknown type 0x%02x in target_type_is_incompatible", simple_type->type);
1960         }
1961         return 1;
1962 }
1963
1964 /*
1965  * Prepare arguments for passing to a function call.
1966  * Return a non-zero value if the arguments can't be passed to the given
1967  * signature.
1968  * The type checks are not yet complete and some conversions may need
1969  * casts on 32 or 64 bit architectures.
1970  *
1971  * FIXME: implement this using target_type_is_incompatible ()
1972  */
1973 static int
1974 check_call_signature (MonoCompile *cfg, MonoMethodSignature *sig, MonoInst **args)
1975 {
1976         MonoType *simple_type;
1977         int i;
1978
1979         if (sig->hasthis) {
1980                 if (args [0]->type != STACK_OBJ && args [0]->type != STACK_MP && args [0]->type != STACK_PTR)
1981                         return 1;
1982                 args++;
1983         }
1984         for (i = 0; i < sig->param_count; ++i) {
1985                 if (sig->params [i]->byref) {
1986                         if (args [i]->type != STACK_MP && args [i]->type != STACK_PTR)
1987                                 return 1;
1988                         continue;
1989                 }
1990                 simple_type = mini_get_underlying_type (sig->params [i]);
1991 handle_enum:
1992                 switch (simple_type->type) {
1993                 case MONO_TYPE_VOID:
1994                         return 1;
1995                         continue;
1996                 case MONO_TYPE_I1:
1997                 case MONO_TYPE_U1:
1998                 case MONO_TYPE_I2:
1999                 case MONO_TYPE_U2:
2000                 case MONO_TYPE_I4:
2001                 case MONO_TYPE_U4:
2002                         if (args [i]->type != STACK_I4 && args [i]->type != STACK_PTR)
2003                                 return 1;
2004                         continue;
2005                 case MONO_TYPE_I:
2006                 case MONO_TYPE_U:
2007                 case MONO_TYPE_PTR:
2008                 case MONO_TYPE_FNPTR:
2009                         if (args [i]->type != STACK_I4 && args [i]->type != STACK_PTR && args [i]->type != STACK_MP && args [i]->type != STACK_OBJ)
2010                                 return 1;
2011                         continue;
2012                 case MONO_TYPE_CLASS:
2013                 case MONO_TYPE_STRING:
2014                 case MONO_TYPE_OBJECT:
2015                 case MONO_TYPE_SZARRAY:
2016                 case MONO_TYPE_ARRAY:    
2017                         if (args [i]->type != STACK_OBJ)
2018                                 return 1;
2019                         continue;
2020                 case MONO_TYPE_I8:
2021                 case MONO_TYPE_U8:
2022                         if (args [i]->type != STACK_I8)
2023                                 return 1;
2024                         continue;
2025                 case MONO_TYPE_R4:
2026                         if (args [i]->type != cfg->r4_stack_type)
2027                                 return 1;
2028                         continue;
2029                 case MONO_TYPE_R8:
2030                         if (args [i]->type != STACK_R8)
2031                                 return 1;
2032                         continue;
2033                 case MONO_TYPE_VALUETYPE:
2034                         if (simple_type->data.klass->enumtype) {
2035                                 simple_type = mono_class_enum_basetype (simple_type->data.klass);
2036                                 goto handle_enum;
2037                         }
2038                         if (args [i]->type != STACK_VTYPE)
2039                                 return 1;
2040                         continue;
2041                 case MONO_TYPE_TYPEDBYREF:
2042                         if (args [i]->type != STACK_VTYPE)
2043                                 return 1;
2044                         continue;
2045                 case MONO_TYPE_GENERICINST:
2046                         simple_type = &simple_type->data.generic_class->container_class->byval_arg;
2047                         goto handle_enum;
2048                 case MONO_TYPE_VAR:
2049                 case MONO_TYPE_MVAR:
2050                         /* gsharedvt */
2051                         if (args [i]->type != STACK_VTYPE)
2052                                 return 1;
2053                         continue;
2054                 default:
2055                         g_error ("unknown type 0x%02x in check_call_signature",
2056                                  simple_type->type);
2057                 }
2058         }
2059         return 0;
2060 }
2061
2062 static int
2063 callvirt_to_call (int opcode)
2064 {
2065         switch (opcode) {
2066         case OP_CALL_MEMBASE:
2067                 return OP_CALL;
2068         case OP_VOIDCALL_MEMBASE:
2069                 return OP_VOIDCALL;
2070         case OP_FCALL_MEMBASE:
2071                 return OP_FCALL;
2072         case OP_RCALL_MEMBASE:
2073                 return OP_RCALL;
2074         case OP_VCALL_MEMBASE:
2075                 return OP_VCALL;
2076         case OP_LCALL_MEMBASE:
2077                 return OP_LCALL;
2078         default:
2079                 g_assert_not_reached ();
2080         }
2081
2082         return -1;
2083 }
2084
2085 static int
2086 callvirt_to_call_reg (int opcode)
2087 {
2088         switch (opcode) {
2089         case OP_CALL_MEMBASE:
2090                 return OP_CALL_REG;
2091         case OP_VOIDCALL_MEMBASE:
2092                 return OP_VOIDCALL_REG;
2093         case OP_FCALL_MEMBASE:
2094                 return OP_FCALL_REG;
2095         case OP_RCALL_MEMBASE:
2096                 return OP_RCALL_REG;
2097         case OP_VCALL_MEMBASE:
2098                 return OP_VCALL_REG;
2099         case OP_LCALL_MEMBASE:
2100                 return OP_LCALL_REG;
2101         default:
2102                 g_assert_not_reached ();
2103         }
2104
2105         return -1;
2106 }
2107
2108 /* Either METHOD or IMT_ARG needs to be set */
2109 static void
2110 emit_imt_argument (MonoCompile *cfg, MonoCallInst *call, MonoMethod *method, MonoInst *imt_arg)
2111 {
2112         int method_reg;
2113
2114         if (COMPILE_LLVM (cfg)) {
2115                 if (imt_arg) {
2116                         method_reg = alloc_preg (cfg);
2117                         MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, method_reg, imt_arg->dreg);
2118                 } else {
2119                         MonoInst *ins = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_METHODCONST, method);
2120                         method_reg = ins->dreg;
2121                 }
2122
2123 #ifdef ENABLE_LLVM
2124                 call->imt_arg_reg = method_reg;
2125 #endif
2126                 mono_call_inst_add_outarg_reg (cfg, call, method_reg, MONO_ARCH_IMT_REG, FALSE);
2127                 return;
2128         }
2129
2130         if (imt_arg) {
2131                 method_reg = alloc_preg (cfg);
2132                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, method_reg, imt_arg->dreg);
2133         } else {
2134                 MonoInst *ins = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_METHODCONST, method);
2135                 method_reg = ins->dreg;
2136         }
2137
2138         mono_call_inst_add_outarg_reg (cfg, call, method_reg, MONO_ARCH_IMT_REG, FALSE);
2139 }
2140
2141 static MonoJumpInfo *
2142 mono_patch_info_new (MonoMemPool *mp, int ip, MonoJumpInfoType type, gconstpointer target)
2143 {
2144         MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc (mp, sizeof (MonoJumpInfo));
2145
2146         ji->ip.i = ip;
2147         ji->type = type;
2148         ji->data.target = target;
2149
2150         return ji;
2151 }
2152
2153 int
2154 mini_class_check_context_used (MonoCompile *cfg, MonoClass *klass)
2155 {
2156         if (cfg->gshared)
2157                 return mono_class_check_context_used (klass);
2158         else
2159                 return 0;
2160 }
2161
2162 static int
2163 mini_method_check_context_used (MonoCompile *cfg, MonoMethod *method)
2164 {
2165         if (cfg->gshared)
2166                 return mono_method_check_context_used (method);
2167         else
2168                 return 0;
2169 }
2170
2171 /*
2172  * check_method_sharing:
2173  *
2174  *   Check whenever the vtable or an mrgctx needs to be passed when calling CMETHOD.
2175  */
2176 static void
2177 check_method_sharing (MonoCompile *cfg, MonoMethod *cmethod, gboolean *out_pass_vtable, gboolean *out_pass_mrgctx)
2178 {
2179         gboolean pass_vtable = FALSE;
2180         gboolean pass_mrgctx = FALSE;
2181
2182         if (((cmethod->flags & METHOD_ATTRIBUTE_STATIC) || cmethod->klass->valuetype) &&
2183                 (mono_class_is_ginst (cmethod->klass) || mono_class_is_gtd (cmethod->klass))) {
2184                 gboolean sharable = FALSE;
2185
2186                 if (mono_method_is_generic_sharable_full (cmethod, TRUE, TRUE, TRUE))
2187                         sharable = TRUE;
2188
2189                 /*
2190                  * Pass vtable iff target method might
2191                  * be shared, which means that sharing
2192                  * is enabled for its class and its
2193                  * context is sharable (and it's not a
2194                  * generic method).
2195                  */
2196                 if (sharable && !(mini_method_get_context (cmethod) && mini_method_get_context (cmethod)->method_inst))
2197                         pass_vtable = TRUE;
2198         }
2199
2200         if (mini_method_get_context (cmethod) &&
2201                 mini_method_get_context (cmethod)->method_inst) {
2202                 g_assert (!pass_vtable);
2203
2204                 if (mono_method_is_generic_sharable_full (cmethod, TRUE, TRUE, TRUE)) {
2205                         pass_mrgctx = TRUE;
2206                 } else {
2207                         if (cfg->gsharedvt && mini_is_gsharedvt_signature (mono_method_signature (cmethod)))
2208                                 pass_mrgctx = TRUE;
2209                 }
2210         }
2211
2212         if (out_pass_vtable)
2213                 *out_pass_vtable = pass_vtable;
2214         if (out_pass_mrgctx)
2215                 *out_pass_mrgctx = pass_mrgctx;
2216 }
2217
2218 inline static MonoCallInst *
2219 mono_emit_call_args (MonoCompile *cfg, MonoMethodSignature *sig, 
2220                                          MonoInst **args, int calli, int virtual_, int tail, int rgctx, int unbox_trampoline, MonoMethod *target)
2221 {
2222         MonoType *sig_ret;
2223         MonoCallInst *call;
2224 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
2225         int i;
2226 #endif
2227
2228         if (cfg->llvm_only)
2229                 tail = FALSE;
2230
2231         if (tail) {
2232                 mini_profiler_emit_tail_call (cfg, target);
2233
2234                 MONO_INST_NEW_CALL (cfg, call, OP_TAILCALL);
2235         } else
2236                 MONO_INST_NEW_CALL (cfg, call, ret_type_to_call_opcode (cfg, sig->ret, calli, virtual_));
2237
2238         call->args = args;
2239         call->signature = sig;
2240         call->rgctx_reg = rgctx;
2241         sig_ret = mini_get_underlying_type (sig->ret);
2242
2243         type_to_eval_stack_type ((cfg), sig_ret, &call->inst);
2244
2245         if (tail) {
2246                 if (mini_type_is_vtype (sig_ret)) {
2247                         call->vret_var = cfg->vret_addr;
2248                         //g_assert_not_reached ();
2249                 }
2250         } else if (mini_type_is_vtype (sig_ret)) {
2251                 MonoInst *temp = mono_compile_create_var (cfg, sig_ret, OP_LOCAL);
2252                 MonoInst *loada;
2253
2254                 temp->backend.is_pinvoke = sig->pinvoke;
2255
2256                 /*
2257                  * We use a new opcode OP_OUTARG_VTRETADDR instead of LDADDR for emitting the
2258                  * address of return value to increase optimization opportunities.
2259                  * Before vtype decomposition, the dreg of the call ins itself represents the
2260                  * fact the call modifies the return value. After decomposition, the call will
2261                  * be transformed into one of the OP_VOIDCALL opcodes, and the VTRETADDR opcode
2262                  * will be transformed into an LDADDR.
2263                  */
2264                 MONO_INST_NEW (cfg, loada, OP_OUTARG_VTRETADDR);
2265                 loada->dreg = alloc_preg (cfg);
2266                 loada->inst_p0 = temp;
2267                 /* We reference the call too since call->dreg could change during optimization */
2268                 loada->inst_p1 = call;
2269                 MONO_ADD_INS (cfg->cbb, loada);
2270
2271                 call->inst.dreg = temp->dreg;
2272
2273                 call->vret_var = loada;
2274         } else if (!MONO_TYPE_IS_VOID (sig_ret))
2275                 call->inst.dreg = alloc_dreg (cfg, (MonoStackType)call->inst.type);
2276
2277 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
2278         if (COMPILE_SOFT_FLOAT (cfg)) {
2279                 /* 
2280                  * If the call has a float argument, we would need to do an r8->r4 conversion using 
2281                  * an icall, but that cannot be done during the call sequence since it would clobber
2282                  * the call registers + the stack. So we do it before emitting the call.
2283                  */
2284                 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
2285                         MonoType *t;
2286                         MonoInst *in = call->args [i];
2287
2288                         if (i >= sig->hasthis)
2289                                 t = sig->params [i - sig->hasthis];
2290                         else
2291                                 t = &mono_defaults.int_class->byval_arg;
2292                         t = mono_type_get_underlying_type (t);
2293
2294                         if (!t->byref && t->type == MONO_TYPE_R4) {
2295                                 MonoInst *iargs [1];
2296                                 MonoInst *conv;
2297
2298                                 iargs [0] = in;
2299                                 conv = mono_emit_jit_icall (cfg, mono_fload_r4_arg, iargs);
2300
2301                                 /* The result will be in an int vreg */
2302                                 call->args [i] = conv;
2303                         }
2304                 }
2305         }
2306 #endif
2307
2308         call->need_unbox_trampoline = unbox_trampoline;
2309
2310 #ifdef ENABLE_LLVM
2311         if (COMPILE_LLVM (cfg))
2312                 mono_llvm_emit_call (cfg, call);
2313         else
2314                 mono_arch_emit_call (cfg, call);
2315 #else
2316         mono_arch_emit_call (cfg, call);
2317 #endif
2318
2319         cfg->param_area = MAX (cfg->param_area, call->stack_usage);
2320         cfg->flags |= MONO_CFG_HAS_CALLS;
2321         
2322         return call;
2323 }
2324
2325 static void
2326 set_rgctx_arg (MonoCompile *cfg, MonoCallInst *call, int rgctx_reg, MonoInst *rgctx_arg)
2327 {
2328         mono_call_inst_add_outarg_reg (cfg, call, rgctx_reg, MONO_ARCH_RGCTX_REG, FALSE);
2329         cfg->uses_rgctx_reg = TRUE;
2330         call->rgctx_reg = TRUE;
2331 #ifdef ENABLE_LLVM
2332         call->rgctx_arg_reg = rgctx_reg;
2333 #endif
2334 }       
2335
2336 MonoInst*
2337 mini_emit_calli (MonoCompile *cfg, MonoMethodSignature *sig, MonoInst **args, MonoInst *addr, MonoInst *imt_arg, MonoInst *rgctx_arg)
2338 {
2339         MonoCallInst *call;
2340         MonoInst *ins;
2341         int rgctx_reg = -1;
2342         gboolean check_sp = FALSE;
2343
2344         if (cfg->check_pinvoke_callconv && cfg->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
2345                 WrapperInfo *info = mono_marshal_get_wrapper_info (cfg->method);
2346
2347                 if (info && info->subtype == WRAPPER_SUBTYPE_PINVOKE)
2348                         check_sp = TRUE;
2349         }
2350
2351         if (rgctx_arg) {
2352                 rgctx_reg = mono_alloc_preg (cfg);
2353                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, rgctx_reg, rgctx_arg->dreg);
2354         }
2355
2356         if (check_sp) {
2357                 if (!cfg->stack_inbalance_var)
2358                         cfg->stack_inbalance_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
2359
2360                 MONO_INST_NEW (cfg, ins, OP_GET_SP);
2361                 ins->dreg = cfg->stack_inbalance_var->dreg;
2362                 MONO_ADD_INS (cfg->cbb, ins);
2363         }
2364
2365         call = mono_emit_call_args (cfg, sig, args, TRUE, FALSE, FALSE, rgctx_arg ? TRUE : FALSE, FALSE, NULL);
2366
2367         call->inst.sreg1 = addr->dreg;
2368
2369         if (imt_arg)
2370                 emit_imt_argument (cfg, call, NULL, imt_arg);
2371
2372         MONO_ADD_INS (cfg->cbb, (MonoInst*)call);
2373
2374         if (check_sp) {
2375                 int sp_reg;
2376
2377                 sp_reg = mono_alloc_preg (cfg);
2378
2379                 MONO_INST_NEW (cfg, ins, OP_GET_SP);
2380                 ins->dreg = sp_reg;
2381                 MONO_ADD_INS (cfg->cbb, ins);
2382
2383                 /* Restore the stack so we don't crash when throwing the exception */
2384                 MONO_INST_NEW (cfg, ins, OP_SET_SP);
2385                 ins->sreg1 = cfg->stack_inbalance_var->dreg;
2386                 MONO_ADD_INS (cfg->cbb, ins);
2387
2388                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, cfg->stack_inbalance_var->dreg, sp_reg);
2389                 MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "ExecutionEngineException");
2390         }
2391
2392         if (rgctx_arg)
2393                 set_rgctx_arg (cfg, call, rgctx_reg, rgctx_arg);
2394
2395         return (MonoInst*)call;
2396 }
2397
2398 static MonoInst*
2399 emit_get_rgctx_method (MonoCompile *cfg, int context_used, MonoMethod *cmethod, MonoRgctxInfoType rgctx_type);
2400
2401 static MonoInst*
2402 mono_emit_method_call_full (MonoCompile *cfg, MonoMethod *method, MonoMethodSignature *sig, gboolean tail,
2403                                                         MonoInst **args, MonoInst *this_ins, MonoInst *imt_arg, MonoInst *rgctx_arg)
2404 {
2405 #ifndef DISABLE_REMOTING
2406         gboolean might_be_remote = FALSE;
2407 #endif
2408         gboolean virtual_ = this_ins != NULL;
2409         gboolean enable_for_aot = TRUE;
2410         int context_used;
2411         MonoCallInst *call;
2412         MonoInst *call_target = NULL;
2413         int rgctx_reg = 0;
2414         gboolean need_unbox_trampoline;
2415
2416         if (!sig)
2417                 sig = mono_method_signature (method);
2418
2419         if (cfg->llvm_only && (mono_class_is_interface (method->klass)))
2420                 g_assert_not_reached ();
2421
2422         if (rgctx_arg) {
2423                 rgctx_reg = mono_alloc_preg (cfg);
2424                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, rgctx_reg, rgctx_arg->dreg);
2425         }
2426
2427         if (method->string_ctor) {
2428                 /* Create the real signature */
2429                 /* FIXME: Cache these */
2430                 MonoMethodSignature *ctor_sig = mono_metadata_signature_dup_mempool (cfg->mempool, sig);
2431                 ctor_sig->ret = &mono_defaults.string_class->byval_arg;
2432
2433                 sig = ctor_sig;
2434         }
2435
2436         context_used = mini_method_check_context_used (cfg, method);
2437
2438 #ifndef DISABLE_REMOTING
2439         might_be_remote = this_ins && sig->hasthis &&
2440                 (mono_class_is_marshalbyref (method->klass) || method->klass == mono_defaults.object_class) &&
2441                 !(method->flags & METHOD_ATTRIBUTE_VIRTUAL) && (!MONO_CHECK_THIS (this_ins) || context_used);
2442
2443         if (might_be_remote && context_used) {
2444                 MonoInst *addr;
2445
2446                 g_assert (cfg->gshared);
2447
2448                 addr = emit_get_rgctx_method (cfg, context_used, method, MONO_RGCTX_INFO_REMOTING_INVOKE_WITH_CHECK);
2449
2450                 return mini_emit_calli (cfg, sig, args, addr, NULL, NULL);
2451         }
2452 #endif
2453
2454         if (cfg->llvm_only && !call_target && virtual_ && (method->flags & METHOD_ATTRIBUTE_VIRTUAL))
2455                 return emit_llvmonly_virtual_call (cfg, method, sig, 0, args);
2456
2457         need_unbox_trampoline = method->klass == mono_defaults.object_class || mono_class_is_interface (method->klass);
2458
2459         call = mono_emit_call_args (cfg, sig, args, FALSE, virtual_, tail, rgctx_arg ? TRUE : FALSE, need_unbox_trampoline, method);
2460
2461 #ifndef DISABLE_REMOTING
2462         if (might_be_remote)
2463                 call->method = mono_marshal_get_remoting_invoke_with_check (method);
2464         else
2465 #endif
2466                 call->method = method;
2467         call->inst.flags |= MONO_INST_HAS_METHOD;
2468         call->inst.inst_left = this_ins;
2469         call->tail_call = tail;
2470
2471         if (virtual_) {
2472                 int vtable_reg, slot_reg, this_reg;
2473                 int offset;
2474
2475                 this_reg = this_ins->dreg;
2476
2477                 if (!cfg->llvm_only && (method->klass->parent == mono_defaults.multicastdelegate_class) && !strcmp (method->name, "Invoke")) {
2478                         MonoInst *dummy_use;
2479
2480                         MONO_EMIT_NULL_CHECK (cfg, this_reg);
2481
2482                         /* Make a call to delegate->invoke_impl */
2483                         call->inst.inst_basereg = this_reg;
2484                         call->inst.inst_offset = MONO_STRUCT_OFFSET (MonoDelegate, invoke_impl);
2485                         MONO_ADD_INS (cfg->cbb, (MonoInst*)call);
2486
2487                         /* We must emit a dummy use here because the delegate trampoline will
2488                         replace the 'this' argument with the delegate target making this activation
2489                         no longer a root for the delegate.
2490                         This is an issue for delegates that target collectible code such as dynamic
2491                         methods of GC'able assemblies.
2492
2493                         For a test case look into #667921.
2494
2495                         FIXME: a dummy use is not the best way to do it as the local register allocator
2496                         will put it on a caller save register and spil it around the call. 
2497                         Ideally, we would either put it on a callee save register or only do the store part.  
2498                          */
2499                         EMIT_NEW_DUMMY_USE (cfg, dummy_use, args [0]);
2500
2501                         return (MonoInst*)call;
2502                 }
2503
2504                 if ((!cfg->compile_aot || enable_for_aot) && 
2505                         (!(method->flags & METHOD_ATTRIBUTE_VIRTUAL) || 
2506                          (MONO_METHOD_IS_FINAL (method) &&
2507                           method->wrapper_type != MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)) &&
2508                         !(mono_class_is_marshalbyref (method->klass) && context_used)) {
2509                         /* 
2510                          * the method is not virtual, we just need to ensure this is not null
2511                          * and then we can call the method directly.
2512                          */
2513 #ifndef DISABLE_REMOTING
2514                         if (mono_class_is_marshalbyref (method->klass) || method->klass == mono_defaults.object_class) {
2515                                 /* 
2516                                  * The check above ensures method is not gshared, this is needed since
2517                                  * gshared methods can't have wrappers.
2518                                  */
2519                                 method = call->method = mono_marshal_get_remoting_invoke_with_check (method);
2520                         }
2521 #endif
2522
2523                         if (!method->string_ctor)
2524                                 MONO_EMIT_NEW_CHECK_THIS (cfg, this_reg);
2525
2526                         call->inst.opcode = callvirt_to_call (call->inst.opcode);
2527                 } else if ((method->flags & METHOD_ATTRIBUTE_VIRTUAL) && MONO_METHOD_IS_FINAL (method)) {
2528                         /*
2529                          * the method is virtual, but we can statically dispatch since either
2530                          * it's class or the method itself are sealed.
2531                          * But first we need to ensure it's not a null reference.
2532                          */
2533                         MONO_EMIT_NEW_CHECK_THIS (cfg, this_reg);
2534
2535                         call->inst.opcode = callvirt_to_call (call->inst.opcode);
2536                 } else if (call_target) {
2537                         vtable_reg = alloc_preg (cfg);
2538                         MONO_EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, vtable_reg, this_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
2539
2540                         call->inst.opcode = callvirt_to_call_reg (call->inst.opcode);
2541                         call->inst.sreg1 = call_target->dreg;
2542                         call->inst.flags &= !MONO_INST_HAS_METHOD;
2543                 } else {
2544                         vtable_reg = alloc_preg (cfg);
2545                         MONO_EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, vtable_reg, this_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
2546                         if (mono_class_is_interface (method->klass)) {
2547                                 guint32 imt_slot = mono_method_get_imt_slot (method);
2548                                 emit_imt_argument (cfg, call, call->method, imt_arg);
2549                                 slot_reg = vtable_reg;
2550                                 offset = ((gint32)imt_slot - MONO_IMT_SIZE) * SIZEOF_VOID_P;
2551                         } else {
2552                                 slot_reg = vtable_reg;
2553                                 offset = MONO_STRUCT_OFFSET (MonoVTable, vtable) +
2554                                         ((mono_method_get_vtable_index (method)) * (SIZEOF_VOID_P));
2555                                 if (imt_arg) {
2556                                         g_assert (mono_method_signature (method)->generic_param_count);
2557                                         emit_imt_argument (cfg, call, call->method, imt_arg);
2558                                 }
2559                         }
2560
2561                         call->inst.sreg1 = slot_reg;
2562                         call->inst.inst_offset = offset;
2563                         call->is_virtual = TRUE;
2564                 }
2565         }
2566
2567         MONO_ADD_INS (cfg->cbb, (MonoInst*)call);
2568
2569         if (rgctx_arg)
2570                 set_rgctx_arg (cfg, call, rgctx_reg, rgctx_arg);
2571
2572         return (MonoInst*)call;
2573 }
2574
2575 MonoInst*
2576 mono_emit_method_call (MonoCompile *cfg, MonoMethod *method, MonoInst **args, MonoInst *this_ins)
2577 {
2578         return mono_emit_method_call_full (cfg, method, mono_method_signature (method), FALSE, args, this_ins, NULL, NULL);
2579 }
2580
2581 MonoInst*
2582 mono_emit_native_call (MonoCompile *cfg, gconstpointer func, MonoMethodSignature *sig,
2583                                            MonoInst **args)
2584 {
2585         MonoCallInst *call;
2586
2587         g_assert (sig);
2588
2589         call = mono_emit_call_args (cfg, sig, args, FALSE, FALSE, FALSE, FALSE, FALSE, NULL);
2590         call->fptr = func;
2591
2592         MONO_ADD_INS (cfg->cbb, (MonoInst*)call);
2593
2594         return (MonoInst*)call;
2595 }
2596
2597 MonoInst*
2598 mono_emit_jit_icall (MonoCompile *cfg, gconstpointer func, MonoInst **args)
2599 {
2600         MonoJitICallInfo *info = mono_find_jit_icall_by_addr (func);
2601
2602         g_assert (info);
2603
2604         return mono_emit_native_call (cfg, mono_icall_get_wrapper (info), info->sig, args);
2605 }
2606
2607 /*
2608  * mono_emit_abs_call:
2609  *
2610  *   Emit a call to the runtime function described by PATCH_TYPE and DATA.
2611  */
2612 inline static MonoInst*
2613 mono_emit_abs_call (MonoCompile *cfg, MonoJumpInfoType patch_type, gconstpointer data, 
2614                                         MonoMethodSignature *sig, MonoInst **args)
2615 {
2616         MonoJumpInfo *ji = mono_patch_info_new (cfg->mempool, 0, patch_type, data);
2617         MonoInst *ins;
2618
2619         /* 
2620          * We pass ji as the call address, the PATCH_INFO_ABS resolving code will
2621          * handle it.
2622          */
2623         if (cfg->abs_patches == NULL)
2624                 cfg->abs_patches = g_hash_table_new (NULL, NULL);
2625         g_hash_table_insert (cfg->abs_patches, ji, ji);
2626         ins = mono_emit_native_call (cfg, ji, sig, args);
2627         ((MonoCallInst*)ins)->fptr_is_patch = TRUE;
2628         return ins;
2629 }
2630
2631 static MonoMethodSignature*
2632 sig_to_rgctx_sig (MonoMethodSignature *sig)
2633 {
2634         // FIXME: memory allocation
2635         MonoMethodSignature *res;
2636         int i;
2637
2638         res = (MonoMethodSignature *)g_malloc (MONO_SIZEOF_METHOD_SIGNATURE + (sig->param_count + 1) * sizeof (MonoType*));
2639         memcpy (res, sig, MONO_SIZEOF_METHOD_SIGNATURE);
2640         res->param_count = sig->param_count + 1;
2641         for (i = 0; i < sig->param_count; ++i)
2642                 res->params [i] = sig->params [i];
2643         res->params [sig->param_count] = &mono_defaults.int_class->this_arg;
2644         return res;
2645 }
2646
2647 /* Make an indirect call to FSIG passing an additional argument */
2648 static MonoInst*
2649 emit_extra_arg_calli (MonoCompile *cfg, MonoMethodSignature *fsig, MonoInst **orig_args, int arg_reg, MonoInst *call_target)
2650 {
2651         MonoMethodSignature *csig;
2652         MonoInst *args_buf [16];
2653         MonoInst **args;
2654         int i, pindex, tmp_reg;
2655
2656         /* Make a call with an rgctx/extra arg */
2657         if (fsig->param_count + 2 < 16)
2658                 args = args_buf;
2659         else
2660                 args = (MonoInst **)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst*) * (fsig->param_count + 2));
2661         pindex = 0;
2662         if (fsig->hasthis)
2663                 args [pindex ++] = orig_args [0];
2664         for (i = 0; i < fsig->param_count; ++i)
2665                 args [pindex ++] = orig_args [fsig->hasthis + i];
2666         tmp_reg = alloc_preg (cfg);
2667         EMIT_NEW_UNALU (cfg, args [pindex], OP_MOVE, tmp_reg, arg_reg);
2668         csig = sig_to_rgctx_sig (fsig);
2669         return mini_emit_calli (cfg, csig, args, call_target, NULL, NULL);
2670 }
2671
2672 /* Emit an indirect call to the function descriptor ADDR */
2673 static MonoInst*
2674 emit_llvmonly_calli (MonoCompile *cfg, MonoMethodSignature *fsig, MonoInst **args, MonoInst *addr)
2675 {
2676         int addr_reg, arg_reg;
2677         MonoInst *call_target;
2678
2679         g_assert (cfg->llvm_only);
2680
2681         /*
2682          * addr points to a <addr, arg> pair, load both of them, and
2683          * make a call to addr, passing arg as an extra arg.
2684          */
2685         addr_reg = alloc_preg (cfg);
2686         EMIT_NEW_LOAD_MEMBASE (cfg, call_target, OP_LOAD_MEMBASE, addr_reg, addr->dreg, 0);
2687         arg_reg = alloc_preg (cfg);
2688         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, arg_reg, addr->dreg, sizeof (gpointer));
2689
2690         return emit_extra_arg_calli (cfg, fsig, args, arg_reg, call_target);
2691 }
2692
2693 static gboolean
2694 direct_icalls_enabled (MonoCompile *cfg)
2695 {
2696         return FALSE;
2697
2698         /* LLVM on amd64 can't handle calls to non-32 bit addresses */
2699 #ifdef TARGET_AMD64
2700         if (cfg->compile_llvm && !cfg->llvm_only)
2701                 return FALSE;
2702 #endif
2703         if (cfg->gen_sdb_seq_points || cfg->disable_direct_icalls)
2704                 return FALSE;
2705         return TRUE;
2706 }
2707
2708 MonoInst*
2709 mono_emit_jit_icall_by_info (MonoCompile *cfg, int il_offset, MonoJitICallInfo *info, MonoInst **args)
2710 {
2711         /*
2712          * Call the jit icall without a wrapper if possible.
2713          * The wrapper is needed for the following reasons:
2714          * - to handle exceptions thrown using mono_raise_exceptions () from the
2715          *   icall function. The EH code needs the lmf frame pushed by the
2716          *   wrapper to be able to unwind back to managed code.
2717          * - to be able to do stack walks for asynchronously suspended
2718          *   threads when debugging.
2719          */
2720         if (info->no_raise && direct_icalls_enabled (cfg)) {
2721                 char *name;
2722                 int costs;
2723
2724                 if (!info->wrapper_method) {
2725                         name = g_strdup_printf ("__icall_wrapper_%s", info->name);
2726                         info->wrapper_method = mono_marshal_get_icall_wrapper (info->sig, name, info->func, TRUE);
2727                         g_free (name);
2728                         mono_memory_barrier ();
2729                 }
2730
2731                 /*
2732                  * Inline the wrapper method, which is basically a call to the C icall, and
2733                  * an exception check.
2734                  */
2735                 costs = inline_method (cfg, info->wrapper_method, NULL,
2736                                                            args, NULL, il_offset, TRUE);
2737                 g_assert (costs > 0);
2738                 g_assert (!MONO_TYPE_IS_VOID (info->sig->ret));
2739
2740                 return args [0];
2741         } else {
2742                 return mono_emit_native_call (cfg, mono_icall_get_wrapper (info), info->sig, args);
2743         }
2744 }
2745  
2746 static MonoInst*
2747 mono_emit_widen_call_res (MonoCompile *cfg, MonoInst *ins, MonoMethodSignature *fsig)
2748 {
2749         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
2750                 if ((fsig->pinvoke || LLVM_ENABLED) && !fsig->ret->byref) {
2751                         int widen_op = -1;
2752
2753                         /* 
2754                          * Native code might return non register sized integers 
2755                          * without initializing the upper bits.
2756                          */
2757                         switch (mono_type_to_load_membase (cfg, fsig->ret)) {
2758                         case OP_LOADI1_MEMBASE:
2759                                 widen_op = OP_ICONV_TO_I1;
2760                                 break;
2761                         case OP_LOADU1_MEMBASE:
2762                                 widen_op = OP_ICONV_TO_U1;
2763                                 break;
2764                         case OP_LOADI2_MEMBASE:
2765                                 widen_op = OP_ICONV_TO_I2;
2766                                 break;
2767                         case OP_LOADU2_MEMBASE:
2768                                 widen_op = OP_ICONV_TO_U2;
2769                                 break;
2770                         default:
2771                                 break;
2772                         }
2773
2774                         if (widen_op != -1) {
2775                                 int dreg = alloc_preg (cfg);
2776                                 MonoInst *widen;
2777
2778                                 EMIT_NEW_UNALU (cfg, widen, widen_op, dreg, ins->dreg);
2779                                 widen->type = ins->type;
2780                                 ins = widen;
2781                         }
2782                 }
2783         }
2784
2785         return ins;
2786 }
2787
2788
2789 static void
2790 emit_method_access_failure (MonoCompile *cfg, MonoMethod *caller, MonoMethod *callee)
2791 {
2792         MonoInst *args [16];
2793
2794         args [0] = emit_get_rgctx_method (cfg, mono_method_check_context_used (caller), caller, MONO_RGCTX_INFO_METHOD);
2795         args [1] = emit_get_rgctx_method (cfg, mono_method_check_context_used (callee), callee, MONO_RGCTX_INFO_METHOD);
2796
2797         mono_emit_jit_icall (cfg, mono_throw_method_access, args);
2798 }
2799
2800 MonoMethod*
2801 mini_get_memcpy_method (void)
2802 {
2803         static MonoMethod *memcpy_method = NULL;
2804         if (!memcpy_method) {
2805                 memcpy_method = mono_class_get_method_from_name (mono_defaults.string_class, "memcpy", 3);
2806                 if (!memcpy_method)
2807                         g_error ("Old corlib found. Install a new one");
2808         }
2809         return memcpy_method;
2810 }
2811
2812 void
2813 mini_emit_write_barrier (MonoCompile *cfg, MonoInst *ptr, MonoInst *value)
2814 {
2815         int card_table_shift_bits;
2816         gpointer card_table_mask;
2817         guint8 *card_table;
2818         MonoInst *dummy_use;
2819         int nursery_shift_bits;
2820         size_t nursery_size;
2821
2822         if (!cfg->gen_write_barriers)
2823                 return;
2824
2825         //method->wrapper_type != MONO_WRAPPER_WRITE_BARRIER && !MONO_INS_IS_PCONST_NULL (sp [1])
2826
2827         card_table = mono_gc_get_card_table (&card_table_shift_bits, &card_table_mask);
2828
2829         mono_gc_get_nursery (&nursery_shift_bits, &nursery_size);
2830
2831         if (cfg->backend->have_card_table_wb && !cfg->compile_aot && card_table && nursery_shift_bits > 0 && !COMPILE_LLVM (cfg)) {
2832                 MonoInst *wbarrier;
2833
2834                 MONO_INST_NEW (cfg, wbarrier, OP_CARD_TABLE_WBARRIER);
2835                 wbarrier->sreg1 = ptr->dreg;
2836                 wbarrier->sreg2 = value->dreg;
2837                 MONO_ADD_INS (cfg->cbb, wbarrier);
2838         } else if (card_table) {
2839                 int offset_reg = alloc_preg (cfg);
2840                 int card_reg;
2841                 MonoInst *ins;
2842
2843                 /*
2844                  * We emit a fast light weight write barrier. This always marks cards as in the concurrent
2845                  * collector case, so, for the serial collector, it might slightly slow down nursery
2846                  * collections. We also expect that the host system and the target system have the same card
2847                  * table configuration, which is the case if they have the same pointer size.
2848                  */
2849
2850                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHR_UN_IMM, offset_reg, ptr->dreg, card_table_shift_bits);
2851                 if (card_table_mask)
2852                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PAND_IMM, offset_reg, offset_reg, card_table_mask);
2853
2854                 /*We can't use PADD_IMM since the cardtable might end up in high addresses and amd64 doesn't support
2855                  * IMM's larger than 32bits.
2856                  */
2857                 ins = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_GC_CARD_TABLE_ADDR, NULL);
2858                 card_reg = ins->dreg;
2859
2860                 MONO_EMIT_NEW_BIALU (cfg, OP_PADD, offset_reg, offset_reg, card_reg);
2861                 MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STOREI1_MEMBASE_IMM, offset_reg, 0, 1);
2862         } else {
2863                 MonoMethod *write_barrier = mono_gc_get_write_barrier ();
2864                 mono_emit_method_call (cfg, write_barrier, &ptr, NULL);
2865         }
2866
2867         EMIT_NEW_DUMMY_USE (cfg, dummy_use, value);
2868 }
2869
2870 MonoMethod*
2871 mini_get_memset_method (void)
2872 {
2873         static MonoMethod *memset_method = NULL;
2874         if (!memset_method) {
2875                 memset_method = mono_class_get_method_from_name (mono_defaults.string_class, "memset", 3);
2876                 if (!memset_method)
2877                         g_error ("Old corlib found. Install a new one");
2878         }
2879         return memset_method;
2880 }
2881
2882 void
2883 mini_emit_initobj (MonoCompile *cfg, MonoInst *dest, const guchar *ip, MonoClass *klass)
2884 {
2885         MonoInst *iargs [3];
2886         int n;
2887         guint32 align;
2888         MonoMethod *memset_method;
2889         MonoInst *size_ins = NULL;
2890         MonoInst *bzero_ins = NULL;
2891         static MonoMethod *bzero_method;
2892
2893         /* FIXME: Optimize this for the case when dest is an LDADDR */
2894         mono_class_init (klass);
2895         if (mini_is_gsharedvt_klass (klass)) {
2896                 size_ins = mini_emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_VALUE_SIZE);
2897                 bzero_ins = mini_emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_BZERO);
2898                 if (!bzero_method)
2899                         bzero_method = mono_class_get_method_from_name (mono_defaults.string_class, "bzero_aligned_1", 2);
2900                 g_assert (bzero_method);
2901                 iargs [0] = dest;
2902                 iargs [1] = size_ins;
2903                 mini_emit_calli (cfg, mono_method_signature (bzero_method), iargs, bzero_ins, NULL, NULL);
2904                 return;
2905         }
2906
2907         klass = mono_class_from_mono_type (mini_get_underlying_type (&klass->byval_arg));
2908
2909         n = mono_class_value_size (klass, &align);
2910
2911         if (n <= sizeof (gpointer) * 8) {
2912                 mini_emit_memset (cfg, dest->dreg, 0, n, 0, align);
2913         }
2914         else {
2915                 memset_method = mini_get_memset_method ();
2916                 iargs [0] = dest;
2917                 EMIT_NEW_ICONST (cfg, iargs [1], 0);
2918                 EMIT_NEW_ICONST (cfg, iargs [2], n);
2919                 mono_emit_method_call (cfg, memset_method, iargs, NULL);
2920         }
2921 }
2922
2923 /*
2924  * emit_get_rgctx:
2925  *
2926  *   Emit IR to return either the this pointer for instance method,
2927  * or the mrgctx for static methods.
2928  */
2929 static MonoInst*
2930 emit_get_rgctx (MonoCompile *cfg, MonoMethod *method, int context_used)
2931 {
2932         MonoInst *this_ins = NULL;
2933
2934         g_assert (cfg->gshared);
2935
2936         if (!(method->flags & METHOD_ATTRIBUTE_STATIC) &&
2937                         !(context_used & MONO_GENERIC_CONTEXT_USED_METHOD) &&
2938                 !method->klass->valuetype)
2939                 EMIT_NEW_VARLOAD (cfg, this_ins, cfg->this_arg, &mono_defaults.object_class->byval_arg);
2940
2941         if (context_used & MONO_GENERIC_CONTEXT_USED_METHOD) {
2942                 MonoInst *mrgctx_loc, *mrgctx_var;
2943
2944                 g_assert (!this_ins);
2945                 g_assert (method->is_inflated && mono_method_get_context (method)->method_inst);
2946
2947                 mrgctx_loc = mono_get_vtable_var (cfg);
2948                 EMIT_NEW_TEMPLOAD (cfg, mrgctx_var, mrgctx_loc->inst_c0);
2949
2950                 return mrgctx_var;
2951         } else if (MONO_CLASS_IS_INTERFACE (cfg->method->klass)) {
2952                 MonoInst *mrgctx_loc, *mrgctx_var;
2953
2954                 /* Default interface methods need an mrgctx since the vtabke at runtime points at an implementing class */
2955                 mrgctx_loc = mono_get_vtable_var (cfg);
2956                 EMIT_NEW_TEMPLOAD (cfg, mrgctx_var, mrgctx_loc->inst_c0);
2957
2958                 g_assert (mono_method_needs_static_rgctx_invoke (cfg->method, TRUE));
2959
2960                 return mrgctx_var;
2961         } else if (method->flags & METHOD_ATTRIBUTE_STATIC || method->klass->valuetype) {
2962                 MonoInst *vtable_loc, *vtable_var;
2963
2964                 g_assert (!this_ins);
2965
2966                 vtable_loc = mono_get_vtable_var (cfg);
2967                 EMIT_NEW_TEMPLOAD (cfg, vtable_var, vtable_loc->inst_c0);
2968
2969                 if (method->is_inflated && mono_method_get_context (method)->method_inst) {
2970                         MonoInst *mrgctx_var = vtable_var;
2971                         int vtable_reg;
2972
2973                         vtable_reg = alloc_preg (cfg);
2974                         EMIT_NEW_LOAD_MEMBASE (cfg, vtable_var, OP_LOAD_MEMBASE, vtable_reg, mrgctx_var->dreg, MONO_STRUCT_OFFSET (MonoMethodRuntimeGenericContext, class_vtable));
2975                         vtable_var->type = STACK_PTR;
2976                 }
2977
2978                 return vtable_var;
2979         } else {
2980                 MonoInst *ins;
2981                 int vtable_reg;
2982         
2983                 vtable_reg = alloc_preg (cfg);
2984                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, vtable_reg, this_ins->dreg, MONO_STRUCT_OFFSET (MonoObject, vtable));
2985                 return ins;
2986         }
2987 }
2988
2989 static MonoJumpInfoRgctxEntry *
2990 mono_patch_info_rgctx_entry_new (MonoMemPool *mp, MonoMethod *method, gboolean in_mrgctx, MonoJumpInfoType patch_type, gconstpointer patch_data, MonoRgctxInfoType info_type)
2991 {
2992         MonoJumpInfoRgctxEntry *res = (MonoJumpInfoRgctxEntry *)mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoRgctxEntry));
2993         res->method = method;
2994         res->in_mrgctx = in_mrgctx;
2995         res->data = (MonoJumpInfo *)mono_mempool_alloc0 (mp, sizeof (MonoJumpInfo));
2996         res->data->type = patch_type;
2997         res->data->data.target = patch_data;
2998         res->info_type = info_type;
2999
3000         return res;
3001 }
3002
3003 static inline MonoInst*
3004 emit_rgctx_fetch_inline (MonoCompile *cfg, MonoInst *rgctx, MonoJumpInfoRgctxEntry *entry)
3005 {
3006         MonoInst *args [16];
3007         MonoInst *call;
3008
3009         // FIXME: No fastpath since the slot is not a compile time constant
3010         args [0] = rgctx;
3011         EMIT_NEW_AOTCONST (cfg, args [1], MONO_PATCH_INFO_RGCTX_SLOT_INDEX, entry);
3012         if (entry->in_mrgctx)
3013                 call = mono_emit_jit_icall (cfg, mono_fill_method_rgctx, args);
3014         else
3015                 call = mono_emit_jit_icall (cfg, mono_fill_class_rgctx, args);
3016         return call;
3017 #if 0
3018         /*
3019          * FIXME: This can be called during decompose, which is a problem since it creates
3020          * new bblocks.
3021          * Also, the fastpath doesn't work since the slot number is dynamically allocated.
3022          */
3023         int i, slot, depth, index, rgctx_reg, val_reg, res_reg;
3024         gboolean mrgctx;
3025         MonoBasicBlock *is_null_bb, *end_bb;
3026         MonoInst *res, *ins, *call;
3027         MonoInst *args[16];
3028
3029         slot = mini_get_rgctx_entry_slot (entry);
3030
3031         mrgctx = MONO_RGCTX_SLOT_IS_MRGCTX (slot);
3032         index = MONO_RGCTX_SLOT_INDEX (slot);
3033         if (mrgctx)
3034                 index += MONO_SIZEOF_METHOD_RUNTIME_GENERIC_CONTEXT / sizeof (gpointer);
3035         for (depth = 0; ; ++depth) {
3036                 int size = mono_class_rgctx_get_array_size (depth, mrgctx);
3037
3038                 if (index < size - 1)
3039                         break;
3040                 index -= size - 1;
3041         }
3042
3043         NEW_BBLOCK (cfg, end_bb);
3044         NEW_BBLOCK (cfg, is_null_bb);
3045
3046         if (mrgctx) {
3047                 rgctx_reg = rgctx->dreg;
3048         } else {
3049                 rgctx_reg = alloc_preg (cfg);
3050
3051                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, rgctx_reg, rgctx->dreg, MONO_STRUCT_OFFSET (MonoVTable, runtime_generic_context));
3052                 // FIXME: Avoid this check by allocating the table when the vtable is created etc.
3053                 NEW_BBLOCK (cfg, is_null_bb);
3054
3055                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, rgctx_reg, 0);
3056                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, is_null_bb);
3057         }
3058
3059         for (i = 0; i < depth; ++i) {
3060                 int array_reg = alloc_preg (cfg);
3061
3062                 /* load ptr to next array */
3063                 if (mrgctx && i == 0)
3064                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, array_reg, rgctx_reg, MONO_SIZEOF_METHOD_RUNTIME_GENERIC_CONTEXT);
3065                 else
3066                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, array_reg, rgctx_reg, 0);
3067                 rgctx_reg = array_reg;
3068                 /* is the ptr null? */
3069                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, rgctx_reg, 0);
3070                 /* if yes, jump to actual trampoline */
3071                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, is_null_bb);
3072         }
3073
3074         /* fetch slot */
3075         val_reg = alloc_preg (cfg);
3076         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, val_reg, rgctx_reg, (index + 1) * sizeof (gpointer));
3077         /* is the slot null? */
3078         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, val_reg, 0);
3079         /* if yes, jump to actual trampoline */
3080         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, is_null_bb);
3081
3082         /* Fastpath */
3083         res_reg = alloc_preg (cfg);
3084         MONO_INST_NEW (cfg, ins, OP_MOVE);
3085         ins->dreg = res_reg;
3086         ins->sreg1 = val_reg;
3087         MONO_ADD_INS (cfg->cbb, ins);
3088         res = ins;
3089         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
3090
3091         /* Slowpath */
3092         MONO_START_BB (cfg, is_null_bb);
3093         args [0] = rgctx;
3094         EMIT_NEW_ICONST (cfg, args [1], index);
3095         if (mrgctx)
3096                 call = mono_emit_jit_icall (cfg, mono_fill_method_rgctx, args);
3097         else
3098                 call = mono_emit_jit_icall (cfg, mono_fill_class_rgctx, args);
3099         MONO_INST_NEW (cfg, ins, OP_MOVE);
3100         ins->dreg = res_reg;
3101         ins->sreg1 = call->dreg;
3102         MONO_ADD_INS (cfg->cbb, ins);
3103         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
3104
3105         MONO_START_BB (cfg, end_bb);
3106
3107         return res;
3108 #endif
3109 }
3110
3111 /*
3112  * emit_rgctx_fetch:
3113  *
3114  *   Emit IR to load the value of the rgctx entry ENTRY from the rgctx
3115  * given by RGCTX.
3116  */
3117 static inline MonoInst*
3118 emit_rgctx_fetch (MonoCompile *cfg, MonoInst *rgctx, MonoJumpInfoRgctxEntry *entry)
3119 {
3120         if (cfg->llvm_only)
3121                 return emit_rgctx_fetch_inline (cfg, rgctx, entry);
3122         else
3123                 return mono_emit_abs_call (cfg, MONO_PATCH_INFO_RGCTX_FETCH, entry, helper_sig_rgctx_lazy_fetch_trampoline, &rgctx);
3124 }
3125
3126 MonoInst*
3127 mini_emit_get_rgctx_klass (MonoCompile *cfg, int context_used,
3128                                           MonoClass *klass, MonoRgctxInfoType rgctx_type)
3129 {
3130         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);
3131         MonoInst *rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3132
3133         return emit_rgctx_fetch (cfg, rgctx, entry);
3134 }
3135
3136 static MonoInst*
3137 emit_get_rgctx_sig (MonoCompile *cfg, int context_used,
3138                                         MonoMethodSignature *sig, MonoRgctxInfoType rgctx_type)
3139 {
3140         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);
3141         MonoInst *rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3142
3143         return emit_rgctx_fetch (cfg, rgctx, entry);
3144 }
3145
3146 static MonoInst*
3147 emit_get_rgctx_gsharedvt_call (MonoCompile *cfg, int context_used,
3148                                                            MonoMethodSignature *sig, MonoMethod *cmethod, MonoRgctxInfoType rgctx_type)
3149 {
3150         MonoJumpInfoGSharedVtCall *call_info;
3151         MonoJumpInfoRgctxEntry *entry;
3152         MonoInst *rgctx;
3153
3154         call_info = (MonoJumpInfoGSharedVtCall *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoJumpInfoGSharedVtCall));
3155         call_info->sig = sig;
3156         call_info->method = cmethod;
3157
3158         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);
3159         rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3160
3161         return emit_rgctx_fetch (cfg, rgctx, entry);
3162 }
3163
3164 /*
3165  * emit_get_rgctx_virt_method:
3166  *
3167  *   Return data for method VIRT_METHOD for a receiver of type KLASS.
3168  */
3169 static MonoInst*
3170 emit_get_rgctx_virt_method (MonoCompile *cfg, int context_used,
3171                                                         MonoClass *klass, MonoMethod *virt_method, MonoRgctxInfoType rgctx_type)
3172 {
3173         MonoJumpInfoVirtMethod *info;
3174         MonoJumpInfoRgctxEntry *entry;
3175         MonoInst *rgctx;
3176
3177         info = (MonoJumpInfoVirtMethod *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoJumpInfoVirtMethod));
3178         info->klass = klass;
3179         info->method = virt_method;
3180
3181         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);
3182         rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3183
3184         return emit_rgctx_fetch (cfg, rgctx, entry);
3185 }
3186
3187 static MonoInst*
3188 emit_get_rgctx_gsharedvt_method (MonoCompile *cfg, int context_used,
3189                                                                  MonoMethod *cmethod, MonoGSharedVtMethodInfo *info)
3190 {
3191         MonoJumpInfoRgctxEntry *entry;
3192         MonoInst *rgctx;
3193
3194         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);
3195         rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3196
3197         return emit_rgctx_fetch (cfg, rgctx, entry);
3198 }
3199
3200 /*
3201  * emit_get_rgctx_method:
3202  *
3203  *   Emit IR to load the property RGCTX_TYPE of CMETHOD. If context_used is 0, emit
3204  * normal constants, else emit a load from the rgctx.
3205  */
3206 static MonoInst*
3207 emit_get_rgctx_method (MonoCompile *cfg, int context_used,
3208                                            MonoMethod *cmethod, MonoRgctxInfoType rgctx_type)
3209 {
3210         if (!context_used) {
3211                 MonoInst *ins;
3212
3213                 switch (rgctx_type) {
3214                 case MONO_RGCTX_INFO_METHOD:
3215                         EMIT_NEW_METHODCONST (cfg, ins, cmethod);
3216                         return ins;
3217                 case MONO_RGCTX_INFO_METHOD_RGCTX:
3218                         EMIT_NEW_METHOD_RGCTX_CONST (cfg, ins, cmethod);
3219                         return ins;
3220                 default:
3221                         g_assert_not_reached ();
3222                 }
3223         } else {
3224                 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);
3225                 MonoInst *rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3226
3227                 return emit_rgctx_fetch (cfg, rgctx, entry);
3228         }
3229 }
3230
3231 static MonoInst*
3232 emit_get_rgctx_field (MonoCompile *cfg, int context_used,
3233                                           MonoClassField *field, MonoRgctxInfoType rgctx_type)
3234 {
3235         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);
3236         MonoInst *rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3237
3238         return emit_rgctx_fetch (cfg, rgctx, entry);
3239 }
3240
3241 static int
3242 get_gsharedvt_info_slot (MonoCompile *cfg, gpointer data, MonoRgctxInfoType rgctx_type)
3243 {
3244         MonoGSharedVtMethodInfo *info = cfg->gsharedvt_info;
3245         MonoRuntimeGenericContextInfoTemplate *template_;
3246         int i, idx;
3247
3248         g_assert (info);
3249
3250         for (i = 0; i < info->num_entries; ++i) {
3251                 MonoRuntimeGenericContextInfoTemplate *otemplate = &info->entries [i];
3252
3253                 if (otemplate->info_type == rgctx_type && otemplate->data == data && rgctx_type != MONO_RGCTX_INFO_LOCAL_OFFSET)
3254                         return i;
3255         }
3256
3257         if (info->num_entries == info->count_entries) {
3258                 MonoRuntimeGenericContextInfoTemplate *new_entries;
3259                 int new_count_entries = info->count_entries ? info->count_entries * 2 : 16;
3260
3261                 new_entries = (MonoRuntimeGenericContextInfoTemplate *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoRuntimeGenericContextInfoTemplate) * new_count_entries);
3262
3263                 memcpy (new_entries, info->entries, sizeof (MonoRuntimeGenericContextInfoTemplate) * info->count_entries);
3264                 info->entries = new_entries;
3265                 info->count_entries = new_count_entries;
3266         }
3267
3268         idx = info->num_entries;
3269         template_ = &info->entries [idx];
3270         template_->info_type = rgctx_type;
3271         template_->data = data;
3272
3273         info->num_entries ++;
3274
3275         return idx;
3276 }
3277
3278 /*
3279  * emit_get_gsharedvt_info:
3280  *
3281  *   This is similar to emit_get_rgctx_.., but loads the data from the gsharedvt info var instead of calling an rgctx fetch trampoline.
3282  */
3283 static MonoInst*
3284 emit_get_gsharedvt_info (MonoCompile *cfg, gpointer data, MonoRgctxInfoType rgctx_type)
3285 {
3286         MonoInst *ins;
3287         int idx, dreg;
3288
3289         idx = get_gsharedvt_info_slot (cfg, data, rgctx_type);
3290         /* Load info->entries [idx] */
3291         dreg = alloc_preg (cfg);
3292         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, dreg, cfg->gsharedvt_info_var->dreg, MONO_STRUCT_OFFSET (MonoGSharedVtMethodRuntimeInfo, entries) + (idx * sizeof (gpointer)));
3293
3294         return ins;
3295 }
3296
3297 MonoInst*
3298 mini_emit_get_gsharedvt_info_klass (MonoCompile *cfg, MonoClass *klass, MonoRgctxInfoType rgctx_type)
3299 {
3300         return emit_get_gsharedvt_info (cfg, &klass->byval_arg, rgctx_type);
3301 }
3302
3303 /*
3304  * On return the caller must check @klass for load errors.
3305  */
3306 static void
3307 emit_class_init (MonoCompile *cfg, MonoClass *klass)
3308 {
3309         MonoInst *vtable_arg;
3310         int context_used;
3311
3312         context_used = mini_class_check_context_used (cfg, klass);
3313
3314         if (context_used) {
3315                 vtable_arg = mini_emit_get_rgctx_klass (cfg, context_used,
3316                                                                                    klass, MONO_RGCTX_INFO_VTABLE);
3317         } else {
3318                 MonoVTable *vtable = mono_class_vtable (cfg->domain, klass);
3319
3320                 if (!vtable)
3321                         return;
3322                 EMIT_NEW_VTABLECONST (cfg, vtable_arg, vtable);
3323         }
3324
3325         if (!COMPILE_LLVM (cfg) && cfg->backend->have_op_generic_class_init) {
3326                 MonoInst *ins;
3327
3328                 /*
3329                  * Using an opcode instead of emitting IR here allows the hiding of the call inside the opcode,
3330                  * so this doesn't have to clobber any regs and it doesn't break basic blocks.
3331                  */
3332                 MONO_INST_NEW (cfg, ins, OP_GENERIC_CLASS_INIT);
3333                 ins->sreg1 = vtable_arg->dreg;
3334                 MONO_ADD_INS (cfg->cbb, ins);
3335         } else {
3336                 int inited_reg;
3337                 MonoBasicBlock *inited_bb;
3338                 MonoInst *args [16];
3339
3340                 inited_reg = alloc_ireg (cfg);
3341
3342                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADU1_MEMBASE, inited_reg, vtable_arg->dreg, MONO_STRUCT_OFFSET (MonoVTable, initialized));
3343
3344                 NEW_BBLOCK (cfg, inited_bb);
3345
3346                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, inited_reg, 0);
3347                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBNE_UN, inited_bb);
3348
3349                 args [0] = vtable_arg;
3350                 mono_emit_jit_icall (cfg, mono_generic_class_init, args);
3351
3352                 MONO_START_BB (cfg, inited_bb);
3353         }
3354 }
3355
3356 static void
3357 emit_seq_point (MonoCompile *cfg, MonoMethod *method, guint8* ip, gboolean intr_loc, gboolean nonempty_stack)
3358 {
3359         MonoInst *ins;
3360
3361         if (cfg->gen_seq_points && cfg->method == method) {
3362                 NEW_SEQ_POINT (cfg, ins, ip - cfg->header->code, intr_loc);
3363                 if (nonempty_stack)
3364                         ins->flags |= MONO_INST_NONEMPTY_STACK;
3365                 MONO_ADD_INS (cfg->cbb, ins);
3366         }
3367 }
3368
3369 void
3370 mini_save_cast_details (MonoCompile *cfg, MonoClass *klass, int obj_reg, gboolean null_check)
3371 {
3372         if (mini_get_debug_options ()->better_cast_details) {
3373                 int vtable_reg = alloc_preg (cfg);
3374                 int klass_reg = alloc_preg (cfg);
3375                 MonoBasicBlock *is_null_bb = NULL;
3376                 MonoInst *tls_get;
3377                 int to_klass_reg, context_used;
3378
3379                 if (null_check) {
3380                         NEW_BBLOCK (cfg, is_null_bb);
3381
3382                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, obj_reg, 0);
3383                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, is_null_bb);
3384                 }
3385
3386                 tls_get = mono_create_tls_get (cfg, TLS_KEY_JIT_TLS);
3387                 if (!tls_get) {
3388                         fprintf (stderr, "error: --debug=casts not supported on this platform.\n.");
3389                         exit (1);
3390                 }
3391
3392                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, vtable_reg, obj_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
3393                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, klass));
3394
3395                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, tls_get->dreg, MONO_STRUCT_OFFSET (MonoJitTlsData, class_cast_from), klass_reg);
3396
3397                 context_used = mini_class_check_context_used (cfg, klass);
3398                 if (context_used) {
3399                         MonoInst *class_ins;
3400
3401                         class_ins = mini_emit_get_rgctx_klass (cfg, context_used, klass, MONO_RGCTX_INFO_KLASS);
3402                         to_klass_reg = class_ins->dreg;
3403                 } else {
3404                         to_klass_reg = alloc_preg (cfg);
3405                         MONO_EMIT_NEW_CLASSCONST (cfg, to_klass_reg, klass);
3406                 }
3407                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, tls_get->dreg, MONO_STRUCT_OFFSET (MonoJitTlsData, class_cast_to), to_klass_reg);
3408
3409                 if (null_check)
3410                         MONO_START_BB (cfg, is_null_bb);
3411         }
3412 }
3413
3414 void
3415 mini_reset_cast_details (MonoCompile *cfg)
3416 {
3417         /* Reset the variables holding the cast details */
3418         if (mini_get_debug_options ()->better_cast_details) {
3419                 MonoInst *tls_get = mono_create_tls_get (cfg, TLS_KEY_JIT_TLS);
3420                 /* It is enough to reset the from field */
3421                 MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STORE_MEMBASE_IMM, tls_get->dreg, MONO_STRUCT_OFFSET (MonoJitTlsData, class_cast_from), 0);
3422         }
3423 }
3424
3425 /*
3426  * On return the caller must check @array_class for load errors
3427  */
3428 static void
3429 mini_emit_check_array_type (MonoCompile *cfg, MonoInst *obj, MonoClass *array_class)
3430 {
3431         int vtable_reg = alloc_preg (cfg);
3432         int context_used;
3433
3434         context_used = mini_class_check_context_used (cfg, array_class);
3435
3436         mini_save_cast_details (cfg, array_class, obj->dreg, FALSE);
3437
3438         MONO_EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, vtable_reg, obj->dreg, MONO_STRUCT_OFFSET (MonoObject, vtable));
3439
3440         if (cfg->opt & MONO_OPT_SHARED) {
3441                 int class_reg = alloc_preg (cfg);
3442                 MonoInst *ins;
3443
3444                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, class_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, klass));
3445                 ins = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_CLASS, array_class);
3446                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, class_reg, ins->dreg);
3447         } else if (context_used) {
3448                 MonoInst *vtable_ins;
3449
3450                 vtable_ins = mini_emit_get_rgctx_klass (cfg, context_used, array_class, MONO_RGCTX_INFO_VTABLE);
3451                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, vtable_reg, vtable_ins->dreg);
3452         } else {
3453                 if (cfg->compile_aot) {
3454                         int vt_reg;
3455                         MonoVTable *vtable;
3456
3457                         if (!(vtable = mono_class_vtable (cfg->domain, array_class)))
3458                                 return;
3459                         vt_reg = alloc_preg (cfg);
3460                         MONO_EMIT_NEW_VTABLECONST (cfg, vt_reg, vtable);
3461                         MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, vtable_reg, vt_reg);
3462                 } else {
3463                         MonoVTable *vtable;
3464                         if (!(vtable = mono_class_vtable (cfg->domain, array_class)))
3465                                 return;
3466                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, vtable_reg, vtable);
3467                 }
3468         }
3469         
3470         MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "ArrayTypeMismatchException");
3471
3472         mini_reset_cast_details (cfg);
3473 }
3474
3475 /**
3476  * Handles unbox of a Nullable<T>. If context_used is non zero, then shared 
3477  * generic code is generated.
3478  */
3479 static MonoInst*
3480 handle_unbox_nullable (MonoCompile* cfg, MonoInst* val, MonoClass* klass, int context_used)
3481 {
3482         MonoMethod* method = mono_class_get_method_from_name (klass, "Unbox", 1);
3483
3484         if (context_used) {
3485                 MonoInst *rgctx, *addr;
3486
3487                 /* FIXME: What if the class is shared?  We might not
3488                    have to get the address of the method from the
3489                    RGCTX. */
3490                 addr = emit_get_rgctx_method (cfg, context_used, method,
3491                                                                           MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
3492                 if (cfg->llvm_only) {
3493                         cfg->signatures = g_slist_prepend_mempool (cfg->mempool, cfg->signatures, mono_method_signature (method));
3494                         return emit_llvmonly_calli (cfg, mono_method_signature (method), &val, addr);
3495                 } else {
3496                         rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3497
3498                         return mini_emit_calli (cfg, mono_method_signature (method), &val, addr, NULL, rgctx);
3499                 }
3500         } else {
3501                 gboolean pass_vtable, pass_mrgctx;
3502                 MonoInst *rgctx_arg = NULL;
3503
3504                 check_method_sharing (cfg, method, &pass_vtable, &pass_mrgctx);
3505                 g_assert (!pass_mrgctx);
3506
3507                 if (pass_vtable) {
3508                         MonoVTable *vtable = mono_class_vtable (cfg->domain, method->klass);
3509
3510                         g_assert (vtable);
3511                         EMIT_NEW_VTABLECONST (cfg, rgctx_arg, vtable);
3512                 }
3513
3514                 return mono_emit_method_call_full (cfg, method, NULL, FALSE, &val, NULL, NULL, rgctx_arg);
3515         }
3516 }
3517
3518 static MonoInst*
3519 handle_unbox (MonoCompile *cfg, MonoClass *klass, MonoInst **sp, int context_used)
3520 {
3521         MonoInst *add;
3522         int obj_reg;
3523         int vtable_reg = alloc_dreg (cfg ,STACK_PTR);
3524         int klass_reg = alloc_dreg (cfg ,STACK_PTR);
3525         int eclass_reg = alloc_dreg (cfg ,STACK_PTR);
3526         int rank_reg = alloc_dreg (cfg ,STACK_I4);
3527
3528         obj_reg = sp [0]->dreg;
3529         MONO_EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, vtable_reg, obj_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
3530         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADU1_MEMBASE, rank_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, rank));
3531
3532         /* FIXME: generics */
3533         g_assert (klass->rank == 0);
3534                         
3535         // Check rank == 0
3536         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, rank_reg, 0);
3537         MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "InvalidCastException");
3538
3539         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, klass));
3540         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, eclass_reg, klass_reg, MONO_STRUCT_OFFSET (MonoClass, element_class));
3541
3542         if (context_used) {
3543                 MonoInst *element_class;
3544
3545                 /* This assertion is from the unboxcast insn */
3546                 g_assert (klass->rank == 0);
3547
3548                 element_class = mini_emit_get_rgctx_klass (cfg, context_used,
3549                                 klass, MONO_RGCTX_INFO_ELEMENT_KLASS);
3550
3551                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, eclass_reg, element_class->dreg);
3552                 MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "InvalidCastException");
3553         } else {
3554                 mini_save_cast_details (cfg, klass->element_class, obj_reg, FALSE);
3555                 mini_emit_class_check (cfg, eclass_reg, klass->element_class);
3556                 mini_reset_cast_details (cfg);
3557         }
3558
3559         NEW_BIALU_IMM (cfg, add, OP_ADD_IMM, alloc_dreg (cfg, STACK_MP), obj_reg, sizeof (MonoObject));
3560         MONO_ADD_INS (cfg->cbb, add);
3561         add->type = STACK_MP;
3562         add->klass = klass;
3563
3564         return add;
3565 }
3566
3567 static MonoInst*
3568 handle_unbox_gsharedvt (MonoCompile *cfg, MonoClass *klass, MonoInst *obj)
3569 {
3570         MonoInst *addr, *klass_inst, *is_ref, *args[16];
3571         MonoBasicBlock *is_ref_bb, *is_nullable_bb, *end_bb;
3572         MonoInst *ins;
3573         int dreg, addr_reg;
3574
3575         klass_inst = mini_emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_KLASS);
3576
3577         /* obj */
3578         args [0] = obj;
3579
3580         /* klass */
3581         args [1] = klass_inst;
3582
3583         /* CASTCLASS */
3584         obj = mono_emit_jit_icall (cfg, mono_object_castclass_unbox, args);
3585
3586         NEW_BBLOCK (cfg, is_ref_bb);
3587         NEW_BBLOCK (cfg, is_nullable_bb);
3588         NEW_BBLOCK (cfg, end_bb);
3589         is_ref = mini_emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_CLASS_BOX_TYPE);
3590         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, is_ref->dreg, MONO_GSHAREDVT_BOX_TYPE_REF);
3591         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, is_ref_bb);
3592
3593         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, is_ref->dreg, MONO_GSHAREDVT_BOX_TYPE_NULLABLE);
3594         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, is_nullable_bb);
3595
3596         /* This will contain either the address of the unboxed vtype, or an address of the temporary where the ref is stored */
3597         addr_reg = alloc_dreg (cfg, STACK_MP);
3598
3599         /* Non-ref case */
3600         /* UNBOX */
3601         NEW_BIALU_IMM (cfg, addr, OP_ADD_IMM, addr_reg, obj->dreg, sizeof (MonoObject));
3602         MONO_ADD_INS (cfg->cbb, addr);
3603
3604         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
3605
3606         /* Ref case */
3607         MONO_START_BB (cfg, is_ref_bb);
3608
3609         /* Save the ref to a temporary */
3610         dreg = alloc_ireg (cfg);
3611         EMIT_NEW_VARLOADA_VREG (cfg, addr, dreg, &klass->byval_arg);
3612         addr->dreg = addr_reg;
3613         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, addr->dreg, 0, obj->dreg);
3614         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
3615
3616         /* Nullable case */
3617         MONO_START_BB (cfg, is_nullable_bb);
3618
3619         {
3620                 MonoInst *addr = mini_emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_NULLABLE_CLASS_UNBOX);
3621                 MonoInst *unbox_call;
3622                 MonoMethodSignature *unbox_sig;
3623
3624                 unbox_sig = (MonoMethodSignature *)mono_mempool_alloc0 (cfg->mempool, MONO_SIZEOF_METHOD_SIGNATURE + (1 * sizeof (MonoType *)));
3625                 unbox_sig->ret = &klass->byval_arg;
3626                 unbox_sig->param_count = 1;
3627                 unbox_sig->params [0] = &mono_defaults.object_class->byval_arg;
3628
3629                 if (cfg->llvm_only)
3630                         unbox_call = emit_llvmonly_calli (cfg, unbox_sig, &obj, addr);
3631                 else
3632                         unbox_call = mini_emit_calli (cfg, unbox_sig, &obj, addr, NULL, NULL);
3633
3634                 EMIT_NEW_VARLOADA_VREG (cfg, addr, unbox_call->dreg, &klass->byval_arg);
3635                 addr->dreg = addr_reg;
3636         }
3637
3638         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
3639
3640         /* End */
3641         MONO_START_BB (cfg, end_bb);
3642
3643         /* LDOBJ */
3644         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr_reg, 0);
3645
3646         return ins;
3647 }
3648
3649 /*
3650  * Returns NULL and set the cfg exception on error.
3651  */
3652 static MonoInst*
3653 handle_alloc (MonoCompile *cfg, MonoClass *klass, gboolean for_box, int context_used)
3654 {
3655         MonoInst *iargs [2];
3656         void *alloc_ftn;
3657
3658         if (context_used) {
3659                 MonoInst *data;
3660                 MonoRgctxInfoType rgctx_info;
3661                 MonoInst *iargs [2];
3662                 gboolean known_instance_size = !mini_is_gsharedvt_klass (klass);
3663
3664                 MonoMethod *managed_alloc = mono_gc_get_managed_allocator (klass, for_box, known_instance_size);
3665
3666                 if (cfg->opt & MONO_OPT_SHARED)
3667                         rgctx_info = MONO_RGCTX_INFO_KLASS;
3668                 else
3669                         rgctx_info = MONO_RGCTX_INFO_VTABLE;
3670                 data = mini_emit_get_rgctx_klass (cfg, context_used, klass, rgctx_info);
3671
3672                 if (cfg->opt & MONO_OPT_SHARED) {
3673                         EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
3674                         iargs [1] = data;
3675                         alloc_ftn = ves_icall_object_new;
3676                 } else {
3677                         iargs [0] = data;
3678                         alloc_ftn = ves_icall_object_new_specific;
3679                 }
3680
3681                 if (managed_alloc && !(cfg->opt & MONO_OPT_SHARED)) {
3682                         if (known_instance_size) {
3683                                 int size = mono_class_instance_size (klass);
3684                                 if (size < sizeof (MonoObject))
3685                                         g_error ("Invalid size %d for class %s", size, mono_type_get_full_name (klass));
3686
3687                                 EMIT_NEW_ICONST (cfg, iargs [1], size);
3688                         }
3689                         return mono_emit_method_call (cfg, managed_alloc, iargs, NULL);
3690                 }
3691
3692                 return mono_emit_jit_icall (cfg, alloc_ftn, iargs);
3693         }
3694
3695         if (cfg->opt & MONO_OPT_SHARED) {
3696                 EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
3697                 EMIT_NEW_CLASSCONST (cfg, iargs [1], klass);
3698
3699                 alloc_ftn = ves_icall_object_new;
3700         } else if (cfg->compile_aot && cfg->cbb->out_of_line && klass->type_token && klass->image == mono_defaults.corlib && !mono_class_is_ginst (klass)) {
3701                 /* This happens often in argument checking code, eg. throw new FooException... */
3702                 /* Avoid relocations and save some space by calling a helper function specialized to mscorlib */
3703                 EMIT_NEW_ICONST (cfg, iargs [0], mono_metadata_token_index (klass->type_token));
3704                 alloc_ftn = mono_helper_newobj_mscorlib;
3705         } else {
3706                 MonoVTable *vtable = mono_class_vtable (cfg->domain, klass);
3707                 MonoMethod *managed_alloc = NULL;
3708
3709                 if (!vtable) {
3710                         mono_cfg_set_exception (cfg, MONO_EXCEPTION_TYPE_LOAD);
3711                         cfg->exception_ptr = klass;
3712                         return NULL;
3713                 }
3714
3715                 managed_alloc = mono_gc_get_managed_allocator (klass, for_box, TRUE);
3716
3717                 if (managed_alloc) {
3718                         int size = mono_class_instance_size (klass);
3719                         if (size < sizeof (MonoObject))
3720                                 g_error ("Invalid size %d for class %s", size, mono_type_get_full_name (klass));
3721
3722                         EMIT_NEW_VTABLECONST (cfg, iargs [0], vtable);
3723                         EMIT_NEW_ICONST (cfg, iargs [1], size);
3724                         return mono_emit_method_call (cfg, managed_alloc, iargs, NULL);
3725                 }
3726                 alloc_ftn = ves_icall_object_new_specific;
3727                 EMIT_NEW_VTABLECONST (cfg, iargs [0], vtable);
3728         }
3729
3730         return mono_emit_jit_icall (cfg, alloc_ftn, iargs);
3731 }
3732         
3733 /*
3734  * Returns NULL and set the cfg exception on error.
3735  */     
3736 static MonoInst*
3737 handle_box (MonoCompile *cfg, MonoInst *val, MonoClass *klass, int context_used)
3738 {
3739         MonoInst *alloc, *ins;
3740
3741         if (mono_class_is_nullable (klass)) {
3742                 MonoMethod* method = mono_class_get_method_from_name (klass, "Box", 1);
3743
3744                 if (context_used) {
3745                         if (cfg->llvm_only && cfg->gsharedvt) {
3746                                 MonoInst *addr = emit_get_rgctx_method (cfg, context_used, method,
3747                                                                                                                 MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
3748                                 return emit_llvmonly_calli (cfg, mono_method_signature (method), &val, addr);
3749                         } else {
3750                                 /* FIXME: What if the class is shared?  We might not
3751                                    have to get the method address from the RGCTX. */
3752                                 MonoInst *addr = emit_get_rgctx_method (cfg, context_used, method,
3753                                                                                                                 MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
3754                                 MonoInst *rgctx = emit_get_rgctx (cfg, cfg->method, context_used);
3755
3756                                 return mini_emit_calli (cfg, mono_method_signature (method), &val, addr, NULL, rgctx);
3757                         }
3758                 } else {
3759                         gboolean pass_vtable, pass_mrgctx;
3760                         MonoInst *rgctx_arg = NULL;
3761
3762                         check_method_sharing (cfg, method, &pass_vtable, &pass_mrgctx);
3763                         g_assert (!pass_mrgctx);
3764
3765                         if (pass_vtable) {
3766                                 MonoVTable *vtable = mono_class_vtable (cfg->domain, method->klass);
3767
3768                                 g_assert (vtable);
3769                                 EMIT_NEW_VTABLECONST (cfg, rgctx_arg, vtable);
3770                         }
3771
3772                         return mono_emit_method_call_full (cfg, method, NULL, FALSE, &val, NULL, NULL, rgctx_arg);
3773                 }
3774         }
3775
3776         if (mini_is_gsharedvt_klass (klass)) {
3777                 MonoBasicBlock *is_ref_bb, *is_nullable_bb, *end_bb;
3778                 MonoInst *res, *is_ref, *src_var, *addr;
3779                 int dreg;
3780
3781                 dreg = alloc_ireg (cfg);
3782
3783                 NEW_BBLOCK (cfg, is_ref_bb);
3784                 NEW_BBLOCK (cfg, is_nullable_bb);
3785                 NEW_BBLOCK (cfg, end_bb);
3786                 is_ref = mini_emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_CLASS_BOX_TYPE);
3787                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, is_ref->dreg, MONO_GSHAREDVT_BOX_TYPE_REF);
3788                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, is_ref_bb);
3789
3790                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, is_ref->dreg, MONO_GSHAREDVT_BOX_TYPE_NULLABLE);
3791                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, is_nullable_bb);
3792
3793                 /* Non-ref case */
3794                 alloc = handle_alloc (cfg, klass, TRUE, context_used);
3795                 if (!alloc)
3796                         return NULL;
3797                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, alloc->dreg, sizeof (MonoObject), val->dreg);
3798                 ins->opcode = OP_STOREV_MEMBASE;
3799
3800                 EMIT_NEW_UNALU (cfg, res, OP_MOVE, dreg, alloc->dreg);
3801                 res->type = STACK_OBJ;
3802                 res->klass = klass;
3803                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
3804                 
3805                 /* Ref case */
3806                 MONO_START_BB (cfg, is_ref_bb);
3807
3808                 /* val is a vtype, so has to load the value manually */
3809                 src_var = get_vreg_to_inst (cfg, val->dreg);
3810                 if (!src_var)
3811                         src_var = mono_compile_create_var_for_vreg (cfg, &klass->byval_arg, OP_LOCAL, val->dreg);
3812                 EMIT_NEW_VARLOADA (cfg, addr, src_var, src_var->inst_vtype);
3813                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, dreg, addr->dreg, 0);
3814                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
3815
3816                 /* Nullable case */
3817                 MONO_START_BB (cfg, is_nullable_bb);
3818
3819                 {
3820                         MonoInst *addr = mini_emit_get_gsharedvt_info_klass (cfg, klass,
3821                                                                                                         MONO_RGCTX_INFO_NULLABLE_CLASS_BOX);
3822                         MonoInst *box_call;
3823                         MonoMethodSignature *box_sig;
3824
3825                         /*
3826                          * klass is Nullable<T>, need to call Nullable<T>.Box () using a gsharedvt signature, but we cannot
3827                          * construct that method at JIT time, so have to do things by hand.
3828                          */
3829                         box_sig = (MonoMethodSignature *)mono_mempool_alloc0 (cfg->mempool, MONO_SIZEOF_METHOD_SIGNATURE + (1 * sizeof (MonoType *)));
3830                         box_sig->ret = &mono_defaults.object_class->byval_arg;
3831                         box_sig->param_count = 1;
3832                         box_sig->params [0] = &klass->byval_arg;
3833
3834                         if (cfg->llvm_only)
3835                                 box_call = emit_llvmonly_calli (cfg, box_sig, &val, addr);
3836                         else
3837                                 box_call = mini_emit_calli (cfg, box_sig, &val, addr, NULL, NULL);
3838                         EMIT_NEW_UNALU (cfg, res, OP_MOVE, dreg, box_call->dreg);
3839                         res->type = STACK_OBJ;
3840                         res->klass = klass;
3841                 }
3842
3843                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
3844
3845                 MONO_START_BB (cfg, end_bb);
3846
3847                 return res;
3848         } else {
3849                 alloc = handle_alloc (cfg, klass, TRUE, context_used);
3850                 if (!alloc)
3851                         return NULL;
3852
3853                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, alloc->dreg, sizeof (MonoObject), val->dreg);
3854                 return alloc;
3855         }
3856 }
3857
3858 static GHashTable* direct_icall_type_hash;
3859
3860 static gboolean
3861 icall_is_direct_callable (MonoCompile *cfg, MonoMethod *cmethod)
3862 {
3863         /* LLVM on amd64 can't handle calls to non-32 bit addresses */
3864         if (!direct_icalls_enabled (cfg))
3865                 return FALSE;
3866
3867         /*
3868          * An icall is directly callable if it doesn't directly or indirectly call mono_raise_exception ().
3869          * Whitelist a few icalls for now.
3870          */
3871         if (!direct_icall_type_hash) {
3872                 GHashTable *h = g_hash_table_new (g_str_hash, g_str_equal);
3873
3874                 g_hash_table_insert (h, (char*)"Decimal", GUINT_TO_POINTER (1));
3875                 g_hash_table_insert (h, (char*)"Number", GUINT_TO_POINTER (1));
3876                 g_hash_table_insert (h, (char*)"Buffer", GUINT_TO_POINTER (1));
3877                 g_hash_table_insert (h, (char*)"Monitor", GUINT_TO_POINTER (1));
3878                 mono_memory_barrier ();
3879                 direct_icall_type_hash = h;
3880         }
3881
3882         if (cmethod->klass == mono_defaults.math_class)
3883                 return TRUE;
3884         /* No locking needed */
3885         if (cmethod->klass->image == mono_defaults.corlib && g_hash_table_lookup (direct_icall_type_hash, cmethod->klass->name))
3886                 return TRUE;
3887         return FALSE;
3888 }
3889
3890 static gboolean
3891 method_needs_stack_walk (MonoCompile *cfg, MonoMethod *cmethod)
3892 {
3893         if (cmethod->klass == mono_defaults.systemtype_class) {
3894                 if (!strcmp (cmethod->name, "GetType"))
3895                         return TRUE;
3896         }
3897         return FALSE;
3898 }
3899
3900 static G_GNUC_UNUSED MonoInst*
3901 handle_enum_has_flag (MonoCompile *cfg, MonoClass *klass, MonoInst *enum_this, MonoInst *enum_flag)
3902 {
3903         MonoType *enum_type = mono_type_get_underlying_type (&klass->byval_arg);
3904         guint32 load_opc = mono_type_to_load_membase (cfg, enum_type);
3905         gboolean is_i4;
3906
3907         switch (enum_type->type) {
3908         case MONO_TYPE_I8:
3909         case MONO_TYPE_U8:
3910 #if SIZEOF_REGISTER == 8
3911         case MONO_TYPE_I:
3912         case MONO_TYPE_U:
3913 #endif
3914                 is_i4 = FALSE;
3915                 break;
3916         default:
3917                 is_i4 = TRUE;
3918                 break;
3919         }
3920
3921         {
3922                 MonoInst *load, *and_, *cmp, *ceq;
3923                 int enum_reg = is_i4 ? alloc_ireg (cfg) : alloc_lreg (cfg);
3924                 int and_reg = is_i4 ? alloc_ireg (cfg) : alloc_lreg (cfg);
3925                 int dest_reg = alloc_ireg (cfg);
3926
3927                 EMIT_NEW_LOAD_MEMBASE (cfg, load, load_opc, enum_reg, enum_this->dreg, 0);
3928                 EMIT_NEW_BIALU (cfg, and_, is_i4 ? OP_IAND : OP_LAND, and_reg, enum_reg, enum_flag->dreg);
3929                 EMIT_NEW_BIALU (cfg, cmp, is_i4 ? OP_ICOMPARE : OP_LCOMPARE, -1, and_reg, enum_flag->dreg);
3930                 EMIT_NEW_UNALU (cfg, ceq, is_i4 ? OP_ICEQ : OP_LCEQ, dest_reg, -1);
3931
3932                 ceq->type = STACK_I4;
3933
3934                 if (!is_i4) {
3935                         load = mono_decompose_opcode (cfg, load);
3936                         and_ = mono_decompose_opcode (cfg, and_);
3937                         cmp = mono_decompose_opcode (cfg, cmp);
3938                         ceq = mono_decompose_opcode (cfg, ceq);
3939                 }
3940
3941                 return ceq;
3942         }
3943 }
3944
3945 /*
3946  * Returns NULL and set the cfg exception on error.
3947  */
3948 static G_GNUC_UNUSED MonoInst*
3949 handle_delegate_ctor (MonoCompile *cfg, MonoClass *klass, MonoInst *target, MonoMethod *method, int context_used, gboolean virtual_)
3950 {
3951         MonoInst *ptr;
3952         int dreg;
3953         gpointer trampoline;
3954         MonoInst *obj, *method_ins, *tramp_ins;
3955         MonoDomain *domain;
3956         guint8 **code_slot;
3957
3958         if (virtual_ && !cfg->llvm_only) {
3959                 MonoMethod *invoke = mono_get_delegate_invoke (klass);
3960                 g_assert (invoke);
3961
3962                 if (!mono_get_delegate_virtual_invoke_impl (mono_method_signature (invoke), context_used ? NULL : method))
3963                         return NULL;
3964         }
3965
3966         obj = handle_alloc (cfg, klass, FALSE, mono_class_check_context_used (klass));
3967         if (!obj)
3968                 return NULL;
3969
3970         /* Inline the contents of mono_delegate_ctor */
3971
3972         /* Set target field */
3973         /* Optimize away setting of NULL target */
3974         if (!MONO_INS_IS_PCONST_NULL (target)) {
3975                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, target->dreg, 0);
3976                 MONO_EMIT_NEW_COND_EXC (cfg, EQ, "NullReferenceException");
3977                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, target), target->dreg);
3978                 if (cfg->gen_write_barriers) {
3979                         dreg = alloc_preg (cfg);
3980                         EMIT_NEW_BIALU_IMM (cfg, ptr, OP_PADD_IMM, dreg, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, target));
3981                         mini_emit_write_barrier (cfg, ptr, target);
3982                 }
3983         }
3984
3985         /* Set method field */
3986         method_ins = emit_get_rgctx_method (cfg, context_used, method, MONO_RGCTX_INFO_METHOD);
3987         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, method), method_ins->dreg);
3988
3989         /* 
3990          * To avoid looking up the compiled code belonging to the target method
3991          * in mono_delegate_trampoline (), we allocate a per-domain memory slot to
3992          * store it, and we fill it after the method has been compiled.
3993          */
3994         if (!method->dynamic && !(cfg->opt & MONO_OPT_SHARED)) {
3995                 MonoInst *code_slot_ins;
3996
3997                 if (context_used) {
3998                         code_slot_ins = emit_get_rgctx_method (cfg, context_used, method, MONO_RGCTX_INFO_METHOD_DELEGATE_CODE);
3999                 } else {
4000                         domain = mono_domain_get ();
4001                         mono_domain_lock (domain);
4002                         if (!domain_jit_info (domain)->method_code_hash)
4003                                 domain_jit_info (domain)->method_code_hash = g_hash_table_new (NULL, NULL);
4004                         code_slot = (guint8 **)g_hash_table_lookup (domain_jit_info (domain)->method_code_hash, method);
4005                         if (!code_slot) {
4006                                 code_slot = (guint8 **)mono_domain_alloc0 (domain, sizeof (gpointer));
4007                                 g_hash_table_insert (domain_jit_info (domain)->method_code_hash, method, code_slot);
4008                         }
4009                         mono_domain_unlock (domain);
4010
4011                         code_slot_ins = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_METHOD_CODE_SLOT, method);
4012                 }
4013                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, method_code), code_slot_ins->dreg);                
4014         }
4015
4016         if (cfg->llvm_only) {
4017                 MonoInst *args [16];
4018
4019                 if (virtual_) {
4020                         args [0] = obj;
4021                         args [1] = target;
4022                         args [2] = emit_get_rgctx_method (cfg, context_used, method, MONO_RGCTX_INFO_METHOD);
4023                         mono_emit_jit_icall (cfg, mono_llvmonly_init_delegate_virtual, args);
4024                 } else {
4025                         args [0] = obj;
4026                         mono_emit_jit_icall (cfg, mono_llvmonly_init_delegate, args);
4027                 }
4028
4029                 return obj;
4030         }
4031
4032         if (cfg->compile_aot) {
4033                 MonoDelegateClassMethodPair *del_tramp;
4034
4035                 del_tramp = (MonoDelegateClassMethodPair *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoDelegateClassMethodPair));
4036                 del_tramp->klass = klass;
4037                 del_tramp->method = context_used ? NULL : method;
4038                 del_tramp->is_virtual = virtual_;
4039                 EMIT_NEW_AOTCONST (cfg, tramp_ins, MONO_PATCH_INFO_DELEGATE_TRAMPOLINE, del_tramp);
4040         } else {
4041                 if (virtual_)
4042                         trampoline = mono_create_delegate_virtual_trampoline (cfg->domain, klass, context_used ? NULL : method);
4043                 else
4044                         trampoline = mono_create_delegate_trampoline_info (cfg->domain, klass, context_used ? NULL : method);
4045                 EMIT_NEW_PCONST (cfg, tramp_ins, trampoline);
4046         }
4047
4048         /* Set invoke_impl field */
4049         if (virtual_) {
4050                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, invoke_impl), tramp_ins->dreg);
4051         } else {
4052                 dreg = alloc_preg (cfg);
4053                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, dreg, tramp_ins->dreg, MONO_STRUCT_OFFSET (MonoDelegateTrampInfo, invoke_impl));
4054                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, invoke_impl), dreg);
4055
4056                 dreg = alloc_preg (cfg);
4057                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, dreg, tramp_ins->dreg, MONO_STRUCT_OFFSET (MonoDelegateTrampInfo, method_ptr));
4058                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, method_ptr), dreg);
4059         }
4060
4061         dreg = alloc_preg (cfg);
4062         MONO_EMIT_NEW_ICONST (cfg, dreg, virtual_ ? 1 : 0);
4063         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI1_MEMBASE_REG, obj->dreg, MONO_STRUCT_OFFSET (MonoDelegate, method_is_virtual), dreg);
4064
4065         /* All the checks which are in mono_delegate_ctor () are done by the delegate trampoline */
4066
4067         return obj;
4068 }
4069
4070 static MonoInst*
4071 handle_array_new (MonoCompile *cfg, int rank, MonoInst **sp, unsigned char *ip)
4072 {
4073         MonoJitICallInfo *info;
4074
4075         /* Need to register the icall so it gets an icall wrapper */
4076         info = mono_get_array_new_va_icall (rank);
4077
4078         cfg->flags |= MONO_CFG_HAS_VARARGS;
4079
4080         /* mono_array_new_va () needs a vararg calling convention */
4081         cfg->exception_message = g_strdup ("array-new");
4082         cfg->disable_llvm = TRUE;
4083
4084         /* FIXME: This uses info->sig, but it should use the signature of the wrapper */
4085         return mono_emit_native_call (cfg, mono_icall_get_wrapper (info), info->sig, sp);
4086 }
4087
4088 /*
4089  * handle_constrained_gsharedvt_call:
4090  *
4091  *   Handle constrained calls where the receiver is a gsharedvt type.
4092  * Return the instruction representing the call. Set the cfg exception on failure.
4093  */
4094 static MonoInst*
4095 handle_constrained_gsharedvt_call (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **sp, MonoClass *constrained_class,
4096                                                                    gboolean *ref_emit_widen)
4097 {
4098         MonoInst *ins = NULL;
4099         gboolean emit_widen = *ref_emit_widen;
4100
4101         /*
4102          * Constrained calls need to behave differently at runtime dependending on whenever the receiver is instantiated as ref type or as a vtype.
4103          * 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
4104          * pack the arguments into an array, and do the rest of the work in in an icall.
4105          */
4106         if (((cmethod->klass == mono_defaults.object_class) || mono_class_is_interface (cmethod->klass) || (!cmethod->klass->valuetype && cmethod->klass->image != mono_defaults.corlib)) &&
4107                 (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)) &&
4108                 (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]))))) {
4109                 MonoInst *args [16];
4110
4111                 /*
4112                  * This case handles calls to
4113                  * - object:ToString()/Equals()/GetHashCode(),
4114                  * - System.IComparable<T>:CompareTo()
4115                  * - System.IEquatable<T>:Equals ()
4116                  * plus some simple interface calls enough to support AsyncTaskMethodBuilder.
4117                  */
4118
4119                 args [0] = sp [0];
4120                 if (mono_method_check_context_used (cmethod))
4121                         args [1] = emit_get_rgctx_method (cfg, mono_method_check_context_used (cmethod), cmethod, MONO_RGCTX_INFO_METHOD);
4122                 else
4123                         EMIT_NEW_METHODCONST (cfg, args [1], cmethod);
4124                 args [2] = mini_emit_get_rgctx_klass (cfg, mono_class_check_context_used (constrained_class), constrained_class, MONO_RGCTX_INFO_KLASS);
4125
4126                 /* !fsig->hasthis is for the wrapper for the Object.GetType () icall */
4127                 if (fsig->hasthis && fsig->param_count) {
4128                         /* Pass the arguments using a localloc-ed array using the format expected by runtime_invoke () */
4129                         MONO_INST_NEW (cfg, ins, OP_LOCALLOC_IMM);
4130                         ins->dreg = alloc_preg (cfg);
4131                         ins->inst_imm = fsig->param_count * sizeof (mgreg_t);
4132                         MONO_ADD_INS (cfg->cbb, ins);
4133                         args [4] = ins;
4134
4135                         if (mini_is_gsharedvt_type (fsig->params [0])) {
4136                                 int addr_reg, deref_arg_reg;
4137
4138                                 ins = mini_emit_get_gsharedvt_info_klass (cfg, mono_class_from_mono_type (fsig->params [0]), MONO_RGCTX_INFO_CLASS_BOX_TYPE);
4139                                 deref_arg_reg = alloc_preg (cfg);
4140                                 /* deref_arg = BOX_TYPE != MONO_GSHAREDVT_BOX_TYPE_VTYPE */
4141                                 EMIT_NEW_BIALU_IMM (cfg, args [3], OP_ISUB_IMM, deref_arg_reg, ins->dreg, 1);
4142
4143                                 EMIT_NEW_VARLOADA_VREG (cfg, ins, sp [1]->dreg, fsig->params [0]);
4144                                 addr_reg = ins->dreg;
4145                                 EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STORE_MEMBASE_REG, args [4]->dreg, 0, addr_reg);
4146                         } else {
4147                                 EMIT_NEW_ICONST (cfg, args [3], 0);
4148                                 EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STORE_MEMBASE_REG, args [4]->dreg, 0, sp [1]->dreg);
4149                         }
4150                 } else {
4151                         EMIT_NEW_ICONST (cfg, args [3], 0);
4152                         EMIT_NEW_ICONST (cfg, args [4], 0);
4153                 }
4154                 ins = mono_emit_jit_icall (cfg, mono_gsharedvt_constrained_call, args);
4155                 emit_widen = FALSE;
4156
4157                 if (mini_is_gsharedvt_type (fsig->ret)) {
4158                         ins = handle_unbox_gsharedvt (cfg, mono_class_from_mono_type (fsig->ret), ins);
4159                 } else if (MONO_TYPE_IS_PRIMITIVE (fsig->ret) || MONO_TYPE_ISSTRUCT (fsig->ret) || mono_class_is_enum (mono_class_from_mono_type (fsig->ret))) {
4160                         MonoInst *add;
4161
4162                         /* Unbox */
4163                         NEW_BIALU_IMM (cfg, add, OP_ADD_IMM, alloc_dreg (cfg, STACK_MP), ins->dreg, sizeof (MonoObject));
4164                         MONO_ADD_INS (cfg->cbb, add);
4165                         /* Load value */
4166                         NEW_LOAD_MEMBASE_TYPE (cfg, ins, fsig->ret, add->dreg, 0);
4167                         MONO_ADD_INS (cfg->cbb, ins);
4168                         /* ins represents the call result */
4169                 }
4170         } else {
4171                 GSHAREDVT_FAILURE (CEE_CALLVIRT);
4172         }
4173
4174         *ref_emit_widen = emit_widen;
4175
4176         return ins;
4177
4178  exception_exit:
4179         return NULL;
4180 }
4181
4182 static void
4183 mono_emit_load_got_addr (MonoCompile *cfg)
4184 {
4185         MonoInst *getaddr, *dummy_use;
4186
4187         if (!cfg->got_var || cfg->got_var_allocated)
4188                 return;
4189
4190         MONO_INST_NEW (cfg, getaddr, OP_LOAD_GOTADDR);
4191         getaddr->cil_code = cfg->header->code;
4192         getaddr->dreg = cfg->got_var->dreg;
4193
4194         /* Add it to the start of the first bblock */
4195         if (cfg->bb_entry->code) {
4196                 getaddr->next = cfg->bb_entry->code;
4197                 cfg->bb_entry->code = getaddr;
4198         }
4199         else
4200                 MONO_ADD_INS (cfg->bb_entry, getaddr);
4201
4202         cfg->got_var_allocated = TRUE;
4203
4204         /* 
4205          * Add a dummy use to keep the got_var alive, since real uses might
4206          * only be generated by the back ends.
4207          * Add it to end_bblock, so the variable's lifetime covers the whole
4208          * method.
4209          * It would be better to make the usage of the got var explicit in all
4210          * cases when the backend needs it (i.e. calls, throw etc.), so this
4211          * wouldn't be needed.
4212          */
4213         NEW_DUMMY_USE (cfg, dummy_use, cfg->got_var);
4214         MONO_ADD_INS (cfg->bb_exit, dummy_use);
4215 }
4216
4217 static int inline_limit;
4218 static gboolean inline_limit_inited;
4219
4220 static gboolean
4221 mono_method_check_inlining (MonoCompile *cfg, MonoMethod *method)
4222 {
4223         MonoMethodHeaderSummary header;
4224         MonoVTable *vtable;
4225 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
4226         MonoMethodSignature *sig = mono_method_signature (method);
4227         int i;
4228 #endif
4229
4230         if (cfg->disable_inline)
4231                 return FALSE;
4232         if (cfg->gsharedvt)
4233                 return FALSE;
4234
4235         if (cfg->inline_depth > 10)
4236                 return FALSE;
4237
4238         if (!mono_method_get_header_summary (method, &header))
4239                 return FALSE;
4240
4241         /*runtime, icall and pinvoke are checked by summary call*/
4242         if ((method->iflags & METHOD_IMPL_ATTRIBUTE_NOINLINING) ||
4243             (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) ||
4244             (mono_class_is_marshalbyref (method->klass)) ||
4245             header.has_clauses)
4246                 return FALSE;
4247
4248         /* also consider num_locals? */
4249         /* Do the size check early to avoid creating vtables */
4250         if (!inline_limit_inited) {
4251                 char *inlinelimit;
4252                 if ((inlinelimit = g_getenv ("MONO_INLINELIMIT"))) {
4253                         inline_limit = atoi (inlinelimit);
4254                         g_free (inlinelimit);
4255                 } else
4256                         inline_limit = INLINE_LENGTH_LIMIT;
4257                 inline_limit_inited = TRUE;
4258         }
4259         if (header.code_size >= inline_limit && !(method->iflags & METHOD_IMPL_ATTRIBUTE_AGGRESSIVE_INLINING))
4260                 return FALSE;
4261
4262         /*
4263          * if we can initialize the class of the method right away, we do,
4264          * otherwise we don't allow inlining if the class needs initialization,
4265          * since it would mean inserting a call to mono_runtime_class_init()
4266          * inside the inlined code
4267          */
4268         if (cfg->gshared && method->klass->has_cctor && mini_class_check_context_used (cfg, method->klass))
4269                 return FALSE;
4270
4271         if (!(cfg->opt & MONO_OPT_SHARED)) {
4272                 /* The AggressiveInlining hint is a good excuse to force that cctor to run. */
4273                 if (method->iflags & METHOD_IMPL_ATTRIBUTE_AGGRESSIVE_INLINING) {
4274                         if (method->klass->has_cctor) {
4275                                 vtable = mono_class_vtable (cfg->domain, method->klass);
4276                                 if (!vtable)
4277                                         return FALSE;
4278                                 if (!cfg->compile_aot) {
4279                                         MonoError error;
4280                                         if (!mono_runtime_class_init_full (vtable, &error)) {
4281                                                 mono_error_cleanup (&error);
4282                                                 return FALSE;
4283                                         }
4284                                 }
4285                         }
4286                 } else if (mono_class_is_before_field_init (method->klass)) {
4287                         if (cfg->run_cctors && method->klass->has_cctor) {
4288                                 /*FIXME it would easier and lazier to just use mono_class_try_get_vtable */
4289                                 if (!method->klass->runtime_info)
4290                                         /* No vtable created yet */
4291                                         return FALSE;
4292                                 vtable = mono_class_vtable (cfg->domain, method->klass);
4293                                 if (!vtable)
4294                                         return FALSE;
4295                                 /* This makes so that inline cannot trigger */
4296                                 /* .cctors: too many apps depend on them */
4297                                 /* running with a specific order... */
4298                                 if (! vtable->initialized)
4299                                         return FALSE;
4300                                 MonoError error;
4301                                 if (!mono_runtime_class_init_full (vtable, &error)) {
4302                                         mono_error_cleanup (&error);
4303                                         return FALSE;
4304                                 }
4305                         }
4306                 } else if (mono_class_needs_cctor_run (method->klass, NULL)) {
4307                         if (!method->klass->runtime_info)
4308                                 /* No vtable created yet */
4309                                 return FALSE;
4310                         vtable = mono_class_vtable (cfg->domain, method->klass);
4311                         if (!vtable)
4312                                 return FALSE;
4313                         if (!vtable->initialized)
4314                                 return FALSE;
4315                 }
4316         } else {
4317                 /* 
4318                  * If we're compiling for shared code
4319                  * the cctor will need to be run at aot method load time, for example,
4320                  * or at the end of the compilation of the inlining method.
4321                  */
4322                 if (mono_class_needs_cctor_run (method->klass, NULL) && !mono_class_is_before_field_init (method->klass))
4323                         return FALSE;
4324         }
4325
4326 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
4327         if (mono_arch_is_soft_float ()) {
4328                 /* FIXME: */
4329                 if (sig->ret && sig->ret->type == MONO_TYPE_R4)
4330                         return FALSE;
4331                 for (i = 0; i < sig->param_count; ++i)
4332                         if (!sig->params [i]->byref && sig->params [i]->type == MONO_TYPE_R4)
4333                                 return FALSE;
4334         }
4335 #endif
4336
4337         if (g_list_find (cfg->dont_inline, method))
4338                 return FALSE;
4339
4340         if (mono_profiler_get_call_instrumentation_flags (method))
4341                 return FALSE;
4342
4343         return TRUE;
4344 }
4345
4346 static gboolean
4347 mini_field_access_needs_cctor_run (MonoCompile *cfg, MonoMethod *method, MonoClass *klass, MonoVTable *vtable)
4348 {
4349         if (!cfg->compile_aot) {
4350                 g_assert (vtable);
4351                 if (vtable->initialized)
4352                         return FALSE;
4353         }
4354
4355         if (mono_class_is_before_field_init (klass)) {
4356                 if (cfg->method == method)
4357                         return FALSE;
4358         }
4359
4360         if (!mono_class_needs_cctor_run (klass, method))
4361                 return FALSE;
4362
4363         if (! (method->flags & METHOD_ATTRIBUTE_STATIC) && (klass == method->klass))
4364                 /* The initialization is already done before the method is called */
4365                 return FALSE;
4366
4367         return TRUE;
4368 }
4369
4370 MonoInst*
4371 mini_emit_ldelema_1_ins (MonoCompile *cfg, MonoClass *klass, MonoInst *arr, MonoInst *index, gboolean bcheck)
4372 {
4373         MonoInst *ins;
4374         guint32 size;
4375         int mult_reg, add_reg, array_reg, index_reg, index2_reg;
4376         int context_used;
4377
4378         if (mini_is_gsharedvt_variable_klass (klass)) {
4379                 size = -1;
4380         } else {
4381                 mono_class_init (klass);
4382                 size = mono_class_array_element_size (klass);
4383         }
4384
4385         mult_reg = alloc_preg (cfg);
4386         array_reg = arr->dreg;
4387         index_reg = index->dreg;
4388
4389 #if SIZEOF_REGISTER == 8
4390         /* The array reg is 64 bits but the index reg is only 32 */
4391         if (COMPILE_LLVM (cfg)) {
4392                 /*
4393                  * abcrem can't handle the OP_SEXT_I4, so add this after abcrem,
4394                  * during OP_BOUNDS_CHECK decomposition, and in the implementation
4395                  * of OP_X86_LEA for llvm.
4396                  */
4397                 index2_reg = index_reg;
4398         } else {
4399                 index2_reg = alloc_preg (cfg);
4400                 MONO_EMIT_NEW_UNALU (cfg, OP_SEXT_I4, index2_reg, index_reg);
4401         }
4402 #else
4403         if (index->type == STACK_I8) {
4404                 index2_reg = alloc_preg (cfg);
4405                 MONO_EMIT_NEW_UNALU (cfg, OP_LCONV_TO_I4, index2_reg, index_reg);
4406         } else {
4407                 index2_reg = index_reg;
4408         }
4409 #endif
4410
4411         if (bcheck)
4412                 MONO_EMIT_BOUNDS_CHECK (cfg, array_reg, MonoArray, max_length, index2_reg);
4413
4414 #if defined(TARGET_X86) || defined(TARGET_AMD64)
4415         if (size == 1 || size == 2 || size == 4 || size == 8) {
4416                 static const int fast_log2 [] = { 1, 0, 1, -1, 2, -1, -1, -1, 3 };
4417
4418                 EMIT_NEW_X86_LEA (cfg, ins, array_reg, index2_reg, fast_log2 [size], MONO_STRUCT_OFFSET (MonoArray, vector));
4419                 ins->klass = mono_class_get_element_class (klass);
4420                 ins->type = STACK_MP;
4421
4422                 return ins;
4423         }
4424 #endif          
4425
4426         add_reg = alloc_ireg_mp (cfg);
4427
4428         if (size == -1) {
4429                 MonoInst *rgctx_ins;
4430
4431                 /* gsharedvt */
4432                 g_assert (cfg->gshared);
4433                 context_used = mini_class_check_context_used (cfg, klass);
4434                 g_assert (context_used);
4435                 rgctx_ins = mini_emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_ARRAY_ELEMENT_SIZE);
4436                 MONO_EMIT_NEW_BIALU (cfg, OP_IMUL, mult_reg, index2_reg, rgctx_ins->dreg);
4437         } else {
4438                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_MUL_IMM, mult_reg, index2_reg, size);
4439         }
4440         MONO_EMIT_NEW_BIALU (cfg, OP_PADD, add_reg, array_reg, mult_reg);
4441         NEW_BIALU_IMM (cfg, ins, OP_PADD_IMM, add_reg, add_reg, MONO_STRUCT_OFFSET (MonoArray, vector));
4442         ins->klass = mono_class_get_element_class (klass);
4443         ins->type = STACK_MP;
4444         MONO_ADD_INS (cfg->cbb, ins);
4445
4446         return ins;
4447 }
4448
4449 static MonoInst*
4450 mini_emit_ldelema_2_ins (MonoCompile *cfg, MonoClass *klass, MonoInst *arr, MonoInst *index_ins1, MonoInst *index_ins2)
4451 {
4452         int bounds_reg = alloc_preg (cfg);
4453         int add_reg = alloc_ireg_mp (cfg);
4454         int mult_reg = alloc_preg (cfg);
4455         int mult2_reg = alloc_preg (cfg);
4456         int low1_reg = alloc_preg (cfg);
4457         int low2_reg = alloc_preg (cfg);
4458         int high1_reg = alloc_preg (cfg);
4459         int high2_reg = alloc_preg (cfg);
4460         int realidx1_reg = alloc_preg (cfg);
4461         int realidx2_reg = alloc_preg (cfg);
4462         int sum_reg = alloc_preg (cfg);
4463         int index1, index2, tmpreg;
4464         MonoInst *ins;
4465         guint32 size;
4466
4467         mono_class_init (klass);
4468         size = mono_class_array_element_size (klass);
4469
4470         index1 = index_ins1->dreg;
4471         index2 = index_ins2->dreg;
4472
4473 #if SIZEOF_REGISTER == 8
4474         /* The array reg is 64 bits but the index reg is only 32 */
4475         if (COMPILE_LLVM (cfg)) {
4476                 /* Not needed */
4477         } else {
4478                 tmpreg = alloc_preg (cfg);
4479                 MONO_EMIT_NEW_UNALU (cfg, OP_SEXT_I4, tmpreg, index1);
4480                 index1 = tmpreg;
4481                 tmpreg = alloc_preg (cfg);
4482                 MONO_EMIT_NEW_UNALU (cfg, OP_SEXT_I4, tmpreg, index2);
4483                 index2 = tmpreg;
4484         }
4485 #else
4486         // FIXME: Do we need to do something here for i8 indexes, like in ldelema_1_ins ?
4487         tmpreg = -1;
4488 #endif
4489
4490         /* range checking */
4491         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, bounds_reg, 
4492                                        arr->dreg, MONO_STRUCT_OFFSET (MonoArray, bounds));
4493
4494         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, low1_reg, 
4495                                        bounds_reg, MONO_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
4496         MONO_EMIT_NEW_BIALU (cfg, OP_PSUB, realidx1_reg, index1, low1_reg);
4497         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, high1_reg, 
4498                                        bounds_reg, MONO_STRUCT_OFFSET (MonoArrayBounds, length));
4499         MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, high1_reg, realidx1_reg);
4500         MONO_EMIT_NEW_COND_EXC (cfg, LE_UN, "IndexOutOfRangeException");
4501
4502         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, low2_reg, 
4503                                        bounds_reg, sizeof (MonoArrayBounds) + MONO_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
4504         MONO_EMIT_NEW_BIALU (cfg, OP_PSUB, realidx2_reg, index2, low2_reg);
4505         MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, high2_reg, 
4506                                        bounds_reg, sizeof (MonoArrayBounds) + MONO_STRUCT_OFFSET (MonoArrayBounds, length));
4507         MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, high2_reg, realidx2_reg);
4508         MONO_EMIT_NEW_COND_EXC (cfg, LE_UN, "IndexOutOfRangeException");
4509
4510         MONO_EMIT_NEW_BIALU (cfg, OP_PMUL, mult_reg, high2_reg, realidx1_reg);
4511         MONO_EMIT_NEW_BIALU (cfg, OP_PADD, sum_reg, mult_reg, realidx2_reg);
4512         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PMUL_IMM, mult2_reg, sum_reg, size);
4513         MONO_EMIT_NEW_BIALU (cfg, OP_PADD, add_reg, mult2_reg, arr->dreg);
4514         NEW_BIALU_IMM (cfg, ins, OP_PADD_IMM, add_reg, add_reg, MONO_STRUCT_OFFSET (MonoArray, vector));
4515
4516         ins->type = STACK_MP;
4517         ins->klass = klass;
4518         MONO_ADD_INS (cfg->cbb, ins);
4519
4520         return ins;
4521 }
4522
4523 static MonoInst*
4524 mini_emit_ldelema_ins (MonoCompile *cfg, MonoMethod *cmethod, MonoInst **sp, unsigned char *ip, gboolean is_set)
4525 {
4526         int rank;
4527         MonoInst *addr;
4528         MonoMethod *addr_method;
4529         int element_size;
4530         MonoClass *eclass = cmethod->klass->element_class;
4531
4532         rank = mono_method_signature (cmethod)->param_count - (is_set? 1: 0);
4533
4534         if (rank == 1)
4535                 return mini_emit_ldelema_1_ins (cfg, eclass, sp [0], sp [1], TRUE);
4536
4537         /* emit_ldelema_2 depends on OP_LMUL */
4538         if (!cfg->backend->emulate_mul_div && rank == 2 && (cfg->opt & MONO_OPT_INTRINS) && !mini_is_gsharedvt_variable_klass (eclass)) {
4539                 return mini_emit_ldelema_2_ins (cfg, eclass, sp [0], sp [1], sp [2]);
4540         }
4541
4542         if (mini_is_gsharedvt_variable_klass (eclass))
4543                 element_size = 0;
4544         else
4545                 element_size = mono_class_array_element_size (eclass);
4546         addr_method = mono_marshal_get_array_address (rank, element_size);
4547         addr = mono_emit_method_call (cfg, addr_method, sp, NULL);
4548
4549         return addr;
4550 }
4551
4552 /* optimize the simple GetGenericValueImpl/SetGenericValueImpl generic icalls */
4553 static MonoInst*
4554 emit_array_generic_access (MonoCompile *cfg, MonoMethodSignature *fsig, MonoInst **args, int is_set)
4555 {
4556         MonoInst *addr, *store, *load;
4557         MonoClass *eklass = mono_class_from_mono_type (fsig->params [2]);
4558
4559         /* the bounds check is already done by the callers */
4560         addr = mini_emit_ldelema_1_ins (cfg, eklass, args [0], args [1], FALSE);
4561         if (is_set) {
4562                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, load, &eklass->byval_arg, args [2]->dreg, 0);
4563                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, store, &eklass->byval_arg, addr->dreg, 0, load->dreg);
4564                 if (mini_type_is_reference (&eklass->byval_arg))
4565                         mini_emit_write_barrier (cfg, addr, load);
4566         } else {
4567                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, load, &eklass->byval_arg, addr->dreg, 0);
4568                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, store, &eklass->byval_arg, args [2]->dreg, 0, load->dreg);
4569         }
4570         return store;
4571 }
4572
4573
4574 static gboolean
4575 generic_class_is_reference_type (MonoCompile *cfg, MonoClass *klass)
4576 {
4577         return mini_type_is_reference (&klass->byval_arg);
4578 }
4579
4580 static MonoInst*
4581 emit_array_store (MonoCompile *cfg, MonoClass *klass, MonoInst **sp, gboolean safety_checks)
4582 {
4583         if (safety_checks && generic_class_is_reference_type (cfg, klass) &&
4584                 !(MONO_INS_IS_PCONST_NULL (sp [2]))) {
4585                 MonoClass *obj_array = mono_array_class_get_cached (mono_defaults.object_class, 1);
4586                 MonoMethod *helper = mono_marshal_get_virtual_stelemref (obj_array);
4587                 MonoInst *iargs [3];
4588
4589                 if (!helper->slot)
4590                         mono_class_setup_vtable (obj_array);
4591                 g_assert (helper->slot);
4592
4593                 if (sp [0]->type != STACK_OBJ)
4594                         return NULL;
4595                 if (sp [2]->type != STACK_OBJ)
4596                         return NULL;
4597
4598                 iargs [2] = sp [2];
4599                 iargs [1] = sp [1];
4600                 iargs [0] = sp [0];
4601
4602                 return mono_emit_method_call (cfg, helper, iargs, sp [0]);
4603         } else {
4604                 MonoInst *ins;
4605
4606                 if (mini_is_gsharedvt_variable_klass (klass)) {
4607                         MonoInst *addr;
4608
4609                         // FIXME-VT: OP_ICONST optimization
4610                         addr = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1], TRUE);
4611                         EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr->dreg, 0, sp [2]->dreg);
4612                         ins->opcode = OP_STOREV_MEMBASE;
4613                 } else if (sp [1]->opcode == OP_ICONST) {
4614                         int array_reg = sp [0]->dreg;
4615                         int index_reg = sp [1]->dreg;
4616                         int offset = (mono_class_array_element_size (klass) * sp [1]->inst_c0) + MONO_STRUCT_OFFSET (MonoArray, vector);
4617
4618                         if (SIZEOF_REGISTER == 8 && COMPILE_LLVM (cfg))
4619                                 MONO_EMIT_NEW_UNALU (cfg, OP_ZEXT_I4, index_reg, index_reg);
4620
4621                         if (safety_checks)
4622                                 MONO_EMIT_BOUNDS_CHECK (cfg, array_reg, MonoArray, max_length, index_reg);
4623                         EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, array_reg, offset, sp [2]->dreg);
4624                 } else {
4625                         MonoInst *addr = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1], safety_checks);
4626                         EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr->dreg, 0, sp [2]->dreg);
4627                         if (generic_class_is_reference_type (cfg, klass))
4628                                 mini_emit_write_barrier (cfg, addr, sp [2]);
4629                 }
4630                 return ins;
4631         }
4632 }
4633
4634 static MonoInst*
4635 emit_array_unsafe_access (MonoCompile *cfg, MonoMethodSignature *fsig, MonoInst **args, int is_set)
4636 {
4637         MonoClass *eklass;
4638         
4639         if (is_set)
4640                 eklass = mono_class_from_mono_type (fsig->params [2]);
4641         else
4642                 eklass = mono_class_from_mono_type (fsig->ret);
4643
4644         if (is_set) {
4645                 return emit_array_store (cfg, eklass, args, FALSE);
4646         } else {
4647                 MonoInst *ins, *addr = mini_emit_ldelema_1_ins (cfg, eklass, args [0], args [1], FALSE);
4648                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &eklass->byval_arg, addr->dreg, 0);
4649                 return ins;
4650         }
4651 }
4652
4653 static gboolean
4654 is_unsafe_mov_compatible (MonoCompile *cfg, MonoClass *param_klass, MonoClass *return_klass)
4655 {
4656         uint32_t align;
4657         int param_size, return_size;
4658
4659         param_klass = mono_class_from_mono_type (mini_get_underlying_type (&param_klass->byval_arg));
4660         return_klass = mono_class_from_mono_type (mini_get_underlying_type (&return_klass->byval_arg));
4661
4662         if (cfg->verbose_level > 3)
4663                 printf ("[UNSAFE-MOV-INTRISIC] %s <- %s\n", return_klass->name, param_klass->name);
4664
4665         //Don't allow mixing reference types with value types
4666         if (param_klass->valuetype != return_klass->valuetype) {
4667                 if (cfg->verbose_level > 3)
4668                         printf ("[UNSAFE-MOV-INTRISIC]\tone of the args is a valuetype and the other is not\n");
4669                 return FALSE;
4670         }
4671
4672         if (!param_klass->valuetype) {
4673                 if (cfg->verbose_level > 3)
4674                         printf ("[UNSAFE-MOV-INTRISIC]\targs are reference types\n");
4675                 return TRUE;
4676         }
4677
4678         //That are blitable
4679         if (param_klass->has_references || return_klass->has_references)
4680                 return FALSE;
4681
4682         /* Avoid mixing structs and primitive types/enums, they need to be handled differently in the JIT */
4683         if ((MONO_TYPE_ISSTRUCT (&param_klass->byval_arg) && !MONO_TYPE_ISSTRUCT (&return_klass->byval_arg)) ||
4684                 (!MONO_TYPE_ISSTRUCT (&param_klass->byval_arg) && MONO_TYPE_ISSTRUCT (&return_klass->byval_arg))) {
4685                         if (cfg->verbose_level > 3)
4686                                 printf ("[UNSAFE-MOV-INTRISIC]\tmixing structs and scalars\n");
4687                 return FALSE;
4688         }
4689
4690         if (param_klass->byval_arg.type == MONO_TYPE_R4 || param_klass->byval_arg.type == MONO_TYPE_R8 ||
4691                 return_klass->byval_arg.type == MONO_TYPE_R4 || return_klass->byval_arg.type == MONO_TYPE_R8) {
4692                 if (cfg->verbose_level > 3)
4693                         printf ("[UNSAFE-MOV-INTRISIC]\tfloat or double are not supported\n");
4694                 return FALSE;
4695         }
4696
4697         param_size = mono_class_value_size (param_klass, &align);
4698         return_size = mono_class_value_size (return_klass, &align);
4699
4700         //We can do it if sizes match
4701         if (param_size == return_size) {
4702                 if (cfg->verbose_level > 3)
4703                         printf ("[UNSAFE-MOV-INTRISIC]\tsame size\n");
4704                 return TRUE;
4705         }
4706
4707         //No simple way to handle struct if sizes don't match
4708         if (MONO_TYPE_ISSTRUCT (&param_klass->byval_arg)) {
4709                 if (cfg->verbose_level > 3)
4710                         printf ("[UNSAFE-MOV-INTRISIC]\tsize mismatch and type is a struct\n");
4711                 return FALSE;
4712         }
4713
4714         /*
4715          * Same reg size category.
4716          * A quick note on why we don't require widening here.
4717          * The intrinsic is "R Array.UnsafeMov<S,R> (S s)".
4718          *
4719          * Since the source value comes from a function argument, the JIT will already have
4720          * the value in a VREG and performed any widening needed before (say, when loading from a field).
4721          */
4722         if (param_size <= 4 && return_size <= 4) {
4723                 if (cfg->verbose_level > 3)
4724                         printf ("[UNSAFE-MOV-INTRISIC]\tsize mismatch but both are of the same reg class\n");
4725                 return TRUE;
4726         }
4727
4728         return FALSE;
4729 }
4730
4731 static MonoInst*
4732 emit_array_unsafe_mov (MonoCompile *cfg, MonoMethodSignature *fsig, MonoInst **args)
4733 {
4734         MonoClass *param_klass = mono_class_from_mono_type (fsig->params [0]);
4735         MonoClass *return_klass = mono_class_from_mono_type (fsig->ret);
4736
4737         if (mini_is_gsharedvt_variable_type (fsig->ret))
4738                 return NULL;
4739
4740         //Valuetypes that are semantically equivalent or numbers than can be widened to
4741         if (is_unsafe_mov_compatible (cfg, param_klass, return_klass))
4742                 return args [0];
4743
4744         //Arrays of valuetypes that are semantically equivalent
4745         if (param_klass->rank == 1 && return_klass->rank == 1 && is_unsafe_mov_compatible (cfg, param_klass->element_class, return_klass->element_class))
4746                 return args [0];
4747
4748         return NULL;
4749 }
4750
4751 static MonoInst*
4752 mini_emit_inst_for_ctor (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
4753 {
4754 #ifdef MONO_ARCH_SIMD_INTRINSICS
4755         MonoInst *ins = NULL;
4756
4757         if (cfg->opt & MONO_OPT_SIMD) {
4758                 ins = mono_emit_simd_intrinsics (cfg, cmethod, fsig, args);
4759                 if (ins)
4760                         return ins;
4761         }
4762 #endif
4763
4764         return mono_emit_native_types_intrinsics (cfg, cmethod, fsig, args);
4765 }
4766
4767 MonoInst*
4768 mini_emit_memory_barrier (MonoCompile *cfg, int kind)
4769 {
4770         MonoInst *ins = NULL;
4771         MONO_INST_NEW (cfg, ins, OP_MEMORY_BARRIER);
4772         MONO_ADD_INS (cfg->cbb, ins);
4773         ins->backend.memory_barrier_kind = kind;
4774
4775         return ins;
4776 }
4777
4778 static MonoInst*
4779 llvm_emit_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
4780 {
4781         MonoInst *ins = NULL;
4782         int opcode = 0;
4783
4784         /* The LLVM backend supports these intrinsics */
4785         if (cmethod->klass == mono_defaults.math_class) {
4786                 if (strcmp (cmethod->name, "Sin") == 0) {
4787                         opcode = OP_SIN;
4788                 } else if (strcmp (cmethod->name, "Cos") == 0) {
4789                         opcode = OP_COS;
4790                 } else if (strcmp (cmethod->name, "Sqrt") == 0) {
4791                         opcode = OP_SQRT;
4792                 } else if (strcmp (cmethod->name, "Abs") == 0 && fsig->params [0]->type == MONO_TYPE_R8) {
4793                         opcode = OP_ABS;
4794                 }
4795
4796                 if (opcode && fsig->param_count == 1) {
4797                         MONO_INST_NEW (cfg, ins, opcode);
4798                         ins->type = STACK_R8;
4799                         ins->dreg = mono_alloc_dreg (cfg, ins->type);
4800                         ins->sreg1 = args [0]->dreg;
4801                         MONO_ADD_INS (cfg->cbb, ins);
4802                 }
4803
4804                 opcode = 0;
4805                 if (cfg->opt & MONO_OPT_CMOV) {
4806                         if (strcmp (cmethod->name, "Min") == 0) {
4807                                 if (fsig->params [0]->type == MONO_TYPE_I4)
4808                                         opcode = OP_IMIN;
4809                                 if (fsig->params [0]->type == MONO_TYPE_U4)
4810                                         opcode = OP_IMIN_UN;
4811                                 else if (fsig->params [0]->type == MONO_TYPE_I8)
4812                                         opcode = OP_LMIN;
4813                                 else if (fsig->params [0]->type == MONO_TYPE_U8)
4814                                         opcode = OP_LMIN_UN;
4815                         } else if (strcmp (cmethod->name, "Max") == 0) {
4816                                 if (fsig->params [0]->type == MONO_TYPE_I4)
4817                                         opcode = OP_IMAX;
4818                                 if (fsig->params [0]->type == MONO_TYPE_U4)
4819                                         opcode = OP_IMAX_UN;
4820                                 else if (fsig->params [0]->type == MONO_TYPE_I8)
4821                                         opcode = OP_LMAX;
4822                                 else if (fsig->params [0]->type == MONO_TYPE_U8)
4823                                         opcode = OP_LMAX_UN;
4824                         }
4825                 }
4826
4827                 if (opcode && fsig->param_count == 2) {
4828                         MONO_INST_NEW (cfg, ins, opcode);
4829                         ins->type = fsig->params [0]->type == MONO_TYPE_I4 ? STACK_I4 : STACK_I8;
4830                         ins->dreg = mono_alloc_dreg (cfg, ins->type);
4831                         ins->sreg1 = args [0]->dreg;
4832                         ins->sreg2 = args [1]->dreg;
4833                         MONO_ADD_INS (cfg->cbb, ins);
4834                 }
4835         }
4836
4837         return ins;
4838 }
4839
4840 static MonoInst*
4841 mini_emit_inst_for_sharable_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
4842 {
4843         if (cmethod->klass == mono_defaults.array_class) {
4844                 if (strcmp (cmethod->name, "UnsafeStore") == 0)
4845                         return emit_array_unsafe_access (cfg, fsig, args, TRUE);
4846                 else if (strcmp (cmethod->name, "UnsafeLoad") == 0)
4847                         return emit_array_unsafe_access (cfg, fsig, args, FALSE);
4848                 else if (strcmp (cmethod->name, "UnsafeMov") == 0)
4849                         return emit_array_unsafe_mov (cfg, fsig, args);
4850         }
4851
4852         return NULL;
4853 }
4854
4855
4856 static gboolean
4857 mono_type_is_native_blittable (MonoType *t)
4858 {
4859         if (MONO_TYPE_IS_REFERENCE (t))
4860                 return FALSE;
4861
4862         if (MONO_TYPE_IS_PRIMITIVE_SCALAR (t))
4863                 return TRUE;
4864
4865         MonoClass *klass = mono_class_from_mono_type (t);
4866
4867         //MonoClass::blitable depends on mono_class_setup_fields being done.
4868         mono_class_setup_fields (klass);
4869         if (!klass->blittable)
4870                 return FALSE;
4871
4872         // If the native marshal size is different we can't convert PtrToStructure to a type load
4873         if (mono_class_native_size (klass, NULL) != mono_class_value_size (klass, NULL))
4874                 return FALSE;
4875
4876         return TRUE;
4877 }
4878
4879
4880 static MonoInst*
4881 mini_emit_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
4882 {
4883         MonoInst *ins = NULL;
4884         MonoClass *runtime_helpers_class = mono_class_get_runtime_helpers_class ();
4885
4886         if (cmethod->klass == mono_defaults.string_class) {
4887                 if (strcmp (cmethod->name, "get_Chars") == 0 && fsig->param_count + fsig->hasthis == 2) {
4888                         int dreg = alloc_ireg (cfg);
4889                         int index_reg = alloc_preg (cfg);
4890                         int add_reg = alloc_preg (cfg);
4891
4892 #if SIZEOF_REGISTER == 8
4893                         if (COMPILE_LLVM (cfg)) {
4894                                 MONO_EMIT_NEW_UNALU (cfg, OP_ZEXT_I4, index_reg, args [1]->dreg);
4895                         } else {
4896                                 /* The array reg is 64 bits but the index reg is only 32 */
4897                                 MONO_EMIT_NEW_UNALU (cfg, OP_SEXT_I4, index_reg, args [1]->dreg);
4898                         }
4899 #else
4900                         index_reg = args [1]->dreg;
4901 #endif  
4902                         MONO_EMIT_BOUNDS_CHECK (cfg, args [0]->dreg, MonoString, length, index_reg);
4903
4904 #if defined(TARGET_X86) || defined(TARGET_AMD64)
4905                         EMIT_NEW_X86_LEA (cfg, ins, args [0]->dreg, index_reg, 1, MONO_STRUCT_OFFSET (MonoString, chars));
4906                         add_reg = ins->dreg;
4907                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADU2_MEMBASE, dreg, 
4908                                                                    add_reg, 0);
4909 #else
4910                         int mult_reg = alloc_preg (cfg);
4911                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHL_IMM, mult_reg, index_reg, 1);
4912                         MONO_EMIT_NEW_BIALU (cfg, OP_PADD, add_reg, mult_reg, args [0]->dreg);
4913                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADU2_MEMBASE, dreg, 
4914                                                                    add_reg, MONO_STRUCT_OFFSET (MonoString, chars));
4915 #endif
4916                         type_from_op (cfg, ins, NULL, NULL);
4917                         return ins;
4918                 } else if (strcmp (cmethod->name, "get_Length") == 0 && fsig->param_count + fsig->hasthis == 1) {
4919                         int dreg = alloc_ireg (cfg);
4920                         /* Decompose later to allow more optimizations */
4921                         EMIT_NEW_UNALU (cfg, ins, OP_STRLEN, dreg, args [0]->dreg);
4922                         ins->type = STACK_I4;
4923                         ins->flags |= MONO_INST_FAULT;
4924                         cfg->cbb->has_array_access = TRUE;
4925                         cfg->flags |= MONO_CFG_HAS_ARRAY_ACCESS;
4926
4927                         return ins;
4928                 } else 
4929                         return NULL;
4930         } else if (cmethod->klass == mono_defaults.object_class) {
4931                 if (strcmp (cmethod->name, "GetType") == 0 && fsig->param_count + fsig->hasthis == 1) {
4932                         int dreg = alloc_ireg_ref (cfg);
4933                         int vt_reg = alloc_preg (cfg);
4934                         MONO_EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, vt_reg, args [0]->dreg, MONO_STRUCT_OFFSET (MonoObject, vtable));
4935                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, dreg, vt_reg, MONO_STRUCT_OFFSET (MonoVTable, type));
4936                         type_from_op (cfg, ins, NULL, NULL);
4937
4938                         return ins;
4939                 } else if (!cfg->backend->emulate_mul_div && strcmp (cmethod->name, "InternalGetHashCode") == 0 && fsig->param_count == 1 && !mono_gc_is_moving ()) {
4940                         int dreg = alloc_ireg (cfg);
4941                         int t1 = alloc_ireg (cfg);
4942         
4943                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHL_IMM, t1, args [0]->dreg, 3);
4944                         EMIT_NEW_BIALU_IMM (cfg, ins, OP_MUL_IMM, dreg, t1, 2654435761u);
4945                         ins->type = STACK_I4;
4946
4947                         return ins;
4948                 } else if (strcmp (cmethod->name, ".ctor") == 0 && fsig->param_count == 0) {
4949                         MONO_INST_NEW (cfg, ins, OP_NOP);
4950                         MONO_ADD_INS (cfg->cbb, ins);
4951                         return ins;
4952                 } else
4953                         return NULL;
4954         } else if (cmethod->klass == mono_defaults.array_class) {
4955                 if (strcmp (cmethod->name, "GetGenericValueImpl") == 0 && fsig->param_count + fsig->hasthis == 3 && !cfg->gsharedvt)
4956                         return emit_array_generic_access (cfg, fsig, args, FALSE);
4957                 else if (strcmp (cmethod->name, "SetGenericValueImpl") == 0 && fsig->param_count + fsig->hasthis == 3 && !cfg->gsharedvt)
4958                         return emit_array_generic_access (cfg, fsig, args, TRUE);
4959
4960 #ifndef MONO_BIG_ARRAYS
4961                 /*
4962                  * This is an inline version of GetLength/GetLowerBound(0) used frequently in
4963                  * Array methods.
4964                  */
4965                 else if (((strcmp (cmethod->name, "GetLength") == 0 && fsig->param_count + fsig->hasthis == 2) ||
4966                          (strcmp (cmethod->name, "GetLowerBound") == 0 && fsig->param_count + fsig->hasthis == 2)) &&
4967                          args [1]->opcode == OP_ICONST && args [1]->inst_c0 == 0) {
4968                         int dreg = alloc_ireg (cfg);
4969                         int bounds_reg = alloc_ireg_mp (cfg);
4970                         MonoBasicBlock *end_bb, *szarray_bb;
4971                         gboolean get_length = strcmp (cmethod->name, "GetLength") == 0;
4972
4973                         NEW_BBLOCK (cfg, end_bb);
4974                         NEW_BBLOCK (cfg, szarray_bb);
4975
4976                         EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, ins, OP_LOAD_MEMBASE, bounds_reg,
4977                                                                                  args [0]->dreg, MONO_STRUCT_OFFSET (MonoArray, bounds));
4978                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, bounds_reg, 0);
4979                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, szarray_bb);
4980                         /* Non-szarray case */
4981                         if (get_length)
4982                                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADI4_MEMBASE, dreg,
4983                                                                            bounds_reg, MONO_STRUCT_OFFSET (MonoArrayBounds, length));
4984                         else
4985                                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADI4_MEMBASE, dreg,
4986                                                                            bounds_reg, MONO_STRUCT_OFFSET (MonoArrayBounds, lower_bound));
4987                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
4988                         MONO_START_BB (cfg, szarray_bb);
4989                         /* Szarray case */
4990                         if (get_length)
4991                                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADI4_MEMBASE, dreg,
4992                                                                            args [0]->dreg, MONO_STRUCT_OFFSET (MonoArray, max_length));
4993                         else
4994                                 MONO_EMIT_NEW_ICONST (cfg, dreg, 0);
4995                         MONO_START_BB (cfg, end_bb);
4996
4997                         EMIT_NEW_UNALU (cfg, ins, OP_MOVE, dreg, dreg);
4998                         ins->type = STACK_I4;
4999                         
5000                         return ins;
5001                 }
5002 #endif
5003
5004                 if (cmethod->name [0] != 'g')
5005                         return NULL;
5006
5007                 if (strcmp (cmethod->name, "get_Rank") == 0 && fsig->param_count + fsig->hasthis == 1) {
5008                         int dreg = alloc_ireg (cfg);
5009                         int vtable_reg = alloc_preg (cfg);
5010                         MONO_EMIT_NEW_LOAD_MEMBASE_OP_FAULT (cfg, OP_LOAD_MEMBASE, vtable_reg, 
5011                                                                                                  args [0]->dreg, MONO_STRUCT_OFFSET (MonoObject, vtable));
5012                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADU1_MEMBASE, dreg,
5013                                                                    vtable_reg, MONO_STRUCT_OFFSET (MonoVTable, rank));
5014                         type_from_op (cfg, ins, NULL, NULL);
5015
5016                         return ins;
5017                 } else if (strcmp (cmethod->name, "get_Length") == 0 && fsig->param_count + fsig->hasthis == 1) {
5018                         int dreg = alloc_ireg (cfg);
5019
5020                         EMIT_NEW_LOAD_MEMBASE_FAULT (cfg, ins, OP_LOADI4_MEMBASE, dreg, 
5021                                                                                  args [0]->dreg, MONO_STRUCT_OFFSET (MonoArray, max_length));
5022                         type_from_op (cfg, ins, NULL, NULL);
5023
5024                         return ins;
5025                 } else
5026                         return NULL;
5027         } else if (cmethod->klass == runtime_helpers_class) {
5028                 if (strcmp (cmethod->name, "get_OffsetToStringData") == 0 && fsig->param_count == 0) {
5029                         EMIT_NEW_ICONST (cfg, ins, MONO_STRUCT_OFFSET (MonoString, chars));
5030                         return ins;
5031                 } else if (strcmp (cmethod->name, "IsReferenceOrContainsReferences") == 0 && fsig->param_count == 0) {
5032                         MonoGenericContext *ctx = mono_method_get_context (cmethod);
5033                         g_assert (ctx);
5034                         g_assert (ctx->method_inst);
5035                         g_assert (ctx->method_inst->type_argc == 1);
5036                         MonoType *arg_type = ctx->method_inst->type_argv [0];
5037                         MonoType *t;
5038                         MonoClass *klass;
5039
5040                         ins = NULL;
5041
5042                         /* Resolve the argument class as possible so we can handle common cases fast */
5043                         t = mini_get_underlying_type (arg_type);
5044                         klass = mono_class_from_mono_type (t);
5045                         mono_class_init (klass);
5046                         if (MONO_TYPE_IS_REFERENCE (t))
5047                                 EMIT_NEW_ICONST (cfg, ins, 1);
5048                         else if (MONO_TYPE_IS_PRIMITIVE (t))
5049                                 EMIT_NEW_ICONST (cfg, ins, 0);
5050                         else if (cfg->gshared && (t->type == MONO_TYPE_VAR || t->type == MONO_TYPE_MVAR) && !mini_type_var_is_vt (t))
5051                                 EMIT_NEW_ICONST (cfg, ins, 1);
5052                         else if (!cfg->gshared || !mini_class_check_context_used (cfg, klass))
5053                                 EMIT_NEW_ICONST (cfg, ins, klass->has_references ? 1 : 0);
5054                         else {
5055                                 g_assert (cfg->gshared);
5056
5057                                 /* Have to use the original argument class here */
5058                                 MonoClass *arg_class = mono_class_from_mono_type (arg_type);
5059                                 int context_used = mini_class_check_context_used (cfg, arg_class);
5060
5061                                 /* This returns 1 or 2 */
5062                                 MonoInst *info = mini_emit_get_rgctx_klass (cfg, context_used, arg_class, MONO_RGCTX_INFO_CLASS_IS_REF_OR_CONTAINS_REFS);
5063                                 int dreg = alloc_ireg (cfg);
5064                                 EMIT_NEW_BIALU_IMM (cfg, ins, OP_ISUB_IMM, dreg, info->dreg, 1);
5065                         }
5066
5067                         return ins;
5068                 } else
5069                         return NULL;
5070         } else if (cmethod->klass == mono_defaults.monitor_class) {
5071                 gboolean is_enter = FALSE;
5072                 gboolean is_v4 = FALSE;
5073
5074                 if (!strcmp (cmethod->name, "Enter") && fsig->param_count == 2 && fsig->params [1]->byref) {
5075                         is_enter = TRUE;
5076                         is_v4 = TRUE;
5077                 }
5078                 if (!strcmp (cmethod->name, "Enter") && fsig->param_count == 1)
5079                         is_enter = TRUE;
5080
5081                 if (is_enter) {
5082                         /*
5083                          * To make async stack traces work, icalls which can block should have a wrapper.
5084                          * For Monitor.Enter, emit two calls: a fastpath which doesn't have a wrapper, and a slowpath, which does.
5085                          */
5086                         MonoBasicBlock *end_bb;
5087
5088                         NEW_BBLOCK (cfg, end_bb);
5089
5090                         ins = mono_emit_jit_icall (cfg, is_v4 ? (gpointer)mono_monitor_enter_v4_fast : (gpointer)mono_monitor_enter_fast, args);
5091                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ICOMPARE_IMM, -1, ins->dreg, 0);
5092                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBNE_UN, end_bb);
5093                         ins = mono_emit_jit_icall (cfg, is_v4 ? (gpointer)mono_monitor_enter_v4_internal : (gpointer)mono_monitor_enter_internal, args);
5094                         MONO_START_BB (cfg, end_bb);
5095                         return ins;
5096                 }
5097         } else if (cmethod->klass == mono_defaults.thread_class) {
5098                 if (strcmp (cmethod->name, "SpinWait_nop") == 0 && fsig->param_count == 0) {
5099                         MONO_INST_NEW (cfg, ins, OP_RELAXED_NOP);
5100                         MONO_ADD_INS (cfg->cbb, ins);
5101                         return ins;
5102                 } else if (strcmp (cmethod->name, "MemoryBarrier") == 0 && fsig->param_count == 0) {
5103                         return mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
5104                 } else if (!strcmp (cmethod->name, "VolatileRead") && fsig->param_count == 1) {
5105                         guint32 opcode = 0;
5106                         gboolean is_ref = mini_type_is_reference (fsig->params [0]);
5107
5108                         if (fsig->params [0]->type == MONO_TYPE_I1)
5109                                 opcode = OP_LOADI1_MEMBASE;
5110                         else if (fsig->params [0]->type == MONO_TYPE_U1)
5111                                 opcode = OP_LOADU1_MEMBASE;
5112                         else if (fsig->params [0]->type == MONO_TYPE_I2)
5113                                 opcode = OP_LOADI2_MEMBASE;
5114                         else if (fsig->params [0]->type == MONO_TYPE_U2)
5115                                 opcode = OP_LOADU2_MEMBASE;
5116                         else if (fsig->params [0]->type == MONO_TYPE_I4)
5117                                 opcode = OP_LOADI4_MEMBASE;
5118                         else if (fsig->params [0]->type == MONO_TYPE_U4)
5119                                 opcode = OP_LOADU4_MEMBASE;
5120                         else if (fsig->params [0]->type == MONO_TYPE_I8 || fsig->params [0]->type == MONO_TYPE_U8)
5121                                 opcode = OP_LOADI8_MEMBASE;
5122                         else if (fsig->params [0]->type == MONO_TYPE_R4)
5123                                 opcode = OP_LOADR4_MEMBASE;
5124                         else if (fsig->params [0]->type == MONO_TYPE_R8)
5125                                 opcode = OP_LOADR8_MEMBASE;
5126                         else if (is_ref || fsig->params [0]->type == MONO_TYPE_I || fsig->params [0]->type == MONO_TYPE_U)
5127                                 opcode = OP_LOAD_MEMBASE;
5128
5129                         if (opcode) {
5130                                 MONO_INST_NEW (cfg, ins, opcode);
5131                                 ins->inst_basereg = args [0]->dreg;
5132                                 ins->inst_offset = 0;
5133                                 MONO_ADD_INS (cfg->cbb, ins);
5134
5135                                 switch (fsig->params [0]->type) {
5136                                 case MONO_TYPE_I1:
5137                                 case MONO_TYPE_U1:
5138                                 case MONO_TYPE_I2:
5139                                 case MONO_TYPE_U2:
5140                                 case MONO_TYPE_I4:
5141                                 case MONO_TYPE_U4:
5142                                         ins->dreg = mono_alloc_ireg (cfg);
5143                                         ins->type = STACK_I4;
5144                                         break;
5145                                 case MONO_TYPE_I8:
5146                                 case MONO_TYPE_U8:
5147                                         ins->dreg = mono_alloc_lreg (cfg);
5148                                         ins->type = STACK_I8;
5149                                         break;
5150                                 case MONO_TYPE_I:
5151                                 case MONO_TYPE_U:
5152                                         ins->dreg = mono_alloc_ireg (cfg);
5153 #if SIZEOF_REGISTER == 8
5154                                         ins->type = STACK_I8;
5155 #else
5156                                         ins->type = STACK_I4;
5157 #endif
5158                                         break;
5159                                 case MONO_TYPE_R4:
5160                                 case MONO_TYPE_R8:
5161                                         ins->dreg = mono_alloc_freg (cfg);
5162                                         ins->type = STACK_R8;
5163                                         break;
5164                                 default:
5165                                         g_assert (mini_type_is_reference (fsig->params [0]));
5166                                         ins->dreg = mono_alloc_ireg_ref (cfg);
5167                                         ins->type = STACK_OBJ;
5168                                         break;
5169                                 }
5170
5171                                 if (opcode == OP_LOADI8_MEMBASE)
5172                                         ins = mono_decompose_opcode (cfg, ins);
5173
5174                                 mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
5175
5176                                 return ins;
5177                         }
5178                 } else if (!strcmp (cmethod->name, "VolatileWrite") && fsig->param_count == 2) {
5179                         guint32 opcode = 0;
5180                         gboolean is_ref = mini_type_is_reference (fsig->params [0]);
5181
5182                         if (fsig->params [0]->type == MONO_TYPE_I1 || fsig->params [0]->type == MONO_TYPE_U1)
5183                                 opcode = OP_STOREI1_MEMBASE_REG;
5184                         else if (fsig->params [0]->type == MONO_TYPE_I2 || fsig->params [0]->type == MONO_TYPE_U2)
5185                                 opcode = OP_STOREI2_MEMBASE_REG;
5186                         else if (fsig->params [0]->type == MONO_TYPE_I4 || fsig->params [0]->type == MONO_TYPE_U4)
5187                                 opcode = OP_STOREI4_MEMBASE_REG;
5188                         else if (fsig->params [0]->type == MONO_TYPE_I8 || fsig->params [0]->type == MONO_TYPE_U8)
5189                                 opcode = OP_STOREI8_MEMBASE_REG;
5190                         else if (fsig->params [0]->type == MONO_TYPE_R4)
5191                                 opcode = OP_STORER4_MEMBASE_REG;
5192                         else if (fsig->params [0]->type == MONO_TYPE_R8)
5193                                 opcode = OP_STORER8_MEMBASE_REG;
5194                         else if (is_ref || fsig->params [0]->type == MONO_TYPE_I || fsig->params [0]->type == MONO_TYPE_U)
5195                                 opcode = OP_STORE_MEMBASE_REG;
5196
5197                         if (opcode) {
5198                                 mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
5199
5200                                 MONO_INST_NEW (cfg, ins, opcode);
5201                                 ins->sreg1 = args [1]->dreg;
5202                                 ins->inst_destbasereg = args [0]->dreg;
5203                                 ins->inst_offset = 0;
5204                                 MONO_ADD_INS (cfg->cbb, ins);
5205
5206                                 if (opcode == OP_STOREI8_MEMBASE_REG)
5207                                         ins = mono_decompose_opcode (cfg, ins);
5208
5209                                 return ins;
5210                         }
5211                 }
5212         } else if (cmethod->klass->image == mono_defaults.corlib &&
5213                            (strcmp (cmethod->klass->name_space, "System.Threading") == 0) &&
5214                            (strcmp (cmethod->klass->name, "Interlocked") == 0)) {
5215                 ins = NULL;
5216
5217 #if SIZEOF_REGISTER == 8
5218                 if (!cfg->llvm_only && strcmp (cmethod->name, "Read") == 0 && fsig->param_count == 1 && (fsig->params [0]->type == MONO_TYPE_I8)) {
5219                         if (!cfg->llvm_only && mono_arch_opcode_supported (OP_ATOMIC_LOAD_I8)) {
5220                                 MONO_INST_NEW (cfg, ins, OP_ATOMIC_LOAD_I8);
5221                                 ins->dreg = mono_alloc_preg (cfg);
5222                                 ins->sreg1 = args [0]->dreg;
5223                                 ins->type = STACK_I8;
5224                                 ins->backend.memory_barrier_kind = MONO_MEMORY_BARRIER_SEQ;
5225                                 MONO_ADD_INS (cfg->cbb, ins);
5226                         } else {
5227                                 MonoInst *load_ins;
5228
5229                                 mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
5230
5231                                 /* 64 bit reads are already atomic */
5232                                 MONO_INST_NEW (cfg, load_ins, OP_LOADI8_MEMBASE);
5233                                 load_ins->dreg = mono_alloc_preg (cfg);
5234                                 load_ins->inst_basereg = args [0]->dreg;
5235                                 load_ins->inst_offset = 0;
5236                                 load_ins->type = STACK_I8;
5237                                 MONO_ADD_INS (cfg->cbb, load_ins);
5238
5239                                 mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
5240
5241                                 ins = load_ins;
5242                         }
5243                 }
5244 #endif
5245
5246                 if (strcmp (cmethod->name, "Increment") == 0 && fsig->param_count == 1) {
5247                         MonoInst *ins_iconst;
5248                         guint32 opcode = 0;
5249
5250                         if (fsig->params [0]->type == MONO_TYPE_I4) {
5251                                 opcode = OP_ATOMIC_ADD_I4;
5252                                 cfg->has_atomic_add_i4 = TRUE;
5253                         }
5254 #if SIZEOF_REGISTER == 8
5255                         else if (fsig->params [0]->type == MONO_TYPE_I8)
5256                                 opcode = OP_ATOMIC_ADD_I8;
5257 #endif
5258                         if (opcode) {
5259                                 if (!mono_arch_opcode_supported (opcode))
5260                                         return NULL;
5261                                 MONO_INST_NEW (cfg, ins_iconst, OP_ICONST);
5262                                 ins_iconst->inst_c0 = 1;
5263                                 ins_iconst->dreg = mono_alloc_ireg (cfg);
5264                                 MONO_ADD_INS (cfg->cbb, ins_iconst);
5265
5266                                 MONO_INST_NEW (cfg, ins, opcode);
5267                                 ins->dreg = mono_alloc_ireg (cfg);
5268                                 ins->inst_basereg = args [0]->dreg;
5269                                 ins->inst_offset = 0;
5270                                 ins->sreg2 = ins_iconst->dreg;
5271                                 ins->type = (opcode == OP_ATOMIC_ADD_I4) ? STACK_I4 : STACK_I8;
5272                                 MONO_ADD_INS (cfg->cbb, ins);
5273                         }
5274                 } else if (strcmp (cmethod->name, "Decrement") == 0 && fsig->param_count == 1) {
5275                         MonoInst *ins_iconst;
5276                         guint32 opcode = 0;
5277
5278                         if (fsig->params [0]->type == MONO_TYPE_I4) {
5279                                 opcode = OP_ATOMIC_ADD_I4;
5280                                 cfg->has_atomic_add_i4 = TRUE;
5281                         }
5282 #if SIZEOF_REGISTER == 8
5283                         else if (fsig->params [0]->type == MONO_TYPE_I8)
5284                                 opcode = OP_ATOMIC_ADD_I8;
5285 #endif
5286                         if (opcode) {
5287                                 if (!mono_arch_opcode_supported (opcode))
5288                                         return NULL;
5289                                 MONO_INST_NEW (cfg, ins_iconst, OP_ICONST);
5290                                 ins_iconst->inst_c0 = -1;
5291                                 ins_iconst->dreg = mono_alloc_ireg (cfg);
5292                                 MONO_ADD_INS (cfg->cbb, ins_iconst);
5293
5294                                 MONO_INST_NEW (cfg, ins, opcode);
5295                                 ins->dreg = mono_alloc_ireg (cfg);
5296                                 ins->inst_basereg = args [0]->dreg;
5297                                 ins->inst_offset = 0;
5298                                 ins->sreg2 = ins_iconst->dreg;
5299                                 ins->type = (opcode == OP_ATOMIC_ADD_I4) ? STACK_I4 : STACK_I8;
5300                                 MONO_ADD_INS (cfg->cbb, ins);
5301                         }
5302                 } else if (strcmp (cmethod->name, "Add") == 0 && fsig->param_count == 2) {
5303                         guint32 opcode = 0;
5304
5305                         if (fsig->params [0]->type == MONO_TYPE_I4) {
5306                                 opcode = OP_ATOMIC_ADD_I4;
5307                                 cfg->has_atomic_add_i4 = TRUE;
5308                         }
5309 #if SIZEOF_REGISTER == 8
5310                         else if (fsig->params [0]->type == MONO_TYPE_I8)
5311                                 opcode = OP_ATOMIC_ADD_I8;
5312 #endif
5313                         if (opcode) {
5314                                 if (!mono_arch_opcode_supported (opcode))
5315                                         return NULL;
5316                                 MONO_INST_NEW (cfg, ins, opcode);
5317                                 ins->dreg = mono_alloc_ireg (cfg);
5318                                 ins->inst_basereg = args [0]->dreg;
5319                                 ins->inst_offset = 0;
5320                                 ins->sreg2 = args [1]->dreg;
5321                                 ins->type = (opcode == OP_ATOMIC_ADD_I4) ? STACK_I4 : STACK_I8;
5322                                 MONO_ADD_INS (cfg->cbb, ins);
5323                         }
5324                 }
5325                 else if (strcmp (cmethod->name, "Exchange") == 0 && fsig->param_count == 2) {
5326                         MonoInst *f2i = NULL, *i2f;
5327                         guint32 opcode, f2i_opcode, i2f_opcode;
5328                         gboolean is_ref = mini_type_is_reference (fsig->params [0]);
5329                         gboolean is_float = fsig->params [0]->type == MONO_TYPE_R4 || fsig->params [0]->type == MONO_TYPE_R8;
5330
5331                         if (fsig->params [0]->type == MONO_TYPE_I4 ||
5332                             fsig->params [0]->type == MONO_TYPE_R4) {
5333                                 opcode = OP_ATOMIC_EXCHANGE_I4;
5334                                 f2i_opcode = OP_MOVE_F_TO_I4;
5335                                 i2f_opcode = OP_MOVE_I4_TO_F;
5336                                 cfg->has_atomic_exchange_i4 = TRUE;
5337                         }
5338 #if SIZEOF_REGISTER == 8
5339                         else if (is_ref ||
5340                                  fsig->params [0]->type == MONO_TYPE_I8 ||
5341                                  fsig->params [0]->type == MONO_TYPE_R8 ||
5342                                  fsig->params [0]->type == MONO_TYPE_I) {
5343                                 opcode = OP_ATOMIC_EXCHANGE_I8;
5344                                 f2i_opcode = OP_MOVE_F_TO_I8;
5345                                 i2f_opcode = OP_MOVE_I8_TO_F;
5346                         }
5347 #else
5348                         else if (is_ref || fsig->params [0]->type == MONO_TYPE_I) {
5349                                 opcode = OP_ATOMIC_EXCHANGE_I4;
5350                                 cfg->has_atomic_exchange_i4 = TRUE;
5351                         }
5352 #endif
5353                         else
5354                                 return NULL;
5355
5356                         if (!mono_arch_opcode_supported (opcode))
5357                                 return NULL;
5358
5359                         if (is_float) {
5360                                 /* TODO: Decompose these opcodes instead of bailing here. */
5361                                 if (COMPILE_SOFT_FLOAT (cfg))
5362                                         return NULL;
5363
5364                                 MONO_INST_NEW (cfg, f2i, f2i_opcode);
5365                                 f2i->dreg = mono_alloc_ireg (cfg);
5366                                 f2i->sreg1 = args [1]->dreg;
5367                                 if (f2i_opcode == OP_MOVE_F_TO_I4)
5368                                         f2i->backend.spill_var = mini_get_int_to_float_spill_area (cfg);
5369                                 MONO_ADD_INS (cfg->cbb, f2i);
5370                         }
5371
5372                         MONO_INST_NEW (cfg, ins, opcode);
5373                         ins->dreg = is_ref ? mono_alloc_ireg_ref (cfg) : mono_alloc_ireg (cfg);
5374                         ins->inst_basereg = args [0]->dreg;
5375                         ins->inst_offset = 0;
5376                         ins->sreg2 = is_float ? f2i->dreg : args [1]->dreg;
5377                         MONO_ADD_INS (cfg->cbb, ins);
5378
5379                         switch (fsig->params [0]->type) {
5380                         case MONO_TYPE_I4:
5381                                 ins->type = STACK_I4;
5382                                 break;
5383                         case MONO_TYPE_I8:
5384                                 ins->type = STACK_I8;
5385                                 break;
5386                         case MONO_TYPE_I:
5387 #if SIZEOF_REGISTER == 8
5388                                 ins->type = STACK_I8;
5389 #else
5390                                 ins->type = STACK_I4;
5391 #endif
5392                                 break;
5393                         case MONO_TYPE_R4:
5394                         case MONO_TYPE_R8:
5395                                 ins->type = STACK_R8;
5396                                 break;
5397                         default:
5398                                 g_assert (mini_type_is_reference (fsig->params [0]));
5399                                 ins->type = STACK_OBJ;
5400                                 break;
5401                         }
5402
5403                         if (is_float) {
5404                                 MONO_INST_NEW (cfg, i2f, i2f_opcode);
5405                                 i2f->dreg = mono_alloc_freg (cfg);
5406                                 i2f->sreg1 = ins->dreg;
5407                                 i2f->type = STACK_R8;
5408                                 if (i2f_opcode == OP_MOVE_I4_TO_F)
5409                                         i2f->backend.spill_var = mini_get_int_to_float_spill_area (cfg);
5410                                 MONO_ADD_INS (cfg->cbb, i2f);
5411
5412                                 ins = i2f;
5413                         }
5414
5415                         if (cfg->gen_write_barriers && is_ref)
5416                                 mini_emit_write_barrier (cfg, args [0], args [1]);
5417                 }
5418                 else if ((strcmp (cmethod->name, "CompareExchange") == 0) && fsig->param_count == 3) {
5419                         MonoInst *f2i_new = NULL, *f2i_cmp = NULL, *i2f;
5420                         guint32 opcode, f2i_opcode, i2f_opcode;
5421                         gboolean is_ref = mini_type_is_reference (fsig->params [1]);
5422                         gboolean is_float = fsig->params [1]->type == MONO_TYPE_R4 || fsig->params [1]->type == MONO_TYPE_R8;
5423
5424                         if (fsig->params [1]->type == MONO_TYPE_I4 ||
5425                             fsig->params [1]->type == MONO_TYPE_R4) {
5426                                 opcode = OP_ATOMIC_CAS_I4;
5427                                 f2i_opcode = OP_MOVE_F_TO_I4;
5428                                 i2f_opcode = OP_MOVE_I4_TO_F;
5429                                 cfg->has_atomic_cas_i4 = TRUE;
5430                         }
5431 #if SIZEOF_REGISTER == 8
5432                         else if (is_ref ||
5433                                  fsig->params [1]->type == MONO_TYPE_I8 ||
5434                                  fsig->params [1]->type == MONO_TYPE_R8 ||
5435                                  fsig->params [1]->type == MONO_TYPE_I) {
5436                                 opcode = OP_ATOMIC_CAS_I8;
5437                                 f2i_opcode = OP_MOVE_F_TO_I8;
5438                                 i2f_opcode = OP_MOVE_I8_TO_F;
5439                         }
5440 #else
5441                         else if (is_ref || fsig->params [1]->type == MONO_TYPE_I) {
5442                                 opcode = OP_ATOMIC_CAS_I4;
5443                                 cfg->has_atomic_cas_i4 = TRUE;
5444                         }
5445 #endif
5446                         else
5447                                 return NULL;
5448
5449                         if (!mono_arch_opcode_supported (opcode))
5450                                 return NULL;
5451
5452                         if (is_float) {
5453                                 /* TODO: Decompose these opcodes instead of bailing here. */
5454                                 if (COMPILE_SOFT_FLOAT (cfg))
5455                                         return NULL;
5456
5457                                 MONO_INST_NEW (cfg, f2i_new, f2i_opcode);
5458                                 f2i_new->dreg = mono_alloc_ireg (cfg);
5459                                 f2i_new->sreg1 = args [1]->dreg;
5460                                 if (f2i_opcode == OP_MOVE_F_TO_I4)
5461                                         f2i_new->backend.spill_var = mini_get_int_to_float_spill_area (cfg);
5462                                 MONO_ADD_INS (cfg->cbb, f2i_new);
5463
5464                                 MONO_INST_NEW (cfg, f2i_cmp, f2i_opcode);
5465                                 f2i_cmp->dreg = mono_alloc_ireg (cfg);
5466                                 f2i_cmp->sreg1 = args [2]->dreg;
5467                                 if (f2i_opcode == OP_MOVE_F_TO_I4)
5468                                         f2i_cmp->backend.spill_var = mini_get_int_to_float_spill_area (cfg);
5469                                 MONO_ADD_INS (cfg->cbb, f2i_cmp);
5470                         }
5471
5472                         MONO_INST_NEW (cfg, ins, opcode);
5473                         ins->dreg = is_ref ? alloc_ireg_ref (cfg) : alloc_ireg (cfg);
5474                         ins->sreg1 = args [0]->dreg;
5475                         ins->sreg2 = is_float ? f2i_new->dreg : args [1]->dreg;
5476                         ins->sreg3 = is_float ? f2i_cmp->dreg : args [2]->dreg;
5477                         MONO_ADD_INS (cfg->cbb, ins);
5478
5479                         switch (fsig->params [1]->type) {
5480                         case MONO_TYPE_I4:
5481                                 ins->type = STACK_I4;
5482                                 break;
5483                         case MONO_TYPE_I8:
5484                                 ins->type = STACK_I8;
5485                                 break;
5486                         case MONO_TYPE_I:
5487 #if SIZEOF_REGISTER == 8
5488                                 ins->type = STACK_I8;
5489 #else
5490                                 ins->type = STACK_I4;
5491 #endif
5492                                 break;
5493                         case MONO_TYPE_R4:
5494                                 ins->type = cfg->r4_stack_type;
5495                                 break;
5496                         case MONO_TYPE_R8:
5497                                 ins->type = STACK_R8;
5498                                 break;
5499                         default:
5500                                 g_assert (mini_type_is_reference (fsig->params [1]));
5501                                 ins->type = STACK_OBJ;
5502                                 break;
5503                         }
5504
5505                         if (is_float) {
5506                                 MONO_INST_NEW (cfg, i2f, i2f_opcode);
5507                                 i2f->dreg = mono_alloc_freg (cfg);
5508                                 i2f->sreg1 = ins->dreg;
5509                                 i2f->type = STACK_R8;
5510                                 if (i2f_opcode == OP_MOVE_I4_TO_F)
5511                                         i2f->backend.spill_var = mini_get_int_to_float_spill_area (cfg);
5512                                 MONO_ADD_INS (cfg->cbb, i2f);
5513
5514                                 ins = i2f;
5515                         }
5516
5517                         if (cfg->gen_write_barriers && is_ref)
5518                                 mini_emit_write_barrier (cfg, args [0], args [1]);
5519                 }
5520                 else if ((strcmp (cmethod->name, "CompareExchange") == 0) && fsig->param_count == 4 &&
5521                          fsig->params [1]->type == MONO_TYPE_I4) {
5522                         MonoInst *cmp, *ceq;
5523
5524                         if (!mono_arch_opcode_supported (OP_ATOMIC_CAS_I4))
5525                                 return NULL;
5526
5527                         /* int32 r = CAS (location, value, comparand); */
5528                         MONO_INST_NEW (cfg, ins, OP_ATOMIC_CAS_I4);
5529                         ins->dreg = alloc_ireg (cfg);
5530                         ins->sreg1 = args [0]->dreg;
5531                         ins->sreg2 = args [1]->dreg;
5532                         ins->sreg3 = args [2]->dreg;
5533                         ins->type = STACK_I4;
5534                         MONO_ADD_INS (cfg->cbb, ins);
5535
5536                         /* bool result = r == comparand; */
5537                         MONO_INST_NEW (cfg, cmp, OP_ICOMPARE);
5538                         cmp->sreg1 = ins->dreg;
5539                         cmp->sreg2 = args [2]->dreg;
5540                         cmp->type = STACK_I4;
5541                         MONO_ADD_INS (cfg->cbb, cmp);
5542
5543                         MONO_INST_NEW (cfg, ceq, OP_ICEQ);
5544                         ceq->dreg = alloc_ireg (cfg);
5545                         ceq->type = STACK_I4;
5546                         MONO_ADD_INS (cfg->cbb, ceq);
5547
5548                         /* *success = result; */
5549                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI1_MEMBASE_REG, args [3]->dreg, 0, ceq->dreg);
5550
5551                         cfg->has_atomic_cas_i4 = TRUE;
5552                 }
5553                 else if (strcmp (cmethod->name, "MemoryBarrier") == 0 && fsig->param_count == 0)
5554                         ins = mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
5555
5556                 if (ins)
5557                         return ins;
5558         } else if (cmethod->klass->image == mono_defaults.corlib &&
5559                            (strcmp (cmethod->klass->name_space, "System.Threading") == 0) &&
5560                            (strcmp (cmethod->klass->name, "Volatile") == 0)) {
5561                 ins = NULL;
5562
5563                 if (!cfg->llvm_only && !strcmp (cmethod->name, "Read") && fsig->param_count == 1) {
5564                         guint32 opcode = 0;
5565                         MonoType *t = fsig->params [0];
5566                         gboolean is_ref;
5567                         gboolean is_float = t->type == MONO_TYPE_R4 || t->type == MONO_TYPE_R8;
5568
5569                         g_assert (t->byref);
5570                         /* t is a byref type, so the reference check is more complicated */
5571                         is_ref = mini_type_is_reference (&mono_class_from_mono_type (t)->byval_arg);
5572                         if (t->type == MONO_TYPE_I1)
5573                                 opcode = OP_ATOMIC_LOAD_I1;
5574                         else if (t->type == MONO_TYPE_U1 || t->type == MONO_TYPE_BOOLEAN)
5575                                 opcode = OP_ATOMIC_LOAD_U1;
5576                         else if (t->type == MONO_TYPE_I2)
5577                                 opcode = OP_ATOMIC_LOAD_I2;
5578                         else if (t->type == MONO_TYPE_U2)
5579                                 opcode = OP_ATOMIC_LOAD_U2;
5580                         else if (t->type == MONO_TYPE_I4)
5581                                 opcode = OP_ATOMIC_LOAD_I4;
5582                         else if (t->type == MONO_TYPE_U4)
5583                                 opcode = OP_ATOMIC_LOAD_U4;
5584                         else if (t->type == MONO_TYPE_R4)
5585                                 opcode = OP_ATOMIC_LOAD_R4;
5586                         else if (t->type == MONO_TYPE_R8)
5587                                 opcode = OP_ATOMIC_LOAD_R8;
5588 #if SIZEOF_REGISTER == 8
5589                         else if (t->type == MONO_TYPE_I8 || t->type == MONO_TYPE_I)
5590                                 opcode = OP_ATOMIC_LOAD_I8;
5591                         else if (is_ref || t->type == MONO_TYPE_U8 || t->type == MONO_TYPE_U)
5592                                 opcode = OP_ATOMIC_LOAD_U8;
5593 #else
5594                         else if (t->type == MONO_TYPE_I)
5595                                 opcode = OP_ATOMIC_LOAD_I4;
5596                         else if (is_ref || t->type == MONO_TYPE_U)
5597                                 opcode = OP_ATOMIC_LOAD_U4;
5598 #endif
5599
5600                         if (opcode) {
5601                                 if (!mono_arch_opcode_supported (opcode))
5602                                         return NULL;
5603
5604                                 MONO_INST_NEW (cfg, ins, opcode);
5605                                 ins->dreg = is_ref ? mono_alloc_ireg_ref (cfg) : (is_float ? mono_alloc_freg (cfg) : mono_alloc_ireg (cfg));
5606                                 ins->sreg1 = args [0]->dreg;
5607                                 ins->backend.memory_barrier_kind = MONO_MEMORY_BARRIER_ACQ;
5608                                 MONO_ADD_INS (cfg->cbb, ins);
5609
5610                                 switch (t->type) {
5611                                 case MONO_TYPE_BOOLEAN:
5612                                 case MONO_TYPE_I1:
5613                                 case MONO_TYPE_U1:
5614                                 case MONO_TYPE_I2:
5615                                 case MONO_TYPE_U2:
5616                                 case MONO_TYPE_I4:
5617                                 case MONO_TYPE_U4:
5618                                         ins->type = STACK_I4;
5619                                         break;
5620                                 case MONO_TYPE_I8:
5621                                 case MONO_TYPE_U8:
5622                                         ins->type = STACK_I8;
5623                                         break;
5624                                 case MONO_TYPE_I:
5625                                 case MONO_TYPE_U:
5626 #if SIZEOF_REGISTER == 8
5627                                         ins->type = STACK_I8;
5628 #else
5629                                         ins->type = STACK_I4;
5630 #endif
5631                                         break;
5632                                 case MONO_TYPE_R4:
5633                                         ins->type = cfg->r4_stack_type;
5634                                         break;
5635                                 case MONO_TYPE_R8:
5636                                         ins->type = STACK_R8;
5637                                         break;
5638                                 default:
5639                                         g_assert (is_ref);
5640                                         ins->type = STACK_OBJ;
5641                                         break;
5642                                 }
5643                         }
5644                 }
5645
5646                 if (!cfg->llvm_only && !strcmp (cmethod->name, "Write") && fsig->param_count == 2) {
5647                         guint32 opcode = 0;
5648                         MonoType *t = fsig->params [0];
5649                         gboolean is_ref;
5650
5651                         g_assert (t->byref);
5652                         is_ref = mini_type_is_reference (&mono_class_from_mono_type (t)->byval_arg);
5653                         if (t->type == MONO_TYPE_I1)
5654                                 opcode = OP_ATOMIC_STORE_I1;
5655                         else if (t->type == MONO_TYPE_U1 || t->type == MONO_TYPE_BOOLEAN)
5656                                 opcode = OP_ATOMIC_STORE_U1;
5657                         else if (t->type == MONO_TYPE_I2)
5658                                 opcode = OP_ATOMIC_STORE_I2;
5659                         else if (t->type == MONO_TYPE_U2)
5660                                 opcode = OP_ATOMIC_STORE_U2;
5661                         else if (t->type == MONO_TYPE_I4)
5662                                 opcode = OP_ATOMIC_STORE_I4;
5663                         else if (t->type == MONO_TYPE_U4)
5664                                 opcode = OP_ATOMIC_STORE_U4;
5665                         else if (t->type == MONO_TYPE_R4)
5666                                 opcode = OP_ATOMIC_STORE_R4;
5667                         else if (t->type == MONO_TYPE_R8)
5668                                 opcode = OP_ATOMIC_STORE_R8;
5669 #if SIZEOF_REGISTER == 8
5670                         else if (t->type == MONO_TYPE_I8 || t->type == MONO_TYPE_I)
5671                                 opcode = OP_ATOMIC_STORE_I8;
5672                         else if (is_ref || t->type == MONO_TYPE_U8 || t->type == MONO_TYPE_U)
5673                                 opcode = OP_ATOMIC_STORE_U8;
5674 #else
5675                         else if (t->type == MONO_TYPE_I)
5676                                 opcode = OP_ATOMIC_STORE_I4;
5677                         else if (is_ref || t->type == MONO_TYPE_U)
5678                                 opcode = OP_ATOMIC_STORE_U4;
5679 #endif
5680
5681                         if (opcode) {
5682                                 if (!mono_arch_opcode_supported (opcode))
5683                                         return NULL;
5684
5685                                 MONO_INST_NEW (cfg, ins, opcode);
5686                                 ins->dreg = args [0]->dreg;
5687                                 ins->sreg1 = args [1]->dreg;
5688                                 ins->backend.memory_barrier_kind = MONO_MEMORY_BARRIER_REL;
5689                                 MONO_ADD_INS (cfg->cbb, ins);
5690
5691                                 if (cfg->gen_write_barriers && is_ref)
5692                                         mini_emit_write_barrier (cfg, args [0], args [1]);
5693                         }
5694                 }
5695
5696                 if (ins)
5697                         return ins;
5698         } else if (cmethod->klass->image == mono_defaults.corlib &&
5699                            (strcmp (cmethod->klass->name_space, "System.Diagnostics") == 0) &&
5700                            (strcmp (cmethod->klass->name, "Debugger") == 0)) {
5701                 if (!strcmp (cmethod->name, "Break") && fsig->param_count == 0) {
5702                         if (mini_should_insert_breakpoint (cfg->method)) {
5703                                 ins = mono_emit_jit_icall (cfg, mono_debugger_agent_user_break, NULL);
5704                         } else {
5705                                 MONO_INST_NEW (cfg, ins, OP_NOP);
5706                                 MONO_ADD_INS (cfg->cbb, ins);
5707                         }
5708                         return ins;
5709                 }
5710         } else if (cmethod->klass->image == mono_defaults.corlib &&
5711                    (strcmp (cmethod->klass->name_space, "System") == 0) &&
5712                    (strcmp (cmethod->klass->name, "Environment") == 0)) {
5713                 if (!strcmp (cmethod->name, "get_IsRunningOnWindows") && fsig->param_count == 0) {
5714 #ifdef TARGET_WIN32
5715                         EMIT_NEW_ICONST (cfg, ins, 1);
5716 #else
5717                         EMIT_NEW_ICONST (cfg, ins, 0);
5718 #endif
5719                 }
5720         } else if (cmethod->klass->image == mono_defaults.corlib &&
5721                            (strcmp (cmethod->klass->name_space, "System.Reflection") == 0) &&
5722                            (strcmp (cmethod->klass->name, "Assembly") == 0)) {
5723                 if (cfg->llvm_only && !strcmp (cmethod->name, "GetExecutingAssembly")) {
5724                         /* No stack walks are currently available, so implement this as an intrinsic */
5725                         MonoInst *assembly_ins;
5726
5727                         EMIT_NEW_AOTCONST (cfg, assembly_ins, MONO_PATCH_INFO_IMAGE, cfg->method->klass->image);
5728                         ins = mono_emit_jit_icall (cfg, mono_get_assembly_object, &assembly_ins);
5729                         return ins;
5730                 }
5731         } else if (cmethod->klass->image == mono_defaults.corlib &&
5732                            (strcmp (cmethod->klass->name_space, "System.Reflection") == 0) &&
5733                            (strcmp (cmethod->klass->name, "MethodBase") == 0)) {
5734                 if (cfg->llvm_only && !strcmp (cmethod->name, "GetCurrentMethod")) {
5735                         /* No stack walks are currently available, so implement this as an intrinsic */
5736                         MonoInst *method_ins;
5737                         MonoMethod *declaring = cfg->method;
5738
5739                         /* This returns the declaring generic method */
5740                         if (declaring->is_inflated)
5741                                 declaring = ((MonoMethodInflated*)cfg->method)->declaring;
5742                         EMIT_NEW_AOTCONST (cfg, method_ins, MONO_PATCH_INFO_METHODCONST, declaring);
5743                         ins = mono_emit_jit_icall (cfg, mono_get_method_object, &method_ins);
5744                         cfg->no_inline = TRUE;
5745                         if (cfg->method != cfg->current_method)
5746                                 inline_failure (cfg, "MethodBase:GetCurrentMethod ()");
5747                         return ins;
5748                 }
5749         } else if (cmethod->klass == mono_defaults.math_class) {
5750                 /* 
5751                  * There is general branchless code for Min/Max, but it does not work for 
5752                  * all inputs:
5753                  * http://everything2.com/?node_id=1051618
5754                  */
5755         } else if (cmethod->klass == mono_defaults.systemtype_class && !strcmp (cmethod->name, "op_Equality")) {
5756                 EMIT_NEW_BIALU (cfg, ins, OP_COMPARE, -1, args [0]->dreg, args [1]->dreg);
5757                 MONO_INST_NEW (cfg, ins, OP_PCEQ);
5758                 ins->dreg = alloc_preg (cfg);
5759                 ins->type = STACK_I4;
5760                 MONO_ADD_INS (cfg->cbb, ins);
5761                 return ins;
5762         } else if (((!strcmp (cmethod->klass->image->assembly->aname.name, "MonoMac") ||
5763                     !strcmp (cmethod->klass->image->assembly->aname.name, "monotouch")) &&
5764                                 !strcmp (cmethod->klass->name_space, "XamCore.ObjCRuntime") &&
5765                                 !strcmp (cmethod->klass->name, "Selector")) ||
5766                            ((!strcmp (cmethod->klass->image->assembly->aname.name, "Xamarin.iOS") ||
5767                                  !strcmp (cmethod->klass->image->assembly->aname.name, "Xamarin.Mac")) &&
5768                                 !strcmp (cmethod->klass->name_space, "ObjCRuntime") &&
5769                                 !strcmp (cmethod->klass->name, "Selector"))
5770                            ) {
5771                 if ((cfg->backend->have_objc_get_selector || cfg->compile_llvm) &&
5772                         !strcmp (cmethod->name, "GetHandle") && fsig->param_count == 1 &&
5773                     (args [0]->opcode == OP_GOT_ENTRY || args [0]->opcode == OP_AOTCONST) &&
5774                     cfg->compile_aot) {
5775                         MonoInst *pi;
5776                         MonoJumpInfoToken *ji;
5777                         char *s;
5778
5779                         if (args [0]->opcode == OP_GOT_ENTRY) {
5780                                 pi = (MonoInst *)args [0]->inst_p1;
5781                                 g_assert (pi->opcode == OP_PATCH_INFO);
5782                                 g_assert (GPOINTER_TO_INT (pi->inst_p1) == MONO_PATCH_INFO_LDSTR);
5783                                 ji = (MonoJumpInfoToken *)pi->inst_p0;
5784                         } else {
5785                                 g_assert (GPOINTER_TO_INT (args [0]->inst_p1) == MONO_PATCH_INFO_LDSTR);
5786                                 ji = (MonoJumpInfoToken *)args [0]->inst_p0;
5787                         }
5788
5789                         NULLIFY_INS (args [0]);
5790
5791                         s = mono_ldstr_utf8 (ji->image, mono_metadata_token_index (ji->token), &cfg->error);
5792                         return_val_if_nok (&cfg->error, NULL);
5793
5794                         MONO_INST_NEW (cfg, ins, OP_OBJC_GET_SELECTOR);
5795                         ins->dreg = mono_alloc_ireg (cfg);
5796                         // FIXME: Leaks
5797                         ins->inst_p0 = s;
5798                         MONO_ADD_INS (cfg->cbb, ins);
5799                         return ins;
5800                 }
5801         } else if (cmethod->klass->image == mono_defaults.corlib &&
5802                         (strcmp (cmethod->klass->name_space, "System.Runtime.InteropServices") == 0) &&
5803                         (strcmp (cmethod->klass->name, "Marshal") == 0)) {
5804                 //Convert Marshal.PtrToStructure<T> of blittable T to direct loads
5805                 if (strcmp (cmethod->name, "PtrToStructure") == 0 &&
5806                                 cmethod->is_inflated &&
5807                                 fsig->param_count == 1 &&
5808                                 !mini_method_check_context_used (cfg, cmethod)) {
5809
5810                         MonoGenericContext *method_context = mono_method_get_context (cmethod);
5811                         MonoType *arg0 = method_context->method_inst->type_argv [0];
5812                         if (mono_type_is_native_blittable (arg0))
5813                                 return mini_emit_memory_load (cfg, arg0, args [0], 0, 0);
5814                 }
5815         }
5816
5817 #ifdef MONO_ARCH_SIMD_INTRINSICS
5818         if (cfg->opt & MONO_OPT_SIMD) {
5819                 ins = mono_emit_simd_intrinsics (cfg, cmethod, fsig, args);
5820                 if (ins)
5821                         return ins;
5822         }
5823 #endif
5824
5825         ins = mono_emit_native_types_intrinsics (cfg, cmethod, fsig, args);
5826         if (ins)
5827                 return ins;
5828
5829         if (COMPILE_LLVM (cfg)) {
5830                 ins = llvm_emit_inst_for_method (cfg, cmethod, fsig, args);
5831                 if (ins)
5832                         return ins;
5833         }
5834
5835         return mono_arch_emit_inst_for_method (cfg, cmethod, fsig, args);
5836 }
5837
5838 /*
5839  * This entry point could be used later for arbitrary method
5840  * redirection.
5841  */
5842 inline static MonoInst*
5843 mini_redirect_call (MonoCompile *cfg, MonoMethod *method,  
5844                                         MonoMethodSignature *signature, MonoInst **args, MonoInst *this_ins)
5845 {
5846         if (method->klass == mono_defaults.string_class) {
5847                 /* managed string allocation support */
5848                 if (strcmp (method->name, "InternalAllocateStr") == 0 && !(cfg->opt & MONO_OPT_SHARED)) {
5849                         MonoInst *iargs [2];
5850                         MonoVTable *vtable = mono_class_vtable (cfg->domain, method->klass);
5851                         MonoMethod *managed_alloc = NULL;
5852
5853                         g_assert (vtable); /*Should not fail since it System.String*/
5854 #ifndef MONO_CROSS_COMPILE
5855                         managed_alloc = mono_gc_get_managed_allocator (method->klass, FALSE, FALSE);
5856 #endif
5857                         if (!managed_alloc)
5858                                 return NULL;
5859                         EMIT_NEW_VTABLECONST (cfg, iargs [0], vtable);
5860                         iargs [1] = args [0];
5861                         return mono_emit_method_call (cfg, managed_alloc, iargs, this_ins);
5862                 }
5863         }
5864         return NULL;
5865 }
5866
5867 static void
5868 mono_save_args (MonoCompile *cfg, MonoMethodSignature *sig, MonoInst **sp)
5869 {
5870         MonoInst *store, *temp;
5871         int i;
5872
5873         for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
5874                 MonoType *argtype = (sig->hasthis && (i == 0)) ? type_from_stack_type (*sp) : sig->params [i - sig->hasthis];
5875
5876                 /*
5877                  * FIXME: We should use *args++ = sp [0], but that would mean the arg
5878                  * would be different than the MonoInst's used to represent arguments, and
5879                  * the ldelema implementation can't deal with that.
5880                  * Solution: When ldelema is used on an inline argument, create a var for 
5881                  * it, emit ldelema on that var, and emit the saving code below in
5882                  * inline_method () if needed.
5883                  */
5884                 temp = mono_compile_create_var (cfg, argtype, OP_LOCAL);
5885                 cfg->args [i] = temp;
5886                 /* This uses cfg->args [i] which is set by the preceeding line */
5887                 EMIT_NEW_ARGSTORE (cfg, store, i, *sp);
5888                 store->cil_code = sp [0]->cil_code;
5889                 sp++;
5890         }
5891 }
5892
5893 #define MONO_INLINE_CALLED_LIMITED_METHODS 1
5894 #define MONO_INLINE_CALLER_LIMITED_METHODS 1
5895
5896 #if (MONO_INLINE_CALLED_LIMITED_METHODS)
5897 static gboolean
5898 check_inline_called_method_name_limit (MonoMethod *called_method)
5899 {
5900         int strncmp_result;
5901         static const char *limit = NULL;
5902         
5903         if (limit == NULL) {
5904                 const char *limit_string = g_getenv ("MONO_INLINE_CALLED_METHOD_NAME_LIMIT");
5905
5906                 if (limit_string != NULL)
5907                         limit = limit_string;
5908                 else
5909                         limit = "";
5910         }
5911
5912         if (limit [0] != '\0') {
5913                 char *called_method_name = mono_method_full_name (called_method, TRUE);
5914
5915                 strncmp_result = strncmp (called_method_name, limit, strlen (limit));
5916                 g_free (called_method_name);
5917         
5918                 //return (strncmp_result <= 0);
5919                 return (strncmp_result == 0);
5920         } else {
5921                 return TRUE;
5922         }
5923 }
5924 #endif
5925
5926 #if (MONO_INLINE_CALLER_LIMITED_METHODS)
5927 static gboolean
5928 check_inline_caller_method_name_limit (MonoMethod *caller_method)
5929 {
5930         int strncmp_result;
5931         static const char *limit = NULL;
5932         
5933         if (limit == NULL) {
5934                 const char *limit_string = g_getenv ("MONO_INLINE_CALLER_METHOD_NAME_LIMIT");
5935                 if (limit_string != NULL) {
5936                         limit = limit_string;
5937                 } else {
5938                         limit = "";
5939                 }
5940         }
5941
5942         if (limit [0] != '\0') {
5943                 char *caller_method_name = mono_method_full_name (caller_method, TRUE);
5944
5945                 strncmp_result = strncmp (caller_method_name, limit, strlen (limit));
5946                 g_free (caller_method_name);
5947         
5948                 //return (strncmp_result <= 0);
5949                 return (strncmp_result == 0);
5950         } else {
5951                 return TRUE;
5952         }
5953 }
5954 #endif
5955
5956 static void
5957 emit_init_rvar (MonoCompile *cfg, int dreg, MonoType *rtype)
5958 {
5959         static double r8_0 = 0.0;
5960         static float r4_0 = 0.0;
5961         MonoInst *ins;
5962         int t;
5963
5964         rtype = mini_get_underlying_type (rtype);
5965         t = rtype->type;
5966
5967         if (rtype->byref) {
5968                 MONO_EMIT_NEW_PCONST (cfg, dreg, NULL);
5969         } else if (t >= MONO_TYPE_BOOLEAN && t <= MONO_TYPE_U4) {
5970                 MONO_EMIT_NEW_ICONST (cfg, dreg, 0);
5971         } else if (t == MONO_TYPE_I8 || t == MONO_TYPE_U8) {
5972                 MONO_EMIT_NEW_I8CONST (cfg, dreg, 0);
5973         } else if (cfg->r4fp && t == MONO_TYPE_R4) {
5974                 MONO_INST_NEW (cfg, ins, OP_R4CONST);
5975                 ins->type = STACK_R4;
5976                 ins->inst_p0 = (void*)&r4_0;
5977                 ins->dreg = dreg;
5978                 MONO_ADD_INS (cfg->cbb, ins);
5979         } else if (t == MONO_TYPE_R4 || t == MONO_TYPE_R8) {
5980                 MONO_INST_NEW (cfg, ins, OP_R8CONST);
5981                 ins->type = STACK_R8;
5982                 ins->inst_p0 = (void*)&r8_0;
5983                 ins->dreg = dreg;
5984                 MONO_ADD_INS (cfg->cbb, ins);
5985         } else if ((t == MONO_TYPE_VALUETYPE) || (t == MONO_TYPE_TYPEDBYREF) ||
5986                    ((t == MONO_TYPE_GENERICINST) && mono_type_generic_inst_is_valuetype (rtype))) {
5987                 MONO_EMIT_NEW_VZERO (cfg, dreg, mono_class_from_mono_type (rtype));
5988         } else if (((t == MONO_TYPE_VAR) || (t == MONO_TYPE_MVAR)) && mini_type_var_is_vt (rtype)) {
5989                 MONO_EMIT_NEW_VZERO (cfg, dreg, mono_class_from_mono_type (rtype));
5990         } else {
5991                 MONO_EMIT_NEW_PCONST (cfg, dreg, NULL);
5992         }
5993 }
5994
5995 static void
5996 emit_dummy_init_rvar (MonoCompile *cfg, int dreg, MonoType *rtype)
5997 {
5998         int t;
5999
6000         rtype = mini_get_underlying_type (rtype);
6001         t = rtype->type;
6002
6003         if (rtype->byref) {
6004                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_PCONST);
6005         } else if (t >= MONO_TYPE_BOOLEAN && t <= MONO_TYPE_U4) {
6006                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_ICONST);
6007         } else if (t == MONO_TYPE_I8 || t == MONO_TYPE_U8) {
6008                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_I8CONST);
6009         } else if (cfg->r4fp && t == MONO_TYPE_R4) {
6010                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_R4CONST);
6011         } else if (t == MONO_TYPE_R4 || t == MONO_TYPE_R8) {
6012                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_R8CONST);
6013         } else if ((t == MONO_TYPE_VALUETYPE) || (t == MONO_TYPE_TYPEDBYREF) ||
6014                    ((t == MONO_TYPE_GENERICINST) && mono_type_generic_inst_is_valuetype (rtype))) {
6015                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_VZERO);
6016         } else if (((t == MONO_TYPE_VAR) || (t == MONO_TYPE_MVAR)) && mini_type_var_is_vt (rtype)) {
6017                 MONO_EMIT_NEW_DUMMY_INIT (cfg, dreg, OP_DUMMY_VZERO);
6018         } else {
6019                 emit_init_rvar (cfg, dreg, rtype);
6020         }
6021 }
6022
6023 /* If INIT is FALSE, emit dummy initialization statements to keep the IR valid */
6024 static void
6025 emit_init_local (MonoCompile *cfg, int local, MonoType *type, gboolean init)
6026 {
6027         MonoInst *var = cfg->locals [local];
6028         if (COMPILE_SOFT_FLOAT (cfg)) {
6029                 MonoInst *store;
6030                 int reg = alloc_dreg (cfg, (MonoStackType)var->type);
6031                 emit_init_rvar (cfg, reg, type);
6032                 EMIT_NEW_LOCSTORE (cfg, store, local, cfg->cbb->last_ins);
6033         } else {
6034                 if (init)
6035                         emit_init_rvar (cfg, var->dreg, type);
6036                 else
6037                         emit_dummy_init_rvar (cfg, var->dreg, type);
6038         }
6039 }
6040
6041 int
6042 mini_inline_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **sp, guchar *ip, guint real_offset, gboolean inline_always)
6043 {
6044         return inline_method (cfg, cmethod, fsig, sp, ip, real_offset, inline_always);
6045 }
6046
6047 /*
6048  * inline_method:
6049  *
6050  * Return the cost of inlining CMETHOD, or zero if it should not be inlined.
6051  */
6052 static int
6053 inline_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **sp,
6054                guchar *ip, guint real_offset, gboolean inline_always)
6055 {
6056         MonoError error;
6057         MonoInst *ins, *rvar = NULL;
6058         MonoMethodHeader *cheader;
6059         MonoBasicBlock *ebblock, *sbblock;
6060         int i, costs;
6061         MonoMethod *prev_inlined_method;
6062         MonoInst **prev_locals, **prev_args;
6063         MonoType **prev_arg_types;
6064         guint prev_real_offset;
6065         GHashTable *prev_cbb_hash;
6066         MonoBasicBlock **prev_cil_offset_to_bb;
6067         MonoBasicBlock *prev_cbb;
6068         const unsigned char *prev_ip;
6069         unsigned char *prev_cil_start;
6070         guint32 prev_cil_offset_to_bb_len;
6071         MonoMethod *prev_current_method;
6072         MonoGenericContext *prev_generic_context;
6073         gboolean ret_var_set, prev_ret_var_set, prev_disable_inline, virtual_ = FALSE;
6074
6075         g_assert (cfg->exception_type == MONO_EXCEPTION_NONE);
6076
6077 #if (MONO_INLINE_CALLED_LIMITED_METHODS)
6078         if ((! inline_always) && ! check_inline_called_method_name_limit (cmethod))
6079                 return 0;
6080 #endif
6081 #if (MONO_INLINE_CALLER_LIMITED_METHODS)
6082         if ((! inline_always) && ! check_inline_caller_method_name_limit (cfg->method))
6083                 return 0;
6084 #endif
6085
6086         if (!fsig)
6087                 fsig = mono_method_signature (cmethod);
6088
6089         if (cfg->verbose_level > 2)
6090                 printf ("INLINE START %p %s -> %s\n", cmethod,  mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
6091
6092         if (!cmethod->inline_info) {
6093                 cfg->stat_inlineable_methods++;
6094                 cmethod->inline_info = 1;
6095         }
6096
6097         /* allocate local variables */
6098         cheader = mono_method_get_header_checked (cmethod, &error);
6099         if (!cheader) {
6100                 if (inline_always) {
6101                         mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
6102                         mono_error_move (&cfg->error, &error);
6103                 } else {
6104                         mono_error_cleanup (&error);
6105                 }
6106                 return 0;
6107         }
6108
6109         /*Must verify before creating locals as it can cause the JIT to assert.*/
6110         if (mono_compile_is_broken (cfg, cmethod, FALSE)) {
6111                 mono_metadata_free_mh (cheader);
6112                 return 0;
6113         }
6114
6115         /* allocate space to store the return value */
6116         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
6117                 rvar = mono_compile_create_var (cfg, fsig->ret, OP_LOCAL);
6118         }
6119
6120         prev_locals = cfg->locals;
6121         cfg->locals = (MonoInst **)mono_mempool_alloc0 (cfg->mempool, cheader->num_locals * sizeof (MonoInst*));
6122         for (i = 0; i < cheader->num_locals; ++i)
6123                 cfg->locals [i] = mono_compile_create_var (cfg, cheader->locals [i], OP_LOCAL);
6124
6125         /* allocate start and end blocks */
6126         /* This is needed so if the inline is aborted, we can clean up */
6127         NEW_BBLOCK (cfg, sbblock);
6128         sbblock->real_offset = real_offset;
6129
6130         NEW_BBLOCK (cfg, ebblock);
6131         ebblock->block_num = cfg->num_bblocks++;
6132         ebblock->real_offset = real_offset;
6133
6134         prev_args = cfg->args;
6135         prev_arg_types = cfg->arg_types;
6136         prev_inlined_method = cfg->inlined_method;
6137         cfg->inlined_method = cmethod;
6138         cfg->ret_var_set = FALSE;
6139         cfg->inline_depth ++;
6140         prev_real_offset = cfg->real_offset;
6141         prev_cbb_hash = cfg->cbb_hash;
6142         prev_cil_offset_to_bb = cfg->cil_offset_to_bb;
6143         prev_cil_offset_to_bb_len = cfg->cil_offset_to_bb_len;
6144         prev_cil_start = cfg->cil_start;
6145         prev_ip = cfg->ip;
6146         prev_cbb = cfg->cbb;
6147         prev_current_method = cfg->current_method;
6148         prev_generic_context = cfg->generic_context;
6149         prev_ret_var_set = cfg->ret_var_set;
6150         prev_disable_inline = cfg->disable_inline;
6151
6152         if (ip && *ip == CEE_CALLVIRT && !(cmethod->flags & METHOD_ATTRIBUTE_STATIC))
6153                 virtual_ = TRUE;
6154
6155         costs = mono_method_to_ir (cfg, cmethod, sbblock, ebblock, rvar, sp, real_offset, virtual_);
6156
6157         ret_var_set = cfg->ret_var_set;
6158
6159         cfg->inlined_method = prev_inlined_method;
6160         cfg->real_offset = prev_real_offset;
6161         cfg->cbb_hash = prev_cbb_hash;
6162         cfg->cil_offset_to_bb = prev_cil_offset_to_bb;
6163         cfg->cil_offset_to_bb_len = prev_cil_offset_to_bb_len;
6164         cfg->cil_start = prev_cil_start;
6165         cfg->ip = prev_ip;
6166         cfg->locals = prev_locals;
6167         cfg->args = prev_args;
6168         cfg->arg_types = prev_arg_types;
6169         cfg->current_method = prev_current_method;
6170         cfg->generic_context = prev_generic_context;
6171         cfg->ret_var_set = prev_ret_var_set;
6172         cfg->disable_inline = prev_disable_inline;
6173         cfg->inline_depth --;
6174
6175         if ((costs >= 0 && costs < 60) || inline_always || (costs >= 0 && (cmethod->iflags & METHOD_IMPL_ATTRIBUTE_AGGRESSIVE_INLINING))) {
6176                 if (cfg->verbose_level > 2)
6177                         printf ("INLINE END %s -> %s\n", mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
6178
6179                 cfg->stat_inlined_methods++;
6180
6181                 /* always add some code to avoid block split failures */
6182                 MONO_INST_NEW (cfg, ins, OP_NOP);
6183                 MONO_ADD_INS (prev_cbb, ins);
6184
6185                 prev_cbb->next_bb = sbblock;
6186                 link_bblock (cfg, prev_cbb, sbblock);
6187
6188                 /* 
6189                  * Get rid of the begin and end bblocks if possible to aid local
6190                  * optimizations.
6191                  */
6192                 if (prev_cbb->out_count == 1)
6193                         mono_merge_basic_blocks (cfg, prev_cbb, sbblock);
6194
6195                 if ((prev_cbb->out_count == 1) && (prev_cbb->out_bb [0]->in_count == 1) && (prev_cbb->out_bb [0] != ebblock))
6196                         mono_merge_basic_blocks (cfg, prev_cbb, prev_cbb->out_bb [0]);
6197
6198                 if ((ebblock->in_count == 1) && ebblock->in_bb [0]->out_count == 1) {
6199                         MonoBasicBlock *prev = ebblock->in_bb [0];
6200
6201                         if (prev->next_bb == ebblock) {
6202                                 mono_merge_basic_blocks (cfg, prev, ebblock);
6203                                 cfg->cbb = prev;
6204                                 if ((prev_cbb->out_count == 1) && (prev_cbb->out_bb [0]->in_count == 1) && (prev_cbb->out_bb [0] == prev)) {
6205                                         mono_merge_basic_blocks (cfg, prev_cbb, prev);
6206                                         cfg->cbb = prev_cbb;
6207                                 }
6208                         } else {
6209                                 /* There could be a bblock after 'prev', and making 'prev' the current bb could cause problems */
6210                                 cfg->cbb = ebblock;
6211                         }
6212                 } else {
6213                         /* 
6214                          * Its possible that the rvar is set in some prev bblock, but not in others.
6215                          * (#1835).
6216                          */
6217                         if (rvar) {
6218                                 MonoBasicBlock *bb;
6219
6220                                 for (i = 0; i < ebblock->in_count; ++i) {
6221                                         bb = ebblock->in_bb [i];
6222
6223                                         if (bb->last_ins && bb->last_ins->opcode == OP_NOT_REACHED) {
6224                                                 cfg->cbb = bb;
6225
6226                                                 emit_init_rvar (cfg, rvar->dreg, fsig->ret);
6227                                         }
6228                                 }
6229                         }
6230
6231                         cfg->cbb = ebblock;
6232                 }
6233
6234                 if (rvar) {
6235                         /*
6236                          * If the inlined method contains only a throw, then the ret var is not 
6237                          * set, so set it to a dummy value.
6238                          */
6239                         if (!ret_var_set)
6240                                 emit_init_rvar (cfg, rvar->dreg, fsig->ret);
6241
6242                         EMIT_NEW_TEMPLOAD (cfg, ins, rvar->inst_c0);
6243                         *sp++ = ins;
6244                 }
6245                 cfg->headers_to_free = g_slist_prepend_mempool (cfg->mempool, cfg->headers_to_free, cheader);
6246                 return costs + 1;
6247         } else {
6248                 if (cfg->verbose_level > 2)
6249                         printf ("INLINE ABORTED %s (cost %d)\n", mono_method_full_name (cmethod, TRUE), costs);
6250                 cfg->exception_type = MONO_EXCEPTION_NONE;
6251
6252                 /* This gets rid of the newly added bblocks */
6253                 cfg->cbb = prev_cbb;
6254         }
6255         cfg->headers_to_free = g_slist_prepend_mempool (cfg->mempool, cfg->headers_to_free, cheader);
6256         return 0;
6257 }
6258
6259 /*
6260  * Some of these comments may well be out-of-date.
6261  * Design decisions: we do a single pass over the IL code (and we do bblock 
6262  * splitting/merging in the few cases when it's required: a back jump to an IL
6263  * address that was not already seen as bblock starting point).
6264  * Code is validated as we go (full verification is still better left to metadata/verify.c).
6265  * Complex operations are decomposed in simpler ones right away. We need to let the 
6266  * arch-specific code peek and poke inside this process somehow (except when the 
6267  * optimizations can take advantage of the full semantic info of coarse opcodes).
6268  * All the opcodes of the form opcode.s are 'normalized' to opcode.
6269  * MonoInst->opcode initially is the IL opcode or some simplification of that 
6270  * (OP_LOAD, OP_STORE). The arch-specific code may rearrange it to an arch-specific 
6271  * opcode with value bigger than OP_LAST.
6272  * At this point the IR can be handed over to an interpreter, a dumb code generator
6273  * or to the optimizing code generator that will translate it to SSA form.
6274  *
6275  * Profiling directed optimizations.
6276  * We may compile by default with few or no optimizations and instrument the code
6277  * or the user may indicate what methods to optimize the most either in a config file
6278  * or through repeated runs where the compiler applies offline the optimizations to 
6279  * each method and then decides if it was worth it.
6280  */
6281
6282 #define CHECK_TYPE(ins) if (!(ins)->type) UNVERIFIED
6283 #define CHECK_STACK(num) if ((sp - stack_start) < (num)) UNVERIFIED
6284 #define CHECK_STACK_OVF(num) if (((sp - stack_start) + (num)) > header->max_stack) UNVERIFIED
6285 #define CHECK_ARG(num) if ((unsigned)(num) >= (unsigned)num_args) UNVERIFIED
6286 #define CHECK_LOCAL(num) if ((unsigned)(num) >= (unsigned)header->num_locals) UNVERIFIED
6287 #define CHECK_OPSIZE(size) if (ip + size > end) UNVERIFIED
6288 #define CHECK_UNVERIFIABLE(cfg) if (cfg->unverifiable) UNVERIFIED
6289 #define CHECK_TYPELOAD(klass) if (!(klass) || mono_class_has_failure (klass)) TYPE_LOAD_ERROR ((klass))
6290
6291 /* offset from br.s -> br like opcodes */
6292 #define BIG_BRANCH_OFFSET 13
6293
6294 static gboolean
6295 ip_in_bb (MonoCompile *cfg, MonoBasicBlock *bb, const guint8* ip)
6296 {
6297         MonoBasicBlock *b = cfg->cil_offset_to_bb [ip - cfg->cil_start];
6298
6299         return b == NULL || b == bb;
6300 }
6301
6302 static int
6303 get_basic_blocks (MonoCompile *cfg, MonoMethodHeader* header, guint real_offset, unsigned char *start, unsigned char *end, unsigned char **pos)
6304 {
6305         unsigned char *ip = start;
6306         unsigned char *target;
6307         int i;
6308         guint cli_addr;
6309         MonoBasicBlock *bblock;
6310         const MonoOpcode *opcode;
6311
6312         while (ip < end) {
6313                 cli_addr = ip - start;
6314                 i = mono_opcode_value ((const guint8 **)&ip, end);
6315                 if (i < 0)
6316                         UNVERIFIED;
6317                 opcode = &mono_opcodes [i];
6318                 switch (opcode->argument) {
6319                 case MonoInlineNone:
6320                         ip++; 
6321                         break;
6322                 case MonoInlineString:
6323                 case MonoInlineType:
6324                 case MonoInlineField:
6325                 case MonoInlineMethod:
6326                 case MonoInlineTok:
6327                 case MonoInlineSig:
6328                 case MonoShortInlineR:
6329                 case MonoInlineI:
6330                         ip += 5;
6331                         break;
6332                 case MonoInlineVar:
6333                         ip += 3;
6334                         break;
6335                 case MonoShortInlineVar:
6336                 case MonoShortInlineI:
6337                         ip += 2;
6338                         break;
6339                 case MonoShortInlineBrTarget:
6340                         target = start + cli_addr + 2 + (signed char)ip [1];
6341                         GET_BBLOCK (cfg, bblock, target);
6342                         ip += 2;
6343                         if (ip < end)
6344                                 GET_BBLOCK (cfg, bblock, ip);
6345                         break;
6346                 case MonoInlineBrTarget:
6347                         target = start + cli_addr + 5 + (gint32)read32 (ip + 1);
6348                         GET_BBLOCK (cfg, bblock, target);
6349                         ip += 5;
6350                         if (ip < end)
6351                                 GET_BBLOCK (cfg, bblock, ip);
6352                         break;
6353                 case MonoInlineSwitch: {
6354                         guint32 n = read32 (ip + 1);
6355                         guint32 j;
6356                         ip += 5;
6357                         cli_addr += 5 + 4 * n;
6358                         target = start + cli_addr;
6359                         GET_BBLOCK (cfg, bblock, target);
6360                         
6361                         for (j = 0; j < n; ++j) {
6362                                 target = start + cli_addr + (gint32)read32 (ip);
6363                                 GET_BBLOCK (cfg, bblock, target);
6364                                 ip += 4;
6365                         }
6366                         break;
6367                 }
6368                 case MonoInlineR:
6369                 case MonoInlineI8:
6370                         ip += 9;
6371                         break;
6372                 default:
6373                         g_assert_not_reached ();
6374                 }
6375
6376                 if (i == CEE_THROW) {
6377                         unsigned char *bb_start = ip - 1;
6378                         
6379                         /* Find the start of the bblock containing the throw */
6380                         bblock = NULL;
6381                         while ((bb_start >= start) && !bblock) {
6382                                 bblock = cfg->cil_offset_to_bb [(bb_start) - start];
6383                                 bb_start --;
6384                         }
6385                         if (bblock)
6386                                 bblock->out_of_line = 1;
6387                 }
6388         }
6389         return 0;
6390 unverified:
6391 exception_exit:
6392         *pos = ip;
6393         return 1;
6394 }
6395
6396 static inline MonoMethod *
6397 mini_get_method_allow_open (MonoMethod *m, guint32 token, MonoClass *klass, MonoGenericContext *context, MonoError *error)
6398 {
6399         MonoMethod *method;
6400
6401         error_init (error);
6402
6403         if (m->wrapper_type != MONO_WRAPPER_NONE) {
6404                 method = (MonoMethod *)mono_method_get_wrapper_data (m, token);
6405                 if (context) {
6406                         method = mono_class_inflate_generic_method_checked (method, context, error);
6407                 }
6408         } else {
6409                 method = mono_get_method_checked (m->klass->image, token, klass, context, error);
6410         }
6411
6412         return method;
6413 }
6414
6415 static inline MonoMethod *
6416 mini_get_method (MonoCompile *cfg, MonoMethod *m, guint32 token, MonoClass *klass, MonoGenericContext *context)
6417 {
6418         MonoError error;
6419         MonoMethod *method = mini_get_method_allow_open (m, token, klass, context, cfg ? &cfg->error : &error);
6420
6421         if (method && cfg && !cfg->gshared && mono_class_is_open_constructed_type (&method->klass->byval_arg)) {
6422                 mono_error_set_bad_image (&cfg->error, cfg->method->klass->image, "Method with open type while not compiling gshared");
6423                 method = NULL;
6424         }
6425
6426         if (!method && !cfg)
6427                 mono_error_cleanup (&error); /* FIXME don't swallow the error */
6428
6429         return method;
6430 }
6431
6432 static inline MonoMethodSignature*
6433 mini_get_signature (MonoMethod *method, guint32 token, MonoGenericContext *context, MonoError *error)
6434 {
6435         MonoMethodSignature *fsig;
6436
6437         error_init (error);
6438         if (method->wrapper_type != MONO_WRAPPER_NONE) {
6439                 fsig = (MonoMethodSignature *)mono_method_get_wrapper_data (method, token);
6440         } else {
6441                 fsig = mono_metadata_parse_signature_checked (method->klass->image, token, error);
6442                 return_val_if_nok (error, NULL);
6443         }
6444         if (context) {
6445                 fsig = mono_inflate_generic_signature(fsig, context, error);
6446         }
6447         return fsig;
6448 }
6449
6450 static MonoMethod*
6451 throw_exception (void)
6452 {
6453         static MonoMethod *method = NULL;
6454
6455         if (!method) {
6456                 MonoSecurityManager *secman = mono_security_manager_get_methods ();
6457                 method = mono_class_get_method_from_name (secman->securitymanager, "ThrowException", 1);
6458         }
6459         g_assert (method);
6460         return method;
6461 }
6462
6463 static void
6464 emit_throw_exception (MonoCompile *cfg, MonoException *ex)
6465 {
6466         MonoMethod *thrower = throw_exception ();
6467         MonoInst *args [1];
6468
6469         EMIT_NEW_PCONST (cfg, args [0], ex);
6470         mono_emit_method_call (cfg, thrower, args, NULL);
6471 }
6472
6473 /*
6474  * Return the original method is a wrapper is specified. We can only access 
6475  * the custom attributes from the original method.
6476  */
6477 static MonoMethod*
6478 get_original_method (MonoMethod *method)
6479 {
6480         if (method->wrapper_type == MONO_WRAPPER_NONE)
6481                 return method;
6482
6483         /* native code (which is like Critical) can call any managed method XXX FIXME XXX to validate all usages */
6484         if (method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED)
6485                 return NULL;
6486
6487         /* in other cases we need to find the original method */
6488         return mono_marshal_method_from_wrapper (method);
6489 }
6490
6491 static void
6492 ensure_method_is_allowed_to_access_field (MonoCompile *cfg, MonoMethod *caller, MonoClassField *field)
6493 {
6494         /* we can't get the coreclr security level on wrappers since they don't have the attributes */
6495         MonoException *ex = mono_security_core_clr_is_field_access_allowed (get_original_method (caller), field);
6496         if (ex)
6497                 emit_throw_exception (cfg, ex);
6498 }
6499
6500 static void
6501 ensure_method_is_allowed_to_call_method (MonoCompile *cfg, MonoMethod *caller, MonoMethod *callee)
6502 {
6503         /* we can't get the coreclr security level on wrappers since they don't have the attributes */
6504         MonoException *ex = mono_security_core_clr_is_call_allowed (get_original_method (caller), callee);
6505         if (ex)
6506                 emit_throw_exception (cfg, ex);
6507 }
6508
6509 /*
6510  * Check that the IL instructions at ip are the array initialization
6511  * sequence and return the pointer to the data and the size.
6512  */
6513 static const char*
6514 initialize_array_data (MonoMethod *method, gboolean aot, unsigned char *ip, MonoClass *klass, guint32 len, int *out_size, guint32 *out_field_token)
6515 {
6516         /*
6517          * newarr[System.Int32]
6518          * dup
6519          * ldtoken field valuetype ...
6520          * call void class [mscorlib]System.Runtime.CompilerServices.RuntimeHelpers::InitializeArray(class [mscorlib]System.Array, valuetype [mscorlib]System.RuntimeFieldHandle)
6521          */
6522         if (ip [0] == CEE_DUP && ip [1] == CEE_LDTOKEN && ip [5] == 0x4 && ip [6] == CEE_CALL) {
6523                 MonoError error;
6524                 guint32 token = read32 (ip + 7);
6525                 guint32 field_token = read32 (ip + 2);
6526                 guint32 field_index = field_token & 0xffffff;
6527                 guint32 rva;
6528                 const char *data_ptr;
6529                 int size = 0;
6530                 MonoMethod *cmethod;
6531                 MonoClass *dummy_class;
6532                 MonoClassField *field = mono_field_from_token_checked (method->klass->image, field_token, &dummy_class, NULL, &error);
6533                 int dummy_align;
6534
6535                 if (!field) {
6536                         mono_error_cleanup (&error); /* FIXME don't swallow the error */
6537                         return NULL;
6538                 }
6539
6540                 *out_field_token = field_token;
6541
6542                 cmethod = mini_get_method (NULL, method, token, NULL, NULL);
6543                 if (!cmethod)
6544                         return NULL;
6545                 if (strcmp (cmethod->name, "InitializeArray") || strcmp (cmethod->klass->name, "RuntimeHelpers") || cmethod->klass->image != mono_defaults.corlib)
6546                         return NULL;
6547                 switch (mini_get_underlying_type (&klass->byval_arg)->type) {
6548                 case MONO_TYPE_I1:
6549                 case MONO_TYPE_U1:
6550                         size = 1; break;
6551                 /* we need to swap on big endian, so punt. Should we handle R4 and R8 as well? */
6552 #if TARGET_BYTE_ORDER == G_LITTLE_ENDIAN
6553                 case MONO_TYPE_I2:
6554                 case MONO_TYPE_U2:
6555                         size = 2; break;
6556                 case MONO_TYPE_I4:
6557                 case MONO_TYPE_U4:
6558                 case MONO_TYPE_R4:
6559                         size = 4; break;
6560                 case MONO_TYPE_R8:
6561                 case MONO_TYPE_I8:
6562                 case MONO_TYPE_U8:
6563                         size = 8; break;
6564 #endif
6565                 default:
6566                         return NULL;
6567                 }
6568                 size *= len;
6569                 if (size > mono_type_size (field->type, &dummy_align))
6570                     return NULL;
6571                 *out_size = size;
6572                 /*g_print ("optimized in %s: size: %d, numelems: %d\n", method->name, size, newarr->inst_newa_len->inst_c0);*/
6573                 if (!image_is_dynamic (method->klass->image)) {
6574                         field_index = read32 (ip + 2) & 0xffffff;
6575                         mono_metadata_field_info (method->klass->image, field_index - 1, NULL, &rva, NULL);
6576                         data_ptr = mono_image_rva_map (method->klass->image, rva);
6577                         /*g_print ("field: 0x%08x, rva: %d, rva_ptr: %p\n", read32 (ip + 2), rva, data_ptr);*/
6578                         /* for aot code we do the lookup on load */
6579                         if (aot && data_ptr)
6580                                 return (const char *)GUINT_TO_POINTER (rva);
6581                 } else {
6582                         /*FIXME is it possible to AOT a SRE assembly not meant to be saved? */ 
6583                         g_assert (!aot);
6584                         data_ptr = mono_field_get_data (field);
6585                 }
6586                 return data_ptr;
6587         }
6588         return NULL;
6589 }
6590
6591 static void
6592 set_exception_type_from_invalid_il (MonoCompile *cfg, MonoMethod *method, unsigned char *ip)
6593 {
6594         MonoError error;
6595         char *method_fname = mono_method_full_name (method, TRUE);
6596         char *method_code;
6597         MonoMethodHeader *header = mono_method_get_header_checked (method, &error);
6598
6599         if (!header) {
6600                 method_code = g_strdup_printf ("could not parse method body due to %s", mono_error_get_message (&error));
6601                 mono_error_cleanup (&error);
6602         } else if (header->code_size == 0)
6603                 method_code = g_strdup ("method body is empty.");
6604         else
6605                 method_code = mono_disasm_code_one (NULL, method, ip, NULL);
6606         mono_cfg_set_exception_invalid_program (cfg, g_strdup_printf ("Invalid IL code in %s: %s\n", method_fname, method_code));
6607         g_free (method_fname);
6608         g_free (method_code);
6609         cfg->headers_to_free = g_slist_prepend_mempool (cfg->mempool, cfg->headers_to_free, header);
6610 }
6611
6612 static guint32
6613 mono_type_to_stloc_coerce (MonoType *type)
6614 {
6615         if (type->byref)
6616                 return 0;
6617
6618         type = mini_get_underlying_type (type);
6619 handle_enum:
6620         switch (type->type) {
6621         case MONO_TYPE_I1:
6622                 return OP_ICONV_TO_I1;
6623         case MONO_TYPE_U1:
6624                 return OP_ICONV_TO_U1;
6625         case MONO_TYPE_I2:
6626                 return OP_ICONV_TO_I2;
6627         case MONO_TYPE_U2:
6628                 return OP_ICONV_TO_U2;
6629         case MONO_TYPE_I4:
6630         case MONO_TYPE_U4:
6631         case MONO_TYPE_I:
6632         case MONO_TYPE_U:
6633         case MONO_TYPE_PTR:
6634         case MONO_TYPE_FNPTR:
6635         case MONO_TYPE_CLASS:
6636         case MONO_TYPE_STRING:
6637         case MONO_TYPE_OBJECT:
6638         case MONO_TYPE_SZARRAY:
6639         case MONO_TYPE_ARRAY:
6640         case MONO_TYPE_I8:
6641         case MONO_TYPE_U8:
6642         case MONO_TYPE_R4:
6643         case MONO_TYPE_R8:
6644         case MONO_TYPE_TYPEDBYREF:
6645         case MONO_TYPE_GENERICINST:
6646                 return 0;
6647         case MONO_TYPE_VALUETYPE:
6648                 if (type->data.klass->enumtype) {
6649                         type = mono_class_enum_basetype (type->data.klass);
6650                         goto handle_enum;
6651                 }
6652                 return 0;
6653         case MONO_TYPE_VAR:
6654         case MONO_TYPE_MVAR: //TODO I believe we don't need to handle gsharedvt as there won't be match and, for example, u1 is not covariant to u32
6655                 return 0;
6656         default:
6657                 g_error ("unknown type 0x%02x in mono_type_to_stloc_coerce", type->type);
6658         }
6659         return -1;
6660 }
6661
6662 static void
6663 emit_stloc_ir (MonoCompile *cfg, MonoInst **sp, MonoMethodHeader *header, int n)
6664 {
6665         MonoInst *ins;
6666         guint32 coerce_op = mono_type_to_stloc_coerce (header->locals [n]);
6667
6668         if (coerce_op) {
6669                 if (cfg->cbb->last_ins == sp [0] && sp [0]->opcode == coerce_op) {
6670                         if (cfg->verbose_level > 2)
6671                                 printf ("Found existing coercing is enough for stloc\n");
6672                 } else {
6673                         MONO_INST_NEW (cfg, ins, coerce_op);
6674                         ins->dreg = alloc_ireg (cfg);
6675                         ins->sreg1 = sp [0]->dreg;
6676                         ins->type = STACK_I4;
6677                         ins->klass = mono_class_from_mono_type (header->locals [n]);
6678                         MONO_ADD_INS (cfg->cbb, ins);
6679                         *sp = mono_decompose_opcode (cfg, ins);
6680                 }
6681         }
6682
6683
6684         guint32 opcode = mono_type_to_regmove (cfg, header->locals [n]);
6685         if ((opcode == OP_MOVE) && cfg->cbb->last_ins == sp [0]  &&
6686                         ((sp [0]->opcode == OP_ICONST) || (sp [0]->opcode == OP_I8CONST))) {
6687                 /* Optimize reg-reg moves away */
6688                 /* 
6689                  * Can't optimize other opcodes, since sp[0] might point to
6690                  * the last ins of a decomposed opcode.
6691                  */
6692                 sp [0]->dreg = (cfg)->locals [n]->dreg;
6693         } else {
6694                 EMIT_NEW_LOCSTORE (cfg, ins, n, *sp);
6695         }
6696 }
6697
6698 static void
6699 emit_starg_ir (MonoCompile *cfg, MonoInst **sp, int n)
6700 {
6701         MonoInst *ins;
6702         guint32 coerce_op = mono_type_to_stloc_coerce (cfg->arg_types [n]);
6703
6704         if (coerce_op) {
6705                 if (cfg->cbb->last_ins == sp [0] && sp [0]->opcode == coerce_op) {
6706                         if (cfg->verbose_level > 2)
6707                                 printf ("Found existing coercing is enough for starg\n");
6708                 } else {
6709                         MONO_INST_NEW (cfg, ins, coerce_op);
6710                         ins->dreg = alloc_ireg (cfg);
6711                         ins->sreg1 = sp [0]->dreg;
6712                         ins->type = STACK_I4;
6713                         ins->klass = mono_class_from_mono_type (cfg->arg_types [n]);
6714                         MONO_ADD_INS (cfg->cbb, ins);
6715                         *sp = mono_decompose_opcode (cfg, ins);
6716                 }
6717         }
6718
6719         EMIT_NEW_ARGSTORE (cfg, ins, n, *sp);
6720 }
6721
6722 /*
6723  * ldloca inhibits many optimizations so try to get rid of it in common
6724  * cases.
6725  */
6726 static inline unsigned char *
6727 emit_optimized_ldloca_ir (MonoCompile *cfg, unsigned char *ip, unsigned char *end, int size)
6728 {
6729         int local, token;
6730         MonoClass *klass;
6731         MonoType *type;
6732
6733         if (size == 1) {
6734                 local = ip [1];
6735                 ip += 2;
6736         } else {
6737                 local = read16 (ip + 2);
6738                 ip += 4;
6739         }
6740         
6741         if (ip + 6 < end && (ip [0] == CEE_PREFIX1) && (ip [1] == CEE_INITOBJ) && ip_in_bb (cfg, cfg->cbb, ip + 1)) {
6742                 /* From the INITOBJ case */
6743                 token = read32 (ip + 2);
6744                 klass = mini_get_class (cfg->current_method, token, cfg->generic_context);
6745                 CHECK_TYPELOAD (klass);
6746                 type = mini_get_underlying_type (&klass->byval_arg);
6747                 emit_init_local (cfg, local, type, TRUE);
6748                 return ip + 6;
6749         }
6750  exception_exit:
6751         return NULL;
6752 }
6753
6754 static MonoInst*
6755 emit_llvmonly_virtual_call (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, int context_used, MonoInst **sp)
6756 {
6757         MonoInst *icall_args [16];
6758         MonoInst *call_target, *ins, *vtable_ins;
6759         int arg_reg, this_reg, vtable_reg;
6760         gboolean is_iface = mono_class_is_interface (cmethod->klass);
6761         gboolean is_gsharedvt = cfg->gsharedvt && mini_is_gsharedvt_variable_signature (fsig);
6762         gboolean variant_iface = FALSE;
6763         guint32 slot;
6764         int offset;
6765         gboolean special_array_interface = cmethod->klass->is_array_special_interface;
6766
6767         /*
6768          * In llvm-only mode, vtables contain function descriptors instead of
6769          * method addresses/trampolines.
6770          */
6771         MONO_EMIT_NULL_CHECK (cfg, sp [0]->dreg);
6772
6773         if (is_iface)
6774                 slot = mono_method_get_imt_slot (cmethod);
6775         else
6776                 slot = mono_method_get_vtable_index (cmethod);
6777
6778         this_reg = sp [0]->dreg;
6779
6780         if (is_iface && mono_class_has_variant_generic_params (cmethod->klass))
6781                 variant_iface = TRUE;
6782
6783         if (!fsig->generic_param_count && !is_iface && !is_gsharedvt) {
6784                 /*
6785                  * The simplest case, a normal virtual call.
6786                  */
6787                 int slot_reg = alloc_preg (cfg);
6788                 int addr_reg = alloc_preg (cfg);
6789                 int arg_reg = alloc_preg (cfg);
6790                 MonoBasicBlock *non_null_bb;
6791
6792                 vtable_reg = alloc_preg (cfg);
6793                 EMIT_NEW_LOAD_MEMBASE (cfg, vtable_ins, OP_LOAD_MEMBASE, vtable_reg, this_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
6794                 offset = MONO_STRUCT_OFFSET (MonoVTable, vtable) + (slot * SIZEOF_VOID_P);
6795
6796                 /* Load the vtable slot, which contains a function descriptor. */
6797                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, slot_reg, vtable_reg, offset);
6798
6799                 NEW_BBLOCK (cfg, non_null_bb);
6800
6801                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, slot_reg, 0);
6802                 cfg->cbb->last_ins->flags |= MONO_INST_LIKELY;
6803                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, non_null_bb);
6804
6805                 /* Slow path */
6806                 // FIXME: Make the wrapper use the preserveall cconv
6807                 // FIXME: Use one icall per slot for small slot numbers ?
6808                 icall_args [0] = vtable_ins;
6809                 EMIT_NEW_ICONST (cfg, icall_args [1], slot);
6810                 /* Make the icall return the vtable slot value to save some code space */
6811                 ins = mono_emit_jit_icall (cfg, mono_init_vtable_slot, icall_args);
6812                 ins->dreg = slot_reg;
6813                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, non_null_bb);
6814
6815                 /* Fastpath */
6816                 MONO_START_BB (cfg, non_null_bb);
6817                 /* Load the address + arg from the vtable slot */
6818                 EMIT_NEW_LOAD_MEMBASE (cfg, call_target, OP_LOAD_MEMBASE, addr_reg, slot_reg, 0);
6819                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, arg_reg, slot_reg, SIZEOF_VOID_P);
6820
6821                 return emit_extra_arg_calli (cfg, fsig, sp, arg_reg, call_target);
6822         }
6823
6824         if (!fsig->generic_param_count && is_iface && !variant_iface && !is_gsharedvt && !special_array_interface) {
6825                 /*
6826                  * A simple interface call
6827                  *
6828                  * We make a call through an imt slot to obtain the function descriptor we need to call.
6829                  * The imt slot contains a function descriptor for a runtime function + arg.
6830                  */
6831                 int slot_reg = alloc_preg (cfg);
6832                 int addr_reg = alloc_preg (cfg);
6833                 int arg_reg = alloc_preg (cfg);
6834                 MonoInst *thunk_addr_ins, *thunk_arg_ins, *ftndesc_ins;
6835
6836                 vtable_reg = alloc_preg (cfg);
6837                 EMIT_NEW_LOAD_MEMBASE (cfg, vtable_ins, OP_LOAD_MEMBASE, vtable_reg, this_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
6838                 offset = ((gint32)slot - MONO_IMT_SIZE) * SIZEOF_VOID_P;
6839
6840                 /*
6841                  * The slot is already initialized when the vtable is created so there is no need
6842                  * to check it here.
6843                  */
6844
6845                 /* Load the imt slot, which contains a function descriptor. */
6846                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, slot_reg, vtable_reg, offset);
6847
6848                 /* Load the address + arg of the imt thunk from the imt slot */
6849                 EMIT_NEW_LOAD_MEMBASE (cfg, thunk_addr_ins, OP_LOAD_MEMBASE, addr_reg, slot_reg, 0);
6850                 EMIT_NEW_LOAD_MEMBASE (cfg, thunk_arg_ins, OP_LOAD_MEMBASE, arg_reg, slot_reg, SIZEOF_VOID_P);
6851                 /*
6852                  * IMT thunks in llvm-only mode are C functions which take an info argument
6853                  * plus the imt method and return the ftndesc to call.
6854                  */
6855                 icall_args [0] = thunk_arg_ins;
6856                 icall_args [1] = emit_get_rgctx_method (cfg, context_used,
6857                                                                                                 cmethod, MONO_RGCTX_INFO_METHOD);
6858                 ftndesc_ins = mini_emit_calli (cfg, helper_sig_llvmonly_imt_trampoline, icall_args, thunk_addr_ins, NULL, NULL);
6859
6860                 return emit_llvmonly_calli (cfg, fsig, sp, ftndesc_ins);
6861         }
6862
6863         if ((fsig->generic_param_count || variant_iface || special_array_interface) && !is_gsharedvt) {
6864                 /*
6865                  * This is similar to the interface case, the vtable slot points to an imt thunk which is
6866                  * dynamically extended as more instantiations are discovered.
6867                  * This handles generic virtual methods both on classes and interfaces.
6868                  */
6869                 int slot_reg = alloc_preg (cfg);
6870                 int addr_reg = alloc_preg (cfg);
6871                 int arg_reg = alloc_preg (cfg);
6872                 int ftndesc_reg = alloc_preg (cfg);
6873                 MonoInst *thunk_addr_ins, *thunk_arg_ins, *ftndesc_ins;
6874                 MonoBasicBlock *slowpath_bb, *end_bb;
6875
6876                 NEW_BBLOCK (cfg, slowpath_bb);
6877                 NEW_BBLOCK (cfg, end_bb);
6878
6879                 vtable_reg = alloc_preg (cfg);
6880                 EMIT_NEW_LOAD_MEMBASE (cfg, vtable_ins, OP_LOAD_MEMBASE, vtable_reg, this_reg, MONO_STRUCT_OFFSET (MonoObject, vtable));
6881                 if (is_iface)
6882                         offset = ((gint32)slot - MONO_IMT_SIZE) * SIZEOF_VOID_P;
6883                 else
6884                         offset = MONO_STRUCT_OFFSET (MonoVTable, vtable) + (slot * SIZEOF_VOID_P);
6885
6886                 /* Load the slot, which contains a function descriptor. */
6887                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, slot_reg, vtable_reg, offset);
6888
6889                 /* These slots are not initialized, so fall back to the slow path until they are initialized */
6890                 /* That happens when mono_method_add_generic_virtual_invocation () creates an IMT thunk */
6891                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, slot_reg, 0);
6892                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, slowpath_bb);
6893
6894                 /* Fastpath */
6895                 /* Same as with iface calls */
6896                 EMIT_NEW_LOAD_MEMBASE (cfg, thunk_addr_ins, OP_LOAD_MEMBASE, addr_reg, slot_reg, 0);
6897                 EMIT_NEW_LOAD_MEMBASE (cfg, thunk_arg_ins, OP_LOAD_MEMBASE, arg_reg, slot_reg, SIZEOF_VOID_P);
6898                 icall_args [0] = thunk_arg_ins;
6899                 icall_args [1] = emit_get_rgctx_method (cfg, context_used,
6900                                                                                                 cmethod, MONO_RGCTX_INFO_METHOD);
6901                 ftndesc_ins = mini_emit_calli (cfg, helper_sig_llvmonly_imt_trampoline, icall_args, thunk_addr_ins, NULL, NULL);
6902                 ftndesc_ins->dreg = ftndesc_reg;
6903                 /*
6904                  * Unlike normal iface calls, these imt thunks can return NULL, i.e. when they are passed an instantiation
6905                  * they don't know about yet. Fall back to the slowpath in that case.
6906                  */
6907                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, ftndesc_reg, 0);
6908                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, slowpath_bb);
6909
6910                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
6911
6912                 /* Slowpath */
6913                 MONO_START_BB (cfg, slowpath_bb);
6914                 icall_args [0] = vtable_ins;
6915                 EMIT_NEW_ICONST (cfg, icall_args [1], slot);
6916                 icall_args [2] = emit_get_rgctx_method (cfg, context_used,
6917                                                                                                 cmethod, MONO_RGCTX_INFO_METHOD);
6918                 if (is_iface)
6919                         ftndesc_ins = mono_emit_jit_icall (cfg, mono_resolve_generic_virtual_iface_call, icall_args);
6920                 else
6921                         ftndesc_ins = mono_emit_jit_icall (cfg, mono_resolve_generic_virtual_call, icall_args);
6922                 ftndesc_ins->dreg = ftndesc_reg;
6923                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
6924
6925                 /* Common case */
6926                 MONO_START_BB (cfg, end_bb);
6927                 return emit_llvmonly_calli (cfg, fsig, sp, ftndesc_ins);
6928         }
6929
6930         /*
6931          * Non-optimized cases
6932          */
6933         icall_args [0] = sp [0];
6934         EMIT_NEW_ICONST (cfg, icall_args [1], slot);
6935
6936         icall_args [2] = emit_get_rgctx_method (cfg, context_used,
6937                                                                                         cmethod, MONO_RGCTX_INFO_METHOD);
6938
6939         arg_reg = alloc_preg (cfg);
6940         MONO_EMIT_NEW_PCONST (cfg, arg_reg, NULL);
6941         EMIT_NEW_VARLOADA_VREG (cfg, icall_args [3], arg_reg, &mono_defaults.int_class->byval_arg);
6942
6943         g_assert (is_gsharedvt);
6944         if (is_iface)
6945                 call_target = mono_emit_jit_icall (cfg, mono_resolve_iface_call_gsharedvt, icall_args);
6946         else
6947                 call_target = mono_emit_jit_icall (cfg, mono_resolve_vcall_gsharedvt, icall_args);
6948
6949         /*
6950          * Pass the extra argument even if the callee doesn't receive it, most
6951          * calling conventions allow this.
6952          */
6953         return emit_extra_arg_calli (cfg, fsig, sp, arg_reg, call_target);
6954 }
6955
6956 static gboolean
6957 is_exception_class (MonoClass *klass)
6958 {
6959         while (klass) {
6960                 if (klass == mono_defaults.exception_class)
6961                         return TRUE;
6962                 klass = klass->parent;
6963         }
6964         return FALSE;
6965 }
6966
6967 /*
6968  * is_jit_optimizer_disabled:
6969  *
6970  *   Determine whenever M's assembly has a DebuggableAttribute with the
6971  * IsJITOptimizerDisabled flag set.
6972  */
6973 static gboolean
6974 is_jit_optimizer_disabled (MonoMethod *m)
6975 {
6976         MonoError error;
6977         MonoAssembly *ass = m->klass->image->assembly;
6978         MonoCustomAttrInfo* attrs;
6979         MonoClass *klass;
6980         int i;
6981         gboolean val = FALSE;
6982
6983         g_assert (ass);
6984         if (ass->jit_optimizer_disabled_inited)
6985                 return ass->jit_optimizer_disabled;
6986
6987         klass = mono_class_try_get_debuggable_attribute_class ();
6988
6989         if (!klass) {
6990                 /* Linked away */
6991                 ass->jit_optimizer_disabled = FALSE;
6992                 mono_memory_barrier ();
6993                 ass->jit_optimizer_disabled_inited = TRUE;
6994                 return FALSE;
6995         }
6996
6997         attrs = mono_custom_attrs_from_assembly_checked (ass, FALSE, &error);
6998         mono_error_cleanup (&error); /* FIXME don't swallow the error */
6999         if (attrs) {
7000                 for (i = 0; i < attrs->num_attrs; ++i) {
7001                         MonoCustomAttrEntry *attr = &attrs->attrs [i];
7002                         const gchar *p;
7003                         MonoMethodSignature *sig;
7004
7005                         if (!attr->ctor || attr->ctor->klass != klass)
7006                                 continue;
7007                         /* Decode the attribute. See reflection.c */
7008                         p = (const char*)attr->data;
7009                         g_assert (read16 (p) == 0x0001);
7010                         p += 2;
7011
7012                         // FIXME: Support named parameters
7013                         sig = mono_method_signature (attr->ctor);
7014                         if (sig->param_count != 2 || sig->params [0]->type != MONO_TYPE_BOOLEAN || sig->params [1]->type != MONO_TYPE_BOOLEAN)
7015                                 continue;
7016                         /* Two boolean arguments */
7017                         p ++;
7018                         val = *p;
7019                 }
7020                 mono_custom_attrs_free (attrs);
7021         }
7022
7023         ass->jit_optimizer_disabled = val;
7024         mono_memory_barrier ();
7025         ass->jit_optimizer_disabled_inited = TRUE;
7026
7027         return val;
7028 }
7029
7030 static gboolean
7031 is_supported_tail_call (MonoCompile *cfg, MonoMethod *method, MonoMethod *cmethod, MonoMethodSignature *fsig, int call_opcode)
7032 {
7033         gboolean supported_tail_call;
7034         int i;
7035
7036         supported_tail_call = mono_arch_tail_call_supported (cfg, mono_method_signature (method), mono_method_signature (cmethod));
7037
7038         for (i = 0; i < fsig->param_count; ++i) {
7039                 if (fsig->params [i]->byref || fsig->params [i]->type == MONO_TYPE_PTR || fsig->params [i]->type == MONO_TYPE_FNPTR)
7040                         /* These can point to the current method's stack */
7041                         supported_tail_call = FALSE;
7042         }
7043         if (fsig->hasthis && cmethod->klass->valuetype)
7044                 /* this might point to the current method's stack */
7045                 supported_tail_call = FALSE;
7046         if (cmethod->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)
7047                 supported_tail_call = FALSE;
7048         if (cfg->method->save_lmf)
7049                 supported_tail_call = FALSE;
7050         if (cmethod->wrapper_type && cmethod->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
7051                 supported_tail_call = FALSE;
7052         if (call_opcode != CEE_CALL)
7053                 supported_tail_call = FALSE;
7054
7055         /* Debugging support */
7056 #if 0
7057         if (supported_tail_call) {
7058                 if (!mono_debug_count ())
7059                         supported_tail_call = FALSE;
7060         }
7061 #endif
7062
7063         return supported_tail_call;
7064 }
7065
7066 /*
7067  * handle_ctor_call:
7068  *
7069  *   Handle calls made to ctors from NEWOBJ opcodes.
7070  */
7071 static void
7072 handle_ctor_call (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, int context_used,
7073                                   MonoInst **sp, guint8 *ip, int *inline_costs)
7074 {
7075         MonoInst *vtable_arg = NULL, *callvirt_this_arg = NULL, *ins;
7076
7077         if (cmethod->klass->valuetype && mono_class_generic_sharing_enabled (cmethod->klass) &&
7078                                         mono_method_is_generic_sharable (cmethod, TRUE)) {
7079                 if (cmethod->is_inflated && mono_method_get_context (cmethod)->method_inst) {
7080                         mono_class_vtable (cfg->domain, cmethod->klass);
7081                         CHECK_TYPELOAD (cmethod->klass);
7082
7083                         vtable_arg = emit_get_rgctx_method (cfg, context_used,
7084                                                                                                 cmethod, MONO_RGCTX_INFO_METHOD_RGCTX);
7085                 } else {
7086                         if (context_used) {
7087                                 vtable_arg = mini_emit_get_rgctx_klass (cfg, context_used,
7088                                                                                                    cmethod->klass, MONO_RGCTX_INFO_VTABLE);
7089                         } else {
7090                                 MonoVTable *vtable = mono_class_vtable (cfg->domain, cmethod->klass);
7091
7092                                 CHECK_TYPELOAD (cmethod->klass);
7093                                 EMIT_NEW_VTABLECONST (cfg, vtable_arg, vtable);
7094                         }
7095                 }
7096         }
7097
7098         /* Avoid virtual calls to ctors if possible */
7099         if (mono_class_is_marshalbyref (cmethod->klass))
7100                 callvirt_this_arg = sp [0];
7101
7102         if (cmethod && (cfg->opt & MONO_OPT_INTRINS) && (ins = mini_emit_inst_for_ctor (cfg, cmethod, fsig, sp))) {
7103                 g_assert (MONO_TYPE_IS_VOID (fsig->ret));
7104                 CHECK_CFG_EXCEPTION;
7105         } else if ((cfg->opt & MONO_OPT_INLINE) && cmethod && !context_used && !vtable_arg &&
7106                            mono_method_check_inlining (cfg, cmethod) &&
7107                            !mono_class_is_subclass_of (cmethod->klass, mono_defaults.exception_class, FALSE)) {
7108                 int costs;
7109
7110                 if ((costs = inline_method (cfg, cmethod, fsig, sp, ip, cfg->real_offset, FALSE))) {
7111                         cfg->real_offset += 5;
7112
7113                         *inline_costs += costs - 5;
7114                 } else {
7115                         INLINE_FAILURE ("inline failure");
7116                         // FIXME-VT: Clean this up
7117                         if (cfg->gsharedvt && mini_is_gsharedvt_signature (fsig))
7118                                 GSHAREDVT_FAILURE(*ip);
7119                         mono_emit_method_call_full (cfg, cmethod, fsig, FALSE, sp, callvirt_this_arg, NULL, NULL);
7120                 }
7121         } else if (cfg->gsharedvt && mini_is_gsharedvt_signature (fsig)) {
7122                 MonoInst *addr;
7123
7124                 addr = emit_get_rgctx_gsharedvt_call (cfg, context_used, fsig, cmethod, MONO_RGCTX_INFO_METHOD_GSHAREDVT_OUT_TRAMPOLINE);
7125
7126                 if (cfg->llvm_only) {
7127                         // FIXME: Avoid initializing vtable_arg
7128                         emit_llvmonly_calli (cfg, fsig, sp, addr);
7129                 } else {
7130                         mini_emit_calli (cfg, fsig, sp, addr, NULL, vtable_arg);
7131                 }
7132         } else if (context_used &&
7133                            ((!mono_method_is_generic_sharable_full (cmethod, TRUE, FALSE, FALSE) ||
7134                                  !mono_class_generic_sharing_enabled (cmethod->klass)) || cfg->gsharedvt)) {
7135                 MonoInst *cmethod_addr;
7136
7137                 /* Generic calls made out of gsharedvt methods cannot be patched, so use an indirect call */
7138
7139                 if (cfg->llvm_only) {
7140                         MonoInst *addr = emit_get_rgctx_method (cfg, context_used, cmethod,
7141                                                                                                         MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
7142                         emit_llvmonly_calli (cfg, fsig, sp, addr);
7143                 } else {
7144                         cmethod_addr = emit_get_rgctx_method (cfg, context_used,
7145                                                                                                   cmethod, MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
7146
7147                         mini_emit_calli (cfg, fsig, sp, cmethod_addr, NULL, vtable_arg);
7148                 }
7149         } else {
7150                 INLINE_FAILURE ("ctor call");
7151                 ins = mono_emit_method_call_full (cfg, cmethod, fsig, FALSE, sp,
7152                                                                                   callvirt_this_arg, NULL, vtable_arg);
7153         }
7154  exception_exit:
7155         return;
7156 }
7157
7158 static void
7159 emit_setret (MonoCompile *cfg, MonoInst *val)
7160 {
7161         MonoType *ret_type = mini_get_underlying_type (mono_method_signature (cfg->method)->ret);
7162         MonoInst *ins;
7163
7164         if (mini_type_to_stind (cfg, ret_type) == CEE_STOBJ) {
7165                 MonoInst *ret_addr;
7166
7167                 if (!cfg->vret_addr) {
7168                         EMIT_NEW_VARSTORE (cfg, ins, cfg->ret, ret_type, val);
7169                 } else {
7170                         EMIT_NEW_RETLOADA (cfg, ret_addr);
7171
7172                         EMIT_NEW_STORE_MEMBASE (cfg, ins, OP_STOREV_MEMBASE, ret_addr->dreg, 0, val->dreg);
7173                         ins->klass = mono_class_from_mono_type (ret_type);
7174                 }
7175         } else {
7176 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
7177                 if (COMPILE_SOFT_FLOAT (cfg) && !ret_type->byref && ret_type->type == MONO_TYPE_R4) {
7178                         MonoInst *iargs [1];
7179                         MonoInst *conv;
7180
7181                         iargs [0] = val;
7182                         conv = mono_emit_jit_icall (cfg, mono_fload_r4_arg, iargs);
7183                         mono_arch_emit_setret (cfg, cfg->method, conv);
7184                 } else {
7185                         mono_arch_emit_setret (cfg, cfg->method, val);
7186                 }
7187 #else
7188                 mono_arch_emit_setret (cfg, cfg->method, val);
7189 #endif
7190         }
7191 }
7192
7193 /*
7194  * mono_method_to_ir:
7195  *
7196  * Translate the .net IL into linear IR.
7197  *
7198  * @start_bblock: if not NULL, the starting basic block, used during inlining.
7199  * @end_bblock: if not NULL, the ending basic block, used during inlining.
7200  * @return_var: if not NULL, the place where the return value is stored, used during inlining.   
7201  * @inline_args: if not NULL, contains the arguments to the inline call
7202  * @inline_offset: if not zero, the real offset from the inline call, or zero otherwise.
7203  * @is_virtual_call: whether this method is being called as a result of a call to callvirt
7204  *
7205  * This method is used to turn ECMA IL into Mono's internal Linear IR
7206  * reprensetation.  It is used both for entire methods, as well as
7207  * inlining existing methods.  In the former case, the @start_bblock,
7208  * @end_bblock, @return_var, @inline_args are all set to NULL, and the
7209  * inline_offset is set to zero.
7210  * 
7211  * Returns: the inline cost, or -1 if there was an error processing this method.
7212  */
7213 int
7214 mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_bblock, MonoBasicBlock *end_bblock, 
7215                    MonoInst *return_var, MonoInst **inline_args, 
7216                    guint inline_offset, gboolean is_virtual_call)
7217 {
7218         MonoError error;
7219         MonoInst *ins, **sp, **stack_start;
7220         MonoBasicBlock *tblock = NULL, *init_localsbb = NULL;
7221         MonoSimpleBasicBlock *bb = NULL, *original_bb = NULL;
7222         MonoMethod *cmethod, *method_definition;
7223         MonoInst **arg_array;
7224         MonoMethodHeader *header;
7225         MonoImage *image;
7226         guint32 token, ins_flag;
7227         MonoClass *klass;
7228         MonoClass *constrained_class = NULL;
7229         unsigned char *ip, *end, *target, *err_pos;
7230         MonoMethodSignature *sig;
7231         MonoGenericContext *generic_context = NULL;
7232         MonoGenericContainer *generic_container = NULL;
7233         MonoType **param_types;
7234         int i, n, start_new_bblock, dreg;
7235         int num_calls = 0, inline_costs = 0;
7236         int breakpoint_id = 0;
7237         guint num_args;
7238         GSList *class_inits = NULL;
7239         gboolean dont_verify, dont_verify_stloc, readonly = FALSE;
7240         int context_used;
7241         gboolean init_locals, seq_points, skip_dead_blocks;
7242         gboolean sym_seq_points = FALSE;
7243         MonoDebugMethodInfo *minfo;
7244         MonoBitSet *seq_point_locs = NULL;
7245         MonoBitSet *seq_point_set_locs = NULL;
7246
7247         cfg->disable_inline = is_jit_optimizer_disabled (method);
7248
7249         /* serialization and xdomain stuff may need access to private fields and methods */
7250         dont_verify = method->klass->image->assembly->corlib_internal? TRUE: FALSE;
7251         dont_verify |= method->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE;
7252         dont_verify |= method->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH;
7253         dont_verify |= method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE; /* bug #77896 */
7254         dont_verify |= method->wrapper_type == MONO_WRAPPER_COMINTEROP;
7255         dont_verify |= method->wrapper_type == MONO_WRAPPER_COMINTEROP_INVOKE;
7256
7257         /* still some type unsafety issues in marshal wrappers... (unknown is PtrToStructure) */
7258         dont_verify_stloc = method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE;
7259         dont_verify_stloc |= method->wrapper_type == MONO_WRAPPER_UNKNOWN;
7260         dont_verify_stloc |= method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED;
7261         dont_verify_stloc |= method->wrapper_type == MONO_WRAPPER_STELEMREF;
7262
7263         image = method->klass->image;
7264         header = mono_method_get_header_checked (method, &cfg->error);
7265         if (!header) {
7266                 mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
7267                 goto exception_exit;
7268         } else {
7269                 cfg->headers_to_free = g_slist_prepend_mempool (cfg->mempool, cfg->headers_to_free, header);
7270         }
7271
7272         generic_container = mono_method_get_generic_container (method);
7273         sig = mono_method_signature (method);
7274         num_args = sig->hasthis + sig->param_count;
7275         ip = (unsigned char*)header->code;
7276         cfg->cil_start = ip;
7277         end = ip + header->code_size;
7278         cfg->stat_cil_code_size += header->code_size;
7279
7280         seq_points = cfg->gen_seq_points && cfg->method == method;
7281
7282         if (method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED) {
7283                 /* We could hit a seq point before attaching to the JIT (#8338) */
7284                 seq_points = FALSE;
7285         }
7286
7287         if (cfg->gen_sdb_seq_points && cfg->method == method) {
7288                 minfo = mono_debug_lookup_method (method);
7289                 if (minfo) {
7290                         MonoSymSeqPoint *sps;
7291                         int i, n_il_offsets;
7292
7293                         mono_debug_get_seq_points (minfo, NULL, NULL, NULL, &sps, &n_il_offsets);
7294                         seq_point_locs = mono_bitset_mem_new (mono_mempool_alloc0 (cfg->mempool, mono_bitset_alloc_size (header->code_size, 0)), header->code_size, 0);
7295                         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);
7296                         sym_seq_points = TRUE;
7297                         for (i = 0; i < n_il_offsets; ++i) {
7298                                 if (sps [i].il_offset < header->code_size)
7299                                         mono_bitset_set_fast (seq_point_locs, sps [i].il_offset);
7300                         }
7301                         g_free (sps);
7302
7303                         MonoDebugMethodAsyncInfo* asyncMethod = mono_debug_lookup_method_async_debug_info (method);
7304                         if (asyncMethod) {
7305                                 for (i = 0; asyncMethod != NULL && i < asyncMethod->num_awaits; i++)
7306                                 {
7307                                         mono_bitset_set_fast (seq_point_locs, asyncMethod->resume_offsets[i]);
7308                                         mono_bitset_set_fast (seq_point_locs, asyncMethod->yield_offsets[i]);
7309                                 }
7310                                 mono_debug_free_method_async_debug_info (asyncMethod);
7311                         }
7312                 } else if (!method->wrapper_type && !method->dynamic && mono_debug_image_has_debug_info (method->klass->image)) {
7313                         /* Methods without line number info like auto-generated property accessors */
7314                         seq_point_locs = mono_bitset_mem_new (mono_mempool_alloc0 (cfg->mempool, mono_bitset_alloc_size (header->code_size, 0)), header->code_size, 0);
7315                         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);
7316                         sym_seq_points = TRUE;
7317                 }
7318         }
7319
7320         /* 
7321          * Methods without init_locals set could cause asserts in various passes
7322          * (#497220). To work around this, we emit dummy initialization opcodes
7323          * (OP_DUMMY_ICONST etc.) which generate no code. These are only supported
7324          * on some platforms.
7325          */
7326         if ((cfg->opt & MONO_OPT_UNSAFE) && cfg->backend->have_dummy_init)
7327                 init_locals = header->init_locals;
7328         else
7329                 init_locals = TRUE;
7330
7331         method_definition = method;
7332         while (method_definition->is_inflated) {
7333                 MonoMethodInflated *imethod = (MonoMethodInflated *) method_definition;
7334                 method_definition = imethod->declaring;
7335         }
7336
7337         /* SkipVerification is not allowed if core-clr is enabled */
7338         if (!dont_verify && mini_assembly_can_skip_verification (cfg->domain, method)) {
7339                 dont_verify = TRUE;
7340                 dont_verify_stloc = TRUE;
7341         }
7342
7343         if (sig->is_inflated)
7344                 generic_context = mono_method_get_context (method);
7345         else if (generic_container)
7346                 generic_context = &generic_container->context;
7347         cfg->generic_context = generic_context;
7348
7349         if (!cfg->gshared)
7350                 g_assert (!sig->has_type_parameters);
7351
7352         if (sig->generic_param_count && method->wrapper_type == MONO_WRAPPER_NONE) {
7353                 g_assert (method->is_inflated);
7354                 g_assert (mono_method_get_context (method)->method_inst);
7355         }
7356         if (method->is_inflated && mono_method_get_context (method)->method_inst)
7357                 g_assert (sig->generic_param_count);
7358
7359         if (cfg->method == method) {
7360                 cfg->real_offset = 0;
7361         } else {
7362                 cfg->real_offset = inline_offset;
7363         }
7364
7365         cfg->cil_offset_to_bb = (MonoBasicBlock **)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoBasicBlock*) * header->code_size);
7366         cfg->cil_offset_to_bb_len = header->code_size;
7367
7368         cfg->current_method = method;
7369
7370         if (cfg->verbose_level > 2)
7371                 printf ("method to IR %s\n", mono_method_full_name (method, TRUE));
7372
7373         param_types = (MonoType **)mono_mempool_alloc (cfg->mempool, sizeof (MonoType*) * num_args);
7374         if (sig->hasthis)
7375                 param_types [0] = method->klass->valuetype?&method->klass->this_arg:&method->klass->byval_arg;
7376         for (n = 0; n < sig->param_count; ++n)
7377                 param_types [n + sig->hasthis] = sig->params [n];
7378         cfg->arg_types = param_types;
7379
7380         cfg->dont_inline = g_list_prepend (cfg->dont_inline, method);
7381         if (cfg->method == method) {
7382
7383                 cfg->coverage_info = mono_profiler_coverage_alloc (cfg->method, header->code_size);
7384
7385                 /* ENTRY BLOCK */
7386                 NEW_BBLOCK (cfg, start_bblock);
7387                 cfg->bb_entry = start_bblock;
7388                 start_bblock->cil_code = NULL;
7389                 start_bblock->cil_length = 0;
7390
7391                 /* EXIT BLOCK */
7392                 NEW_BBLOCK (cfg, end_bblock);
7393                 cfg->bb_exit = end_bblock;
7394                 end_bblock->cil_code = NULL;
7395                 end_bblock->cil_length = 0;
7396                 end_bblock->flags |= BB_INDIRECT_JUMP_TARGET;
7397                 g_assert (cfg->num_bblocks == 2);
7398
7399                 arg_array = cfg->args;
7400
7401                 if (header->num_clauses) {
7402                         cfg->spvars = g_hash_table_new (NULL, NULL);
7403                         cfg->exvars = g_hash_table_new (NULL, NULL);
7404                 }
7405                 /* handle exception clauses */
7406                 for (i = 0; i < header->num_clauses; ++i) {
7407                         MonoBasicBlock *try_bb;
7408                         MonoExceptionClause *clause = &header->clauses [i];
7409                         GET_BBLOCK (cfg, try_bb, ip + clause->try_offset);
7410
7411                         try_bb->real_offset = clause->try_offset;
7412                         try_bb->try_start = TRUE;
7413                         try_bb->region = ((i + 1) << 8) | clause->flags;
7414                         GET_BBLOCK (cfg, tblock, ip + clause->handler_offset);
7415                         tblock->real_offset = clause->handler_offset;
7416                         tblock->flags |= BB_EXCEPTION_HANDLER;
7417
7418                         if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
7419                                 mono_create_exvar_for_offset (cfg, clause->handler_offset);
7420                         /*
7421                          * Linking the try block with the EH block hinders inlining as we won't be able to 
7422                          * merge the bblocks from inlining and produce an artificial hole for no good reason.
7423                          */
7424                         if (COMPILE_LLVM (cfg))
7425                                 link_bblock (cfg, try_bb, tblock);
7426
7427                         if (*(ip + clause->handler_offset) == CEE_POP)
7428                                 tblock->flags |= BB_EXCEPTION_DEAD_OBJ;
7429
7430                         if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY ||
7431                             clause->flags == MONO_EXCEPTION_CLAUSE_FILTER ||
7432                             clause->flags == MONO_EXCEPTION_CLAUSE_FAULT) {
7433                                 MONO_INST_NEW (cfg, ins, OP_START_HANDLER);
7434                                 MONO_ADD_INS (tblock, ins);
7435
7436                                 if (seq_points && clause->flags != MONO_EXCEPTION_CLAUSE_FINALLY && clause->flags != MONO_EXCEPTION_CLAUSE_FILTER) {
7437                                         /* finally clauses already have a seq point */
7438                                         /* seq points for filter clauses are emitted below */
7439                                         NEW_SEQ_POINT (cfg, ins, clause->handler_offset, TRUE);
7440                                         MONO_ADD_INS (tblock, ins);
7441                                 }
7442
7443                                 /* todo: is a fault block unsafe to optimize? */
7444                                 if (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT)
7445                                         tblock->flags |= BB_EXCEPTION_UNSAFE;
7446                         }
7447
7448                         /*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);
7449                           while (p < end) {
7450                           printf ("%s", mono_disasm_code_one (NULL, method, p, &p));
7451                           }*/
7452                         /* catch and filter blocks get the exception object on the stack */
7453                         if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE ||
7454                             clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
7455
7456                                 /* mostly like handle_stack_args (), but just sets the input args */
7457                                 /* printf ("handling clause at IL_%04x\n", clause->handler_offset); */
7458                                 tblock->in_scount = 1;
7459                                 tblock->in_stack = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*));
7460                                 tblock->in_stack [0] = mono_create_exvar_for_offset (cfg, clause->handler_offset);
7461
7462                                 cfg->cbb = tblock;
7463
7464 #ifdef MONO_CONTEXT_SET_LLVM_EXC_REG
7465                                 /* The EH code passes in the exception in a register to both JITted and LLVM compiled code */
7466                                 if (!cfg->compile_llvm) {
7467                                         MONO_INST_NEW (cfg, ins, OP_GET_EX_OBJ);
7468                                         ins->dreg = tblock->in_stack [0]->dreg;
7469                                         MONO_ADD_INS (tblock, ins);
7470                                 }
7471 #else
7472                                 MonoInst *dummy_use;
7473
7474                                 /* 
7475                                  * Add a dummy use for the exvar so its liveness info will be
7476                                  * correct.
7477                                  */
7478                                 EMIT_NEW_DUMMY_USE (cfg, dummy_use, tblock->in_stack [0]);
7479 #endif
7480
7481                                 if (seq_points && clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
7482                                         NEW_SEQ_POINT (cfg, ins, clause->handler_offset, TRUE);
7483                                         MONO_ADD_INS (tblock, ins);
7484                                 }
7485                                 
7486                                 if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
7487                                         GET_BBLOCK (cfg, tblock, ip + clause->data.filter_offset);
7488                                         tblock->flags |= BB_EXCEPTION_HANDLER;
7489                                         tblock->real_offset = clause->data.filter_offset;
7490                                         tblock->in_scount = 1;
7491                                         tblock->in_stack = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*));
7492                                         /* The filter block shares the exvar with the handler block */
7493                                         tblock->in_stack [0] = mono_create_exvar_for_offset (cfg, clause->handler_offset);
7494                                         MONO_INST_NEW (cfg, ins, OP_START_HANDLER);
7495                                         MONO_ADD_INS (tblock, ins);
7496                                 }
7497                         }
7498
7499                         if (clause->flags != MONO_EXCEPTION_CLAUSE_FILTER &&
7500                                         clause->data.catch_class &&
7501                                         cfg->gshared &&
7502                                         mono_class_check_context_used (clause->data.catch_class)) {
7503                                 /*
7504                                  * In shared generic code with catch
7505                                  * clauses containing type variables
7506                                  * the exception handling code has to
7507                                  * be able to get to the rgctx.
7508                                  * Therefore we have to make sure that
7509                                  * the vtable/mrgctx argument (for
7510                                  * static or generic methods) or the
7511                                  * "this" argument (for non-static
7512                                  * methods) are live.
7513                                  */
7514                                 if ((method->flags & METHOD_ATTRIBUTE_STATIC) ||
7515                                                 mini_method_get_context (method)->method_inst ||
7516                                                 method->klass->valuetype) {
7517                                         mono_get_vtable_var (cfg);
7518                                 } else {
7519                                         MonoInst *dummy_use;
7520
7521                                         EMIT_NEW_DUMMY_USE (cfg, dummy_use, arg_array [0]);
7522                                 }
7523                         }
7524                 }
7525         } else {
7526                 arg_array = (MonoInst **) alloca (sizeof (MonoInst *) * num_args);
7527                 cfg->cbb = start_bblock;
7528                 cfg->args = arg_array;
7529                 mono_save_args (cfg, sig, inline_args);
7530         }
7531
7532         /* FIRST CODE BLOCK */
7533         NEW_BBLOCK (cfg, tblock);
7534         tblock->cil_code = ip;
7535         cfg->cbb = tblock;
7536         cfg->ip = ip;
7537
7538         ADD_BBLOCK (cfg, tblock);
7539
7540         if (cfg->method == method) {
7541                 breakpoint_id = mono_debugger_method_has_breakpoint (method);
7542                 if (breakpoint_id) {
7543                         MONO_INST_NEW (cfg, ins, OP_BREAK);
7544                         MONO_ADD_INS (cfg->cbb, ins);
7545                 }
7546         }
7547
7548         /* we use a separate basic block for the initialization code */
7549         NEW_BBLOCK (cfg, init_localsbb);
7550         if (cfg->method == method)
7551                 cfg->bb_init = init_localsbb;
7552         init_localsbb->real_offset = cfg->real_offset;
7553         start_bblock->next_bb = init_localsbb;
7554         init_localsbb->next_bb = cfg->cbb;
7555         link_bblock (cfg, start_bblock, init_localsbb);
7556         link_bblock (cfg, init_localsbb, cfg->cbb);
7557                 
7558         cfg->cbb = init_localsbb;
7559
7560         if (cfg->gsharedvt && cfg->method == method) {
7561                 MonoGSharedVtMethodInfo *info;
7562                 MonoInst *var, *locals_var;
7563                 int dreg;
7564
7565                 info = (MonoGSharedVtMethodInfo *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoGSharedVtMethodInfo));
7566                 info->method = cfg->method;
7567                 info->count_entries = 16;
7568                 info->entries = (MonoRuntimeGenericContextInfoTemplate *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoRuntimeGenericContextInfoTemplate) * info->count_entries);
7569                 cfg->gsharedvt_info = info;
7570
7571                 var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
7572                 /* prevent it from being register allocated */
7573                 //var->flags |= MONO_INST_VOLATILE;
7574                 cfg->gsharedvt_info_var = var;
7575
7576                 ins = emit_get_rgctx_gsharedvt_method (cfg, mini_method_check_context_used (cfg, method), method, info);
7577                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, var->dreg, ins->dreg);
7578
7579                 /* Allocate locals */
7580                 locals_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
7581                 /* prevent it from being register allocated */
7582                 //locals_var->flags |= MONO_INST_VOLATILE;
7583                 cfg->gsharedvt_locals_var = locals_var;
7584
7585                 dreg = alloc_ireg (cfg);
7586                 MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, dreg, var->dreg, MONO_STRUCT_OFFSET (MonoGSharedVtMethodRuntimeInfo, locals_size));
7587
7588                 MONO_INST_NEW (cfg, ins, OP_LOCALLOC);
7589                 ins->dreg = locals_var->dreg;
7590                 ins->sreg1 = dreg;
7591                 MONO_ADD_INS (cfg->cbb, ins);
7592                 cfg->gsharedvt_locals_var_ins = ins;
7593                 
7594                 cfg->flags |= MONO_CFG_HAS_ALLOCA;
7595                 /*
7596                 if (init_locals)
7597                         ins->flags |= MONO_INST_INIT;
7598                 */
7599         }
7600
7601         if (mono_security_core_clr_enabled ()) {
7602                 /* check if this is native code, e.g. an icall or a p/invoke */
7603                 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
7604                         MonoMethod *wrapped = mono_marshal_method_from_wrapper (method);
7605                         if (wrapped) {
7606                                 gboolean pinvk = (wrapped->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL);
7607                                 gboolean icall = (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL);
7608
7609                                 /* if this ia a native call then it can only be JITted from platform code */
7610                                 if ((icall || pinvk) && method->klass && method->klass->image) {
7611                                         if (!mono_security_core_clr_is_platform_image (method->klass->image)) {
7612                                                 MonoException *ex = icall ? mono_get_exception_security () : 
7613                                                         mono_get_exception_method_access ();
7614                                                 emit_throw_exception (cfg, ex);
7615                                         }
7616                                 }
7617                         }
7618                 }
7619         }
7620
7621         CHECK_CFG_EXCEPTION;
7622
7623         if (header->code_size == 0)
7624                 UNVERIFIED;
7625
7626         if (get_basic_blocks (cfg, header, cfg->real_offset, ip, end, &err_pos)) {
7627                 ip = err_pos;
7628                 UNVERIFIED;
7629         }
7630
7631         if (cfg->method == method)
7632                 mono_debug_init_method (cfg, cfg->cbb, breakpoint_id);
7633
7634         for (n = 0; n < header->num_locals; ++n) {
7635                 if (header->locals [n]->type == MONO_TYPE_VOID && !header->locals [n]->byref)
7636                         UNVERIFIED;
7637         }
7638         class_inits = NULL;
7639
7640         /* We force the vtable variable here for all shared methods
7641            for the possibility that they might show up in a stack
7642            trace where their exact instantiation is needed. */
7643         if (cfg->gshared && method == cfg->method) {
7644                 if ((method->flags & METHOD_ATTRIBUTE_STATIC) ||
7645                                 mini_method_get_context (method)->method_inst ||
7646                                 method->klass->valuetype) {
7647                         mono_get_vtable_var (cfg);
7648                 } else {
7649                         /* FIXME: Is there a better way to do this?
7650                            We need the variable live for the duration
7651                            of the whole method. */
7652                         cfg->args [0]->flags |= MONO_INST_VOLATILE;
7653                 }
7654         }
7655
7656         /* add a check for this != NULL to inlined methods */
7657         if (is_virtual_call) {
7658                 MonoInst *arg_ins;
7659
7660                 NEW_ARGLOAD (cfg, arg_ins, 0);
7661                 MONO_ADD_INS (cfg->cbb, arg_ins);
7662                 MONO_EMIT_NEW_CHECK_THIS (cfg, arg_ins->dreg);
7663         }
7664
7665         skip_dead_blocks = !dont_verify;
7666         if (skip_dead_blocks) {
7667                 original_bb = bb = mono_basic_block_split (method, &cfg->error, header);
7668                 CHECK_CFG_ERROR;
7669                 g_assert (bb);
7670         }
7671
7672         /* we use a spare stack slot in SWITCH and NEWOBJ and others */
7673         stack_start = sp = (MonoInst **)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst*) * (header->max_stack + 1));
7674
7675         ins_flag = 0;
7676         start_new_bblock = 0;
7677         while (ip < end) {
7678                 if (cfg->method == method)
7679                         cfg->real_offset = ip - header->code;
7680                 else
7681                         cfg->real_offset = inline_offset;
7682                 cfg->ip = ip;
7683
7684                 context_used = 0;
7685
7686                 if (start_new_bblock) {
7687                         cfg->cbb->cil_length = ip - cfg->cbb->cil_code;
7688                         if (start_new_bblock == 2) {
7689                                 g_assert (ip == tblock->cil_code);
7690                         } else {
7691                                 GET_BBLOCK (cfg, tblock, ip);
7692                         }
7693                         cfg->cbb->next_bb = tblock;
7694                         cfg->cbb = tblock;
7695                         start_new_bblock = 0;
7696                         for (i = 0; i < cfg->cbb->in_scount; ++i) {
7697                                 if (cfg->verbose_level > 3)
7698                                         printf ("loading %d from temp %d\n", i, (int)cfg->cbb->in_stack [i]->inst_c0);
7699                                 EMIT_NEW_TEMPLOAD (cfg, ins, cfg->cbb->in_stack [i]->inst_c0);
7700                                 *sp++ = ins;
7701                         }
7702                         if (class_inits)
7703                                 g_slist_free (class_inits);
7704                         class_inits = NULL;
7705                 } else {
7706                         if ((tblock = cfg->cil_offset_to_bb [ip - cfg->cil_start]) && (tblock != cfg->cbb)) {
7707                                 link_bblock (cfg, cfg->cbb, tblock);
7708                                 if (sp != stack_start) {
7709                                         handle_stack_args (cfg, stack_start, sp - stack_start);
7710                                         sp = stack_start;
7711                                         CHECK_UNVERIFIABLE (cfg);
7712                                 }
7713                                 cfg->cbb->next_bb = tblock;
7714                                 cfg->cbb = tblock;
7715                                 for (i = 0; i < cfg->cbb->in_scount; ++i) {
7716                                         if (cfg->verbose_level > 3)
7717                                                 printf ("loading %d from temp %d\n", i, (int)cfg->cbb->in_stack [i]->inst_c0);
7718                                         EMIT_NEW_TEMPLOAD (cfg, ins, cfg->cbb->in_stack [i]->inst_c0);
7719                                         *sp++ = ins;
7720                                 }
7721                                 g_slist_free (class_inits);
7722                                 class_inits = NULL;
7723                         }
7724                 }
7725
7726                 if (skip_dead_blocks) {
7727                         int ip_offset = ip - header->code;
7728
7729                         if (ip_offset == bb->end)
7730                                 bb = bb->next;
7731
7732                         if (bb->dead) {
7733                                 int op_size = mono_opcode_size (ip, end);
7734                                 g_assert (op_size > 0); /*The BB formation pass must catch all bad ops*/
7735
7736                                 if (cfg->verbose_level > 3) printf ("SKIPPING DEAD OP at %x\n", ip_offset);
7737
7738                                 if (ip_offset + op_size == bb->end) {
7739                                         MONO_INST_NEW (cfg, ins, OP_NOP);
7740                                         MONO_ADD_INS (cfg->cbb, ins);
7741                                         start_new_bblock = 1;
7742                                 }
7743
7744                                 ip += op_size;
7745                                 continue;
7746                         }
7747                 }
7748                 /*
7749                  * Sequence points are points where the debugger can place a breakpoint.
7750                  * Currently, we generate these automatically at points where the IL
7751                  * stack is empty.
7752                  */
7753                 if (seq_points && ((!sym_seq_points && (sp == stack_start)) || (sym_seq_points && mono_bitset_test_fast (seq_point_locs, ip - header->code)))) {
7754                         /*
7755                          * Make methods interruptable at the beginning, and at the targets of
7756                          * backward branches.
7757                          * Also, do this at the start of every bblock in methods with clauses too,
7758                          * to be able to handle instructions with inprecise control flow like
7759                          * throw/endfinally.
7760                          * Backward branches are handled at the end of method-to-ir ().
7761                          */
7762                         gboolean intr_loc = ip == header->code || (!cfg->cbb->last_ins && cfg->header->num_clauses);
7763                         gboolean sym_seq_point = sym_seq_points && mono_bitset_test_fast (seq_point_locs, ip - header->code);
7764
7765                         /* Avoid sequence points on empty IL like .volatile */
7766                         // FIXME: Enable this
7767                         //if (!(cfg->cbb->last_ins && cfg->cbb->last_ins->opcode == OP_SEQ_POINT)) {
7768                         NEW_SEQ_POINT (cfg, ins, ip - header->code, intr_loc);
7769                         if ((sp != stack_start) && !sym_seq_point)
7770                                 ins->flags |= MONO_INST_NONEMPTY_STACK;
7771                         MONO_ADD_INS (cfg->cbb, ins);
7772
7773                         if (sym_seq_points)
7774                                 mono_bitset_set_fast (seq_point_set_locs, ip - header->code);
7775                 }
7776
7777                 cfg->cbb->real_offset = cfg->real_offset;
7778
7779                 if ((cfg->method == method) && cfg->coverage_info) {
7780                         guint32 cil_offset = ip - header->code;
7781                         gpointer counter = &cfg->coverage_info->data [cil_offset].count;
7782                         cfg->coverage_info->data [cil_offset].cil_code = ip;
7783
7784                         if (mono_arch_opcode_supported (OP_ATOMIC_ADD_I4)) {
7785                                 MonoInst *one_ins, *load_ins;
7786
7787                                 EMIT_NEW_PCONST (cfg, load_ins, counter);
7788                                 EMIT_NEW_ICONST (cfg, one_ins, 1);
7789                                 MONO_INST_NEW (cfg, ins, OP_ATOMIC_ADD_I4);
7790                                 ins->dreg = mono_alloc_ireg (cfg);
7791                                 ins->inst_basereg = load_ins->dreg;
7792                                 ins->inst_offset = 0;
7793                                 ins->sreg2 = one_ins->dreg;
7794                                 ins->type = STACK_I4;
7795                                 MONO_ADD_INS (cfg->cbb, ins);
7796                         } else {
7797                                 EMIT_NEW_PCONST (cfg, ins, counter);
7798                                 MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STORE_MEMBASE_IMM, ins->dreg, 0, 1);
7799                         }
7800                 }
7801
7802                 if (cfg->verbose_level > 3)
7803                         printf ("converting (in B%d: stack: %d) %s", cfg->cbb->block_num, (int)(sp - stack_start), mono_disasm_code_one (NULL, method, ip, NULL));
7804
7805                 switch (*ip) {
7806                 case CEE_NOP:
7807                         if (seq_points && !sym_seq_points && sp != stack_start) {
7808                                 /*
7809                                  * The C# compiler uses these nops to notify the JIT that it should
7810                                  * insert seq points.
7811                                  */
7812                                 NEW_SEQ_POINT (cfg, ins, ip - header->code, FALSE);
7813                                 MONO_ADD_INS (cfg->cbb, ins);
7814                         }
7815                         if (cfg->keep_cil_nops)
7816                                 MONO_INST_NEW (cfg, ins, OP_HARD_NOP);
7817                         else
7818                                 MONO_INST_NEW (cfg, ins, OP_NOP);
7819                         ip++;
7820                         MONO_ADD_INS (cfg->cbb, ins);
7821                         break;
7822                 case CEE_BREAK:
7823                         if (mini_should_insert_breakpoint (cfg->method)) {
7824                                 ins = mono_emit_jit_icall (cfg, mono_debugger_agent_user_break, NULL);
7825                         } else {
7826                                 MONO_INST_NEW (cfg, ins, OP_NOP);
7827                         }
7828                         ip++;
7829                         MONO_ADD_INS (cfg->cbb, ins);
7830                         break;
7831                 case CEE_LDARG_0:
7832                 case CEE_LDARG_1:
7833                 case CEE_LDARG_2:
7834                 case CEE_LDARG_3:
7835                         CHECK_STACK_OVF (1);
7836                         n = (*ip)-CEE_LDARG_0;
7837                         CHECK_ARG (n);
7838                         EMIT_NEW_ARGLOAD (cfg, ins, n);
7839                         ip++;
7840                         *sp++ = ins;
7841                         break;
7842                 case CEE_LDLOC_0:
7843                 case CEE_LDLOC_1:
7844                 case CEE_LDLOC_2:
7845                 case CEE_LDLOC_3:
7846                         CHECK_STACK_OVF (1);
7847                         n = (*ip)-CEE_LDLOC_0;
7848                         CHECK_LOCAL (n);
7849                         EMIT_NEW_LOCLOAD (cfg, ins, n);
7850                         ip++;
7851                         *sp++ = ins;
7852                         break;
7853                 case CEE_STLOC_0:
7854                 case CEE_STLOC_1:
7855                 case CEE_STLOC_2:
7856                 case CEE_STLOC_3: {
7857                         CHECK_STACK (1);
7858                         n = (*ip)-CEE_STLOC_0;
7859                         CHECK_LOCAL (n);
7860                         --sp;
7861                         if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [n], *sp))
7862                                 UNVERIFIED;
7863                         emit_stloc_ir (cfg, sp, header, n);
7864                         ++ip;
7865                         inline_costs += 1;
7866                         break;
7867                         }
7868                 case CEE_LDARG_S:
7869                         CHECK_OPSIZE (2);
7870                         CHECK_STACK_OVF (1);
7871                         n = ip [1];
7872                         CHECK_ARG (n);
7873                         EMIT_NEW_ARGLOAD (cfg, ins, n);
7874                         *sp++ = ins;
7875                         ip += 2;
7876                         break;
7877                 case CEE_LDARGA_S:
7878                         CHECK_OPSIZE (2);
7879                         CHECK_STACK_OVF (1);
7880                         n = ip [1];
7881                         CHECK_ARG (n);
7882                         NEW_ARGLOADA (cfg, ins, n);
7883                         MONO_ADD_INS (cfg->cbb, ins);
7884                         *sp++ = ins;
7885                         ip += 2;
7886                         break;
7887                 case CEE_STARG_S:
7888                         CHECK_OPSIZE (2);
7889                         CHECK_STACK (1);
7890                         --sp;
7891                         n = ip [1];
7892                         CHECK_ARG (n);
7893                         if (!dont_verify_stloc && target_type_is_incompatible (cfg, param_types [ip [1]], *sp))
7894                                 UNVERIFIED;
7895                         emit_starg_ir (cfg, sp, n);
7896                         ip += 2;
7897                         break;
7898                 case CEE_LDLOC_S:
7899                         CHECK_OPSIZE (2);
7900                         CHECK_STACK_OVF (1);
7901                         n = ip [1];
7902                         CHECK_LOCAL (n);
7903                         if ((ip [2] == CEE_LDFLD) && ip_in_bb (cfg, cfg->cbb, ip + 2) && MONO_TYPE_ISSTRUCT (header->locals [n])) {
7904                                 /* Avoid loading a struct just to load one of its fields */
7905                                 EMIT_NEW_LOCLOADA (cfg, ins, n);
7906                         } else {
7907                                 EMIT_NEW_LOCLOAD (cfg, ins, n);
7908                         }
7909                         *sp++ = ins;
7910                         ip += 2;
7911                         break;
7912                 case CEE_LDLOCA_S: {
7913                         unsigned char *tmp_ip;
7914                         CHECK_OPSIZE (2);
7915                         CHECK_STACK_OVF (1);
7916                         CHECK_LOCAL (ip [1]);
7917
7918                         if ((tmp_ip = emit_optimized_ldloca_ir (cfg, ip, end, 1))) {
7919                                 ip = tmp_ip;
7920                                 inline_costs += 1;
7921                                 break;
7922                         }
7923
7924                         EMIT_NEW_LOCLOADA (cfg, ins, ip [1]);
7925                         *sp++ = ins;
7926                         ip += 2;
7927                         break;
7928                 }
7929                 case CEE_STLOC_S:
7930                         CHECK_OPSIZE (2);
7931                         CHECK_STACK (1);
7932                         --sp;
7933                         CHECK_LOCAL (ip [1]);
7934                         if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [ip [1]], *sp))
7935                                 UNVERIFIED;
7936                         emit_stloc_ir (cfg, sp, header, ip [1]);
7937                         ip += 2;
7938                         inline_costs += 1;
7939                         break;
7940                 case CEE_LDNULL:
7941                         CHECK_STACK_OVF (1);
7942                         EMIT_NEW_PCONST (cfg, ins, NULL);
7943                         ins->type = STACK_OBJ;
7944                         ++ip;
7945                         *sp++ = ins;
7946                         break;
7947                 case CEE_LDC_I4_M1:
7948                         CHECK_STACK_OVF (1);
7949                         EMIT_NEW_ICONST (cfg, ins, -1);
7950                         ++ip;
7951                         *sp++ = ins;
7952                         break;
7953                 case CEE_LDC_I4_0:
7954                 case CEE_LDC_I4_1:
7955                 case CEE_LDC_I4_2:
7956                 case CEE_LDC_I4_3:
7957                 case CEE_LDC_I4_4:
7958                 case CEE_LDC_I4_5:
7959                 case CEE_LDC_I4_6:
7960                 case CEE_LDC_I4_7:
7961                 case CEE_LDC_I4_8:
7962                         CHECK_STACK_OVF (1);
7963                         EMIT_NEW_ICONST (cfg, ins, (*ip) - CEE_LDC_I4_0);
7964                         ++ip;
7965                         *sp++ = ins;
7966                         break;
7967                 case CEE_LDC_I4_S:
7968                         CHECK_OPSIZE (2);
7969                         CHECK_STACK_OVF (1);
7970                         ++ip;
7971                         EMIT_NEW_ICONST (cfg, ins, *((signed char*)ip));
7972                         ++ip;
7973                         *sp++ = ins;
7974                         break;
7975                 case CEE_LDC_I4:
7976                         CHECK_OPSIZE (5);
7977                         CHECK_STACK_OVF (1);
7978                         EMIT_NEW_ICONST (cfg, ins, (gint32)read32 (ip + 1));
7979                         ip += 5;
7980                         *sp++ = ins;
7981                         break;
7982                 case CEE_LDC_I8:
7983                         CHECK_OPSIZE (9);
7984                         CHECK_STACK_OVF (1);
7985                         MONO_INST_NEW (cfg, ins, OP_I8CONST);
7986                         ins->type = STACK_I8;
7987                         ins->dreg = alloc_dreg (cfg, STACK_I8);
7988                         ++ip;
7989                         ins->inst_l = (gint64)read64 (ip);
7990                         MONO_ADD_INS (cfg->cbb, ins);
7991                         ip += 8;
7992                         *sp++ = ins;
7993                         break;
7994                 case CEE_LDC_R4: {
7995                         float *f;
7996                         gboolean use_aotconst = FALSE;
7997
7998 #ifdef TARGET_POWERPC
7999                         /* FIXME: Clean this up */
8000                         if (cfg->compile_aot)
8001                                 use_aotconst = TRUE;
8002 #endif
8003
8004                         /* FIXME: we should really allocate this only late in the compilation process */
8005                         f = (float *)mono_domain_alloc (cfg->domain, sizeof (float));
8006                         CHECK_OPSIZE (5);
8007                         CHECK_STACK_OVF (1);
8008
8009                         if (use_aotconst) {
8010                                 MonoInst *cons;
8011                                 int dreg;
8012
8013                                 EMIT_NEW_AOTCONST (cfg, cons, MONO_PATCH_INFO_R4, f);
8014
8015                                 dreg = alloc_freg (cfg);
8016                                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADR4_MEMBASE, dreg, cons->dreg, 0);
8017                                 ins->type = cfg->r4_stack_type;
8018                         } else {
8019                                 MONO_INST_NEW (cfg, ins, OP_R4CONST);
8020                                 ins->type = cfg->r4_stack_type;
8021                                 ins->dreg = alloc_dreg (cfg, STACK_R8);
8022                                 ins->inst_p0 = f;
8023                                 MONO_ADD_INS (cfg->cbb, ins);
8024                         }
8025                         ++ip;
8026                         readr4 (ip, f);
8027                         ip += 4;
8028                         *sp++ = ins;                    
8029                         break;
8030                 }
8031                 case CEE_LDC_R8: {
8032                         double *d;
8033                         gboolean use_aotconst = FALSE;
8034
8035 #ifdef TARGET_POWERPC
8036                         /* FIXME: Clean this up */
8037                         if (cfg->compile_aot)
8038                                 use_aotconst = TRUE;
8039 #endif
8040
8041                         /* FIXME: we should really allocate this only late in the compilation process */
8042                         d = (double *)mono_domain_alloc (cfg->domain, sizeof (double));
8043                         CHECK_OPSIZE (9);
8044                         CHECK_STACK_OVF (1);
8045
8046                         if (use_aotconst) {
8047                                 MonoInst *cons;
8048                                 int dreg;
8049
8050                                 EMIT_NEW_AOTCONST (cfg, cons, MONO_PATCH_INFO_R8, d);
8051
8052                                 dreg = alloc_freg (cfg);
8053                                 EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOADR8_MEMBASE, dreg, cons->dreg, 0);
8054                                 ins->type = STACK_R8;
8055                         } else {
8056                                 MONO_INST_NEW (cfg, ins, OP_R8CONST);
8057                                 ins->type = STACK_R8;
8058                                 ins->dreg = alloc_dreg (cfg, STACK_R8);
8059                                 ins->inst_p0 = d;
8060                                 MONO_ADD_INS (cfg->cbb, ins);
8061                         }
8062                         ++ip;
8063                         readr8 (ip, d);
8064                         ip += 8;
8065                         *sp++ = ins;
8066                         break;
8067                 }
8068                 case CEE_DUP: {
8069                         MonoInst *temp, *store;
8070                         CHECK_STACK (1);
8071                         CHECK_STACK_OVF (1);
8072                         sp--;
8073                         ins = *sp;
8074
8075                         temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
8076                         EMIT_NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
8077
8078                         EMIT_NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
8079                         *sp++ = ins;
8080
8081                         EMIT_NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
8082                         *sp++ = ins;
8083
8084                         ++ip;
8085                         inline_costs += 2;
8086                         break;
8087                 }
8088                 case CEE_POP:
8089                         CHECK_STACK (1);
8090                         ip++;
8091                         --sp;
8092
8093 #ifdef TARGET_X86
8094                         if (sp [0]->type == STACK_R8)
8095                                 /* we need to pop the value from the x86 FP stack */
8096                                 MONO_EMIT_NEW_UNALU (cfg, OP_X86_FPOP, -1, sp [0]->dreg);
8097 #endif
8098                         break;
8099                 case CEE_JMP: {
8100                         MonoCallInst *call;
8101                         MonoMethodSignature *fsig;
8102                         int i, n;
8103
8104                         INLINE_FAILURE ("jmp");
8105                         GSHAREDVT_FAILURE (*ip);
8106
8107                         CHECK_OPSIZE (5);
8108                         if (stack_start != sp)
8109                                 UNVERIFIED;
8110                         token = read32 (ip + 1);
8111                         /* FIXME: check the signature matches */
8112                         cmethod = mini_get_method (cfg, method, token, NULL, generic_context);
8113                         CHECK_CFG_ERROR;
8114  
8115                         if (cfg->gshared && mono_method_check_context_used (cmethod))
8116                                 GENERIC_SHARING_FAILURE (CEE_JMP);
8117
8118                         mini_profiler_emit_tail_call (cfg, cmethod);
8119
8120                         fsig = mono_method_signature (cmethod);
8121                         n = fsig->param_count + fsig->hasthis;
8122                         if (cfg->llvm_only) {
8123                                 MonoInst **args;
8124
8125                                 args = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * n);
8126                                 for (i = 0; i < n; ++i)
8127                                         EMIT_NEW_ARGLOAD (cfg, args [i], i);
8128                                 ins = mono_emit_method_call_full (cfg, cmethod, fsig, TRUE, args, NULL, NULL, NULL);
8129                                 /*
8130                                  * The code in mono-basic-block.c treats the rest of the code as dead, but we
8131                                  * have to emit a normal return since llvm expects it.
8132                                  */
8133                                 if (cfg->ret)
8134                                         emit_setret (cfg, ins);
8135                                 MONO_INST_NEW (cfg, ins, OP_BR);
8136                                 ins->inst_target_bb = end_bblock;
8137                                 MONO_ADD_INS (cfg->cbb, ins);
8138                                 link_bblock (cfg, cfg->cbb, end_bblock);
8139                                 ip += 5;
8140                                 break;
8141                         } else if (cfg->backend->have_op_tail_call) {
8142                                 /* Handle tail calls similarly to calls */
8143                                 DISABLE_AOT (cfg);
8144
8145                                 MONO_INST_NEW_CALL (cfg, call, OP_TAILCALL);
8146                                 call->method = cmethod;
8147                                 call->tail_call = TRUE;
8148                                 call->signature = mono_method_signature (cmethod);
8149                                 call->args = (MonoInst **)mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * n);
8150                                 call->inst.inst_p0 = cmethod;
8151                                 for (i = 0; i < n; ++i)
8152                                         EMIT_NEW_ARGLOAD (cfg, call->args [i], i);
8153
8154                                 if (mini_type_is_vtype (mini_get_underlying_type (call->signature->ret)))
8155                                         call->vret_var = cfg->vret_addr;
8156
8157                                 mono_arch_emit_call (cfg, call);
8158                                 cfg->param_area = MAX(cfg->param_area, call->stack_usage);
8159                                 MONO_ADD_INS (cfg->cbb, (MonoInst*)call);
8160                         } else {
8161                                 for (i = 0; i < num_args; ++i)
8162                                         /* Prevent arguments from being optimized away */
8163                                         arg_array [i]->flags |= MONO_INST_VOLATILE;
8164
8165                                 MONO_INST_NEW_CALL (cfg, call, OP_JMP);
8166                                 ins = (MonoInst*)call;
8167                                 ins->inst_p0 = cmethod;
8168                                 MONO_ADD_INS (cfg->cbb, ins);
8169                         }
8170
8171                         ip += 5;
8172                         start_new_bblock = 1;
8173                         break;
8174                 }
8175                 case CEE_CALLI: {
8176                         MonoInst *addr;
8177                         MonoMethodSignature *fsig;
8178
8179                         CHECK_OPSIZE (5);
8180                         token = read32 (ip + 1);
8181
8182                         ins = NULL;
8183
8184                         //GSHAREDVT_FAILURE (*ip);
8185                         cmethod = NULL;
8186                         CHECK_STACK (1);
8187                         --sp;
8188                         addr = *sp;
8189                         fsig = mini_get_signature (method, token, generic_context, &cfg->error);
8190                         CHECK_CFG_ERROR;
8191
8192                         if (method->dynamic && fsig->pinvoke) {
8193                                 MonoInst *args [3];
8194
8195                                 /*
8196                                  * This is a call through a function pointer using a pinvoke
8197                                  * signature. Have to create a wrapper and call that instead.
8198                                  * FIXME: This is very slow, need to create a wrapper at JIT time
8199                                  * instead based on the signature.
8200                                  */
8201                                 EMIT_NEW_IMAGECONST (cfg, args [0], method->klass->image);
8202                                 EMIT_NEW_PCONST (cfg, args [1], fsig);
8203                                 args [2] = addr;
8204                                 addr = mono_emit_jit_icall (cfg, mono_get_native_calli_wrapper, args);
8205                         }
8206
8207                         n = fsig->param_count + fsig->hasthis;
8208
8209                         CHECK_STACK (n);
8210
8211                         //g_assert (!virtual_ || fsig->hasthis);
8212
8213                         sp -= n;
8214
8215                         inline_costs += 10 * num_calls++;
8216
8217                         /*
8218                          * Making generic calls out of gsharedvt methods.
8219                          * This needs to be used for all generic calls, not just ones with a gsharedvt signature, to avoid
8220                          * patching gshared method addresses into a gsharedvt method.
8221                          */
8222                         if (cfg->gsharedvt && mini_is_gsharedvt_signature (fsig)) {
8223                                 /*
8224                                  * We pass the address to the gsharedvt trampoline in the rgctx reg
8225                                  */
8226                                 MonoInst *callee = addr;
8227
8228                                 if (method->wrapper_type != MONO_WRAPPER_DELEGATE_INVOKE)
8229                                         /* Not tested */
8230                                         GSHAREDVT_FAILURE (*ip);
8231
8232                                 if (cfg->llvm_only)
8233                                         // FIXME:
8234                                         GSHAREDVT_FAILURE (*ip);
8235
8236                                 addr = emit_get_rgctx_sig (cfg, context_used,
8237                                                                                           fsig, MONO_RGCTX_INFO_SIG_GSHAREDVT_OUT_TRAMPOLINE_CALLI);
8238                                 ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, NULL, callee);
8239                                 goto calli_end;
8240                         }
8241
8242                         /* Prevent inlining of methods with indirect calls */
8243                         INLINE_FAILURE ("indirect call");
8244
8245                         if (addr->opcode == OP_PCONST || addr->opcode == OP_AOTCONST || addr->opcode == OP_GOT_ENTRY) {
8246                                 MonoJumpInfoType info_type;
8247                                 gpointer info_data;
8248
8249                                 /*
8250                                  * Instead of emitting an indirect call, emit a direct call
8251                                  * with the contents of the aotconst as the patch info.
8252                                  */
8253                                 if (addr->opcode == OP_PCONST || addr->opcode == OP_AOTCONST) {
8254                                         info_type = (MonoJumpInfoType)addr->inst_c1;
8255                                         info_data = addr->inst_p0;
8256                                 } else {
8257                                         info_type = (MonoJumpInfoType)addr->inst_right->inst_c1;
8258                                         info_data = addr->inst_right->inst_left;
8259                                 }
8260
8261                                 if (info_type == MONO_PATCH_INFO_ICALL_ADDR) {
8262                                         ins = (MonoInst*)mono_emit_abs_call (cfg, MONO_PATCH_INFO_ICALL_ADDR_CALL, info_data, fsig, sp);
8263                                         NULLIFY_INS (addr);
8264                                         goto calli_end;
8265                                 } else if (info_type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
8266                                         ins = (MonoInst*)mono_emit_abs_call (cfg, info_type, info_data, fsig, sp);
8267                                         NULLIFY_INS (addr);
8268                                         goto calli_end;
8269                                 }
8270                         }
8271                         ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
8272
8273                         calli_end:
8274
8275                         /* End of call, INS should contain the result of the call, if any */
8276
8277                         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
8278                                 g_assert (ins);
8279                                 *sp++ = mono_emit_widen_call_res (cfg, ins, fsig);
8280                         }
8281
8282                         CHECK_CFG_EXCEPTION;
8283
8284                         ip += 5;
8285                         ins_flag = 0;
8286                         constrained_class = NULL;
8287                         break;
8288                 }
8289                 case CEE_CALL:
8290                 case CEE_CALLVIRT: {
8291                         MonoInst *addr = NULL;
8292                         MonoMethodSignature *fsig = NULL;
8293                         int array_rank = 0;
8294                         int virtual_ = *ip == CEE_CALLVIRT;
8295                         gboolean pass_imt_from_rgctx = FALSE;
8296                         MonoInst *imt_arg = NULL;
8297                         MonoInst *keep_this_alive = NULL;
8298                         gboolean pass_vtable = FALSE;
8299                         gboolean pass_mrgctx = FALSE;
8300                         MonoInst *vtable_arg = NULL;
8301                         gboolean check_this = FALSE;
8302                         gboolean supported_tail_call = FALSE;
8303                         gboolean tail_call = FALSE;
8304                         gboolean need_seq_point = FALSE;
8305                         guint32 call_opcode = *ip;
8306                         gboolean emit_widen = TRUE;
8307                         gboolean push_res = TRUE;
8308                         gboolean skip_ret = FALSE;
8309                         gboolean delegate_invoke = FALSE;
8310                         gboolean direct_icall = FALSE;
8311                         gboolean constrained_partial_call = FALSE;
8312                         MonoMethod *cil_method;
8313
8314                         CHECK_OPSIZE (5);
8315                         token = read32 (ip + 1);
8316
8317                         ins = NULL;
8318
8319                         cmethod = mini_get_method (cfg, method, token, NULL, generic_context);
8320                         CHECK_CFG_ERROR;
8321
8322                         cil_method = cmethod;
8323                                 
8324                         if (constrained_class) {
8325                                 if ((constrained_class->byval_arg.type == MONO_TYPE_VAR || constrained_class->byval_arg.type == MONO_TYPE_MVAR) && cfg->gshared) {
8326                                         if (!mini_is_gsharedvt_klass (constrained_class)) {
8327                                                 g_assert (!cmethod->klass->valuetype);
8328                                                 if (!mini_type_is_reference (&constrained_class->byval_arg))
8329                                                         constrained_partial_call = TRUE;
8330                                         }
8331                                 }
8332
8333                                 if (method->wrapper_type != MONO_WRAPPER_NONE) {
8334                                         if (cfg->verbose_level > 2)
8335                                                 printf ("DM Constrained call to %s\n", mono_type_get_full_name (constrained_class));
8336                                         if (!((constrained_class->byval_arg.type == MONO_TYPE_VAR ||
8337                                                    constrained_class->byval_arg.type == MONO_TYPE_MVAR) &&
8338                                                   cfg->gshared)) {
8339                                                 cmethod = mono_get_method_constrained_with_method (image, cil_method, constrained_class, generic_context, &cfg->error);
8340                                                 CHECK_CFG_ERROR;
8341                                         }
8342                                 } else {
8343                                         if (cfg->verbose_level > 2)
8344                                                 printf ("Constrained call to %s\n", mono_type_get_full_name (constrained_class));
8345
8346                                         if ((constrained_class->byval_arg.type == MONO_TYPE_VAR || constrained_class->byval_arg.type == MONO_TYPE_MVAR) && cfg->gshared) {
8347                                                 /* 
8348                                                  * This is needed since get_method_constrained can't find 
8349                                                  * the method in klass representing a type var.
8350                                                  * The type var is guaranteed to be a reference type in this
8351                                                  * case.
8352                                                  */
8353                                                 if (!mini_is_gsharedvt_klass (constrained_class))
8354                                                         g_assert (!cmethod->klass->valuetype);
8355                                         } else {
8356                                                 cmethod = mono_get_method_constrained_checked (image, token, constrained_class, generic_context, &cil_method, &cfg->error);
8357                                                 CHECK_CFG_ERROR;
8358                                         }
8359                                 }
8360
8361                                 if (constrained_class->enumtype && !strcmp (cmethod->name, "GetHashCode")) {
8362                                         /* Use the corresponding method from the base type to avoid boxing */
8363                                         MonoType *base_type = mono_class_enum_basetype (constrained_class);
8364                                         g_assert (base_type);
8365                                         constrained_class = mono_class_from_mono_type (base_type);
8366                                         cmethod = mono_class_get_method_from_name (constrained_class, cmethod->name, 0);
8367                                         g_assert (cmethod);
8368                                 }
8369                         }
8370                                         
8371                         if (!dont_verify && !cfg->skip_visibility) {
8372                                 MonoMethod *target_method = cil_method;
8373                                 if (method->is_inflated) {
8374                                         target_method = mini_get_method_allow_open (method, token, NULL, &(mono_method_get_generic_container (method_definition)->context), &cfg->error);
8375                                         CHECK_CFG_ERROR;
8376                                 }
8377                                 if (!mono_method_can_access_method (method_definition, target_method) &&
8378                                         !mono_method_can_access_method (method, cil_method))
8379                                         emit_method_access_failure (cfg, method, cil_method);
8380                         }
8381
8382                         if (mono_security_core_clr_enabled ())
8383                                 ensure_method_is_allowed_to_call_method (cfg, method, cil_method);
8384
8385                         if (!virtual_ && (cmethod->flags & METHOD_ATTRIBUTE_ABSTRACT))
8386                                 /* MS.NET seems to silently convert this to a callvirt */
8387                                 virtual_ = 1;
8388
8389                         {
8390                                 /*
8391                                  * MS.NET accepts non virtual calls to virtual final methods of transparent proxy classes and
8392                                  * converts to a callvirt.
8393                                  *
8394                                  * tests/bug-515884.il is an example of this behavior
8395                                  */
8396                                 const int test_flags = METHOD_ATTRIBUTE_VIRTUAL | METHOD_ATTRIBUTE_FINAL | METHOD_ATTRIBUTE_STATIC;
8397                                 const int expected_flags = METHOD_ATTRIBUTE_VIRTUAL | METHOD_ATTRIBUTE_FINAL;
8398                                 if (!virtual_ && mono_class_is_marshalbyref (cmethod->klass) && (cmethod->flags & test_flags) == expected_flags && cfg->method->wrapper_type == MONO_WRAPPER_NONE)
8399                                         virtual_ = 1;
8400                         }
8401
8402                         if (!cmethod->klass->inited)
8403                                 if (!mono_class_init (cmethod->klass))
8404                                         TYPE_LOAD_ERROR (cmethod->klass);
8405
8406                         fsig = mono_method_signature (cmethod);
8407                         if (!fsig)
8408                                 LOAD_ERROR;
8409                         if (cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL &&
8410                                 mini_class_is_system_array (cmethod->klass)) {
8411                                 array_rank = cmethod->klass->rank;
8412                         } else if ((cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && icall_is_direct_callable (cfg, cmethod)) {
8413                                 direct_icall = TRUE;
8414                         } else if (fsig->pinvoke) {
8415                                 MonoMethod *wrapper = mono_marshal_get_native_wrapper (cmethod, TRUE, cfg->compile_aot);
8416                                 fsig = mono_method_signature (wrapper);
8417                         } else if (constrained_class) {
8418                         } else {
8419                                 fsig = mono_method_get_signature_checked (cmethod, image, token, generic_context, &cfg->error);
8420                                 CHECK_CFG_ERROR;
8421                         }
8422
8423                         if (cfg->llvm_only && !cfg->method->wrapper_type && (!cmethod || cmethod->is_inflated))
8424                                 cfg->signatures = g_slist_prepend_mempool (cfg->mempool, cfg->signatures, fsig);
8425
8426                         /* See code below */
8427                         if (cmethod->klass == mono_defaults.monitor_class && !strcmp (cmethod->name, "Enter") && mono_method_signature (cmethod)->param_count == 1) {
8428                                 MonoBasicBlock *tbb;
8429
8430                                 GET_BBLOCK (cfg, tbb, ip + 5);
8431                                 if (tbb->try_start && MONO_REGION_FLAGS(tbb->region) == MONO_EXCEPTION_CLAUSE_FINALLY) {
8432                                         /*
8433                                          * We want to extend the try block to cover the call, but we can't do it if the
8434                                          * call is made directly since its followed by an exception check.
8435                                          */
8436                                         direct_icall = FALSE;
8437                                 }
8438                         }
8439
8440                         mono_save_token_info (cfg, image, token, cil_method);
8441
8442                         if (!(seq_point_locs && mono_bitset_test_fast (seq_point_locs, ip + 5 - header->code)))
8443                                 need_seq_point = TRUE;
8444
8445                         /* Don't support calls made using type arguments for now */
8446                         /*
8447                           if (cfg->gsharedvt) {
8448                           if (mini_is_gsharedvt_signature (fsig))
8449                           GSHAREDVT_FAILURE (*ip);
8450                           }
8451                         */
8452
8453                         if (cmethod->string_ctor && method->wrapper_type != MONO_WRAPPER_RUNTIME_INVOKE)
8454                                 g_assert_not_reached ();
8455
8456                         n = fsig->param_count + fsig->hasthis;
8457
8458                         if (!cfg->gshared && mono_class_is_gtd (cmethod->klass))
8459                                 UNVERIFIED;
8460
8461                         if (!cfg->gshared)
8462                                 g_assert (!mono_method_check_context_used (cmethod));
8463
8464                         CHECK_STACK (n);
8465
8466                         //g_assert (!virtual_ || fsig->hasthis);
8467
8468                         sp -= n;
8469
8470                         if (cmethod && cmethod->klass->image == mono_defaults.corlib && !strcmp (cmethod->klass->name, "ThrowHelper"))
8471                                 cfg->cbb->out_of_line = TRUE;
8472
8473                         /*
8474                          * We have the `constrained.' prefix opcode.
8475                          */
8476                         if (constrained_class) {
8477                                 if (mini_is_gsharedvt_klass (constrained_class)) {
8478                                         if ((cmethod->klass != mono_defaults.object_class) && constrained_class->valuetype && cmethod->klass->valuetype) {
8479                                                 /* The 'Own method' case below */
8480                                         } else if (cmethod->klass->image != mono_defaults.corlib && !mono_class_is_interface (cmethod->klass) && !cmethod->klass->valuetype) {
8481                                                 /* 'The type parameter is instantiated as a reference type' case below. */
8482                                         } else {
8483                                                 ins = handle_constrained_gsharedvt_call (cfg, cmethod, fsig, sp, constrained_class, &emit_widen);
8484                                                 CHECK_CFG_EXCEPTION;
8485                                                 g_assert (ins);
8486                                                 goto call_end;
8487                                         }
8488                                 }
8489
8490                                 if (constrained_partial_call) {
8491                                         gboolean need_box = TRUE;
8492
8493                                         /*
8494                                          * The receiver is a valuetype, but the exact type is not known at compile time. This means the
8495                                          * called method is not known at compile time either. The called method could end up being
8496                                          * one of the methods on the parent classes (object/valuetype/enum), in which case we need
8497                                          * to box the receiver.
8498                                          * A simple solution would be to box always and make a normal virtual call, but that would
8499                                          * be bad performance wise.
8500                                          */
8501                                         if (mono_class_is_interface (cmethod->klass) && mono_class_is_ginst (cmethod->klass)) {
8502                                                 /*
8503                                                  * The parent classes implement no generic interfaces, so the called method will be a vtype method, so no boxing neccessary.
8504                                                  */
8505                                                 need_box = FALSE;
8506                                         }
8507
8508                                         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)) {
8509                                                 /* The called method is not virtual, i.e. Object:GetType (), the receiver is a vtype, has to box */
8510                                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &constrained_class->byval_arg, sp [0]->dreg, 0);
8511                                                 ins->klass = constrained_class;
8512                                                 sp [0] = handle_box (cfg, ins, constrained_class, mono_class_check_context_used (constrained_class));
8513                                                 CHECK_CFG_EXCEPTION;
8514                                         } else if (need_box) {
8515                                                 MonoInst *box_type;
8516                                                 MonoBasicBlock *is_ref_bb, *end_bb;
8517                                                 MonoInst *nonbox_call;
8518
8519                                                 /*
8520                                                  * Determine at runtime whenever the called method is defined on object/valuetype/enum, and emit a boxing call
8521                                                  * if needed.
8522                                                  * FIXME: It is possible to inline the called method in a lot of cases, i.e. for T_INT,
8523                                                  * the no-box case goes to a method in Int32, while the box case goes to a method in Enum.
8524                                                  */
8525                                                 addr = emit_get_rgctx_virt_method (cfg, mono_class_check_context_used (constrained_class), constrained_class, cmethod, MONO_RGCTX_INFO_VIRT_METHOD_CODE);
8526
8527                                                 NEW_BBLOCK (cfg, is_ref_bb);
8528                                                 NEW_BBLOCK (cfg, end_bb);
8529
8530                                                 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);
8531                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, box_type->dreg, MONO_GSHAREDVT_BOX_TYPE_REF);
8532                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBEQ, is_ref_bb);
8533
8534                                                 /* Non-ref case */
8535                                                 nonbox_call = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
8536
8537                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
8538
8539                                                 /* Ref case */
8540                                                 MONO_START_BB (cfg, is_ref_bb);
8541                                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &constrained_class->byval_arg, sp [0]->dreg, 0);
8542                                                 ins->klass = constrained_class;
8543                                                 sp [0] = handle_box (cfg, ins, constrained_class, mono_class_check_context_used (constrained_class));
8544                                                 ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
8545
8546                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
8547
8548                                                 MONO_START_BB (cfg, end_bb);
8549                                                 cfg->cbb = end_bb;
8550
8551                                                 nonbox_call->dreg = ins->dreg;
8552                                                 goto call_end;
8553                                         } else {
8554                                                 g_assert (mono_class_is_interface (cmethod->klass));
8555                                                 addr = emit_get_rgctx_virt_method (cfg, mono_class_check_context_used (constrained_class), constrained_class, cmethod, MONO_RGCTX_INFO_VIRT_METHOD_CODE);
8556                                                 ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
8557                                                 goto call_end;
8558                                         }
8559                                 } else if (constrained_class->valuetype && (cmethod->klass == mono_defaults.object_class || cmethod->klass == mono_defaults.enum_class->parent || cmethod->klass == mono_defaults.enum_class)) {
8560                                         /*
8561                                          * The type parameter is instantiated as a valuetype,
8562                                          * but that type doesn't override the method we're
8563                                          * calling, so we need to box `this'.
8564                                          */
8565                                         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &constrained_class->byval_arg, sp [0]->dreg, 0);
8566                                         ins->klass = constrained_class;
8567                                         sp [0] = handle_box (cfg, ins, constrained_class, mono_class_check_context_used (constrained_class));
8568                                         CHECK_CFG_EXCEPTION;
8569                                 } else if (!constrained_class->valuetype) {
8570                                         int dreg = alloc_ireg_ref (cfg);
8571
8572                                         /*
8573                                          * The type parameter is instantiated as a reference
8574                                          * type.  We have a managed pointer on the stack, so
8575                                          * we need to dereference it here.
8576                                          */
8577                                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, dreg, sp [0]->dreg, 0);
8578                                         ins->type = STACK_OBJ;
8579                                         sp [0] = ins;
8580                                 } else {
8581                                         if (cmethod->klass->valuetype) {
8582                                                 /* Own method */
8583                                         } else {
8584                                                 /* Interface method */
8585                                                 int ioffset, slot;
8586
8587                                                 mono_class_setup_vtable (constrained_class);
8588                                                 CHECK_TYPELOAD (constrained_class);
8589                                                 ioffset = mono_class_interface_offset (constrained_class, cmethod->klass);
8590                                                 if (ioffset == -1)
8591                                                         TYPE_LOAD_ERROR (constrained_class);
8592                                                 slot = mono_method_get_vtable_slot (cmethod);
8593                                                 if (slot == -1)
8594                                                         TYPE_LOAD_ERROR (cmethod->klass);
8595                                                 cmethod = constrained_class->vtable [ioffset + slot];
8596
8597                                                 if (cmethod->klass == mono_defaults.enum_class) {
8598                                                         /* Enum implements some interfaces, so treat this as the first case */
8599                                                         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &constrained_class->byval_arg, sp [0]->dreg, 0);
8600                                                         ins->klass = constrained_class;
8601                                                         sp [0] = handle_box (cfg, ins, constrained_class, mono_class_check_context_used (constrained_class));
8602                                                         CHECK_CFG_EXCEPTION;
8603                                                 }
8604                                         }
8605                                         virtual_ = 0;
8606                                 }
8607                                 constrained_class = NULL;
8608                         }
8609
8610                         if (check_call_signature (cfg, fsig, sp))
8611                                 UNVERIFIED;
8612
8613                         if ((cmethod->klass->parent == mono_defaults.multicastdelegate_class) && !strcmp (cmethod->name, "Invoke"))
8614                                 delegate_invoke = TRUE;
8615
8616                         if ((cfg->opt & MONO_OPT_INTRINS) && (ins = mini_emit_inst_for_sharable_method (cfg, cmethod, fsig, sp))) {
8617                                 if (!MONO_TYPE_IS_VOID (fsig->ret)) {
8618                                         type_to_eval_stack_type ((cfg), fsig->ret, ins);
8619                                         emit_widen = FALSE;
8620                                 }
8621
8622                                 goto call_end;
8623                         }
8624
8625                         /* 
8626                          * If the callee is a shared method, then its static cctor
8627                          * might not get called after the call was patched.
8628                          */
8629                         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)) {
8630                                 emit_class_init (cfg, cmethod->klass);
8631                                 CHECK_TYPELOAD (cmethod->klass);
8632                         }
8633
8634                         check_method_sharing (cfg, cmethod, &pass_vtable, &pass_mrgctx);
8635
8636                         if (cfg->gshared) {
8637                                 MonoGenericContext *cmethod_context = mono_method_get_context (cmethod);
8638
8639                                 context_used = mini_method_check_context_used (cfg, cmethod);
8640
8641                                 if (context_used && mono_class_is_interface (cmethod->klass)) {
8642                                         /* Generic method interface
8643                                            calls are resolved via a
8644                                            helper function and don't
8645                                            need an imt. */
8646                                         if (!cmethod_context || !cmethod_context->method_inst)
8647                                                 pass_imt_from_rgctx = TRUE;
8648                                 }
8649
8650                                 /*
8651                                  * If a shared method calls another
8652                                  * shared method then the caller must
8653                                  * have a generic sharing context
8654                                  * because the magic trampoline
8655                                  * requires it.  FIXME: We shouldn't
8656                                  * have to force the vtable/mrgctx
8657                                  * variable here.  Instead there
8658                                  * should be a flag in the cfg to
8659                                  * request a generic sharing context.
8660                                  */
8661                                 if (context_used &&
8662                                                 ((cfg->method->flags & METHOD_ATTRIBUTE_STATIC) || cfg->method->klass->valuetype))
8663                                         mono_get_vtable_var (cfg);
8664                         }
8665
8666                         if (pass_vtable) {
8667                                 if (context_used) {
8668                                         vtable_arg = mini_emit_get_rgctx_klass (cfg, context_used, cmethod->klass, MONO_RGCTX_INFO_VTABLE);
8669                                 } else {
8670                                         MonoVTable *vtable = mono_class_vtable (cfg->domain, cmethod->klass);
8671
8672                                         CHECK_TYPELOAD (cmethod->klass);
8673                                         EMIT_NEW_VTABLECONST (cfg, vtable_arg, vtable);
8674                                 }
8675                         }
8676
8677                         if (pass_mrgctx) {
8678                                 g_assert (!vtable_arg);
8679
8680                                 if (!cfg->compile_aot) {
8681                                         /* 
8682                                          * emit_get_rgctx_method () calls mono_class_vtable () so check 
8683                                          * for type load errors before.
8684                                          */
8685                                         mono_class_setup_vtable (cmethod->klass);
8686                                         CHECK_TYPELOAD (cmethod->klass);
8687                                 }
8688
8689                                 vtable_arg = emit_get_rgctx_method (cfg, context_used, cmethod, MONO_RGCTX_INFO_METHOD_RGCTX);
8690
8691                                 /* !marshalbyref is needed to properly handle generic methods + remoting */
8692                                 if ((!(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) ||
8693                                          MONO_METHOD_IS_FINAL (cmethod)) &&
8694                                         !mono_class_is_marshalbyref (cmethod->klass)) {
8695                                         if (virtual_)
8696                                                 check_this = TRUE;
8697                                         virtual_ = 0;
8698                                 }
8699                         }
8700
8701                         if (pass_imt_from_rgctx) {
8702                                 g_assert (!pass_vtable);
8703
8704                                 imt_arg = emit_get_rgctx_method (cfg, context_used,
8705                                         cmethod, MONO_RGCTX_INFO_METHOD);
8706                         }
8707
8708                         if (check_this)
8709                                 MONO_EMIT_NEW_CHECK_THIS (cfg, sp [0]->dreg);
8710
8711                         /* Calling virtual generic methods */
8712                         if (virtual_ && (cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) &&
8713                             !(MONO_METHOD_IS_FINAL (cmethod) && 
8714                               cmethod->wrapper_type != MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK) &&
8715                             fsig->generic_param_count && 
8716                                 !(cfg->gsharedvt && mini_is_gsharedvt_signature (fsig)) &&
8717                                 !cfg->llvm_only) {
8718                                 MonoInst *this_temp, *this_arg_temp, *store;
8719                                 MonoInst *iargs [4];
8720
8721                                 g_assert (fsig->is_inflated);
8722
8723                                 /* Prevent inlining of methods that contain indirect calls */
8724                                 INLINE_FAILURE ("virtual generic call");
8725
8726                                 if (cfg->gsharedvt && mini_is_gsharedvt_signature (fsig))
8727                                         GSHAREDVT_FAILURE (*ip);
8728
8729                                 if (cfg->backend->have_generalized_imt_trampoline && cfg->backend->gshared_supported && cmethod->wrapper_type == MONO_WRAPPER_NONE) {
8730                                         g_assert (!imt_arg);
8731                                         if (!context_used)
8732                                                 g_assert (cmethod->is_inflated);
8733                                         imt_arg = emit_get_rgctx_method (cfg, context_used,
8734                                                                                                          cmethod, MONO_RGCTX_INFO_METHOD);
8735                                         ins = mono_emit_method_call_full (cfg, cmethod, fsig, FALSE, sp, sp [0], imt_arg, NULL);
8736                                 } else {
8737                                         this_temp = mono_compile_create_var (cfg, type_from_stack_type (sp [0]), OP_LOCAL);
8738                                         NEW_TEMPSTORE (cfg, store, this_temp->inst_c0, sp [0]);
8739                                         MONO_ADD_INS (cfg->cbb, store);
8740
8741                                         /* FIXME: This should be a managed pointer */
8742                                         this_arg_temp = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
8743
8744                                         EMIT_NEW_TEMPLOAD (cfg, iargs [0], this_temp->inst_c0);
8745                                         iargs [1] = emit_get_rgctx_method (cfg, context_used,
8746                                                                                                            cmethod, MONO_RGCTX_INFO_METHOD);
8747                                         EMIT_NEW_TEMPLOADA (cfg, iargs [2], this_arg_temp->inst_c0);
8748                                         addr = mono_emit_jit_icall (cfg,
8749                                                                                                 mono_helper_compile_generic_method, iargs);
8750
8751                                         EMIT_NEW_TEMPLOAD (cfg, sp [0], this_arg_temp->inst_c0);
8752
8753                                         ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
8754                                 }
8755
8756                                 goto call_end;
8757                         }
8758
8759                         /*
8760                          * Implement a workaround for the inherent races involved in locking:
8761                          * Monitor.Enter ()
8762                          * try {
8763                          * } finally {
8764                          *    Monitor.Exit ()
8765                          * }
8766                          * If a thread abort happens between the call to Monitor.Enter () and the start of the
8767                          * try block, the Exit () won't be executed, see:
8768                          * http://www.bluebytesoftware.com/blog/2007/01/30/MonitorEnterThreadAbortsAndOrphanedLocks.aspx
8769                          * To work around this, we extend such try blocks to include the last x bytes
8770                          * of the Monitor.Enter () call.
8771                          */
8772                         if (cmethod->klass == mono_defaults.monitor_class && !strcmp (cmethod->name, "Enter") && mono_method_signature (cmethod)->param_count == 1) {
8773                                 MonoBasicBlock *tbb;
8774
8775                                 GET_BBLOCK (cfg, tbb, ip + 5);
8776                                 /* 
8777                                  * Only extend try blocks with a finally, to avoid catching exceptions thrown
8778                                  * from Monitor.Enter like ArgumentNullException.
8779                                  */
8780                                 if (tbb->try_start && MONO_REGION_FLAGS(tbb->region) == MONO_EXCEPTION_CLAUSE_FINALLY) {
8781                                         /* Mark this bblock as needing to be extended */
8782                                         tbb->extend_try_block = TRUE;
8783                                 }
8784                         }
8785
8786                         /* Conversion to a JIT intrinsic */
8787                         if ((cfg->opt & MONO_OPT_INTRINS) && (ins = mini_emit_inst_for_method (cfg, cmethod, fsig, sp))) {
8788                                 if (!MONO_TYPE_IS_VOID (fsig->ret)) {
8789                                         type_to_eval_stack_type ((cfg), fsig->ret, ins);
8790                                         emit_widen = FALSE;
8791                                 }
8792                                 goto call_end;
8793                         }
8794                         CHECK_CFG_ERROR;
8795                         
8796                         /* Inlining */
8797                         if ((cfg->opt & MONO_OPT_INLINE) &&
8798                                 (!virtual_ || !(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) || MONO_METHOD_IS_FINAL (cmethod)) &&
8799                             mono_method_check_inlining (cfg, cmethod)) {
8800                                 int costs;
8801                                 gboolean always = FALSE;
8802
8803                                 if ((cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
8804                                         (cmethod->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
8805                                         /* Prevent inlining of methods that call wrappers */
8806                                         INLINE_FAILURE ("wrapper call");
8807                                         cmethod = mono_marshal_get_native_wrapper (cmethod, TRUE, FALSE);
8808                                         always = TRUE;
8809                                 }
8810
8811                                 costs = inline_method (cfg, cmethod, fsig, sp, ip, cfg->real_offset, always);
8812                                 if (costs) {
8813                                         cfg->real_offset += 5;
8814
8815                                         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
8816                                                 /* *sp is already set by inline_method */
8817                                                 sp++;
8818                                                 push_res = FALSE;
8819                                         }
8820
8821                                         inline_costs += costs;
8822
8823                                         goto call_end;
8824                                 }
8825                         }
8826
8827                         /* Tail recursion elimination */
8828                         if ((cfg->opt & MONO_OPT_TAILC) && call_opcode == CEE_CALL && cmethod == method && ip [5] == CEE_RET && !vtable_arg) {
8829                                 gboolean has_vtargs = FALSE;
8830                                 int i;
8831
8832                                 /* Prevent inlining of methods with tail calls (the call stack would be altered) */
8833                                 INLINE_FAILURE ("tail call");
8834
8835                                 /* keep it simple */
8836                                 for (i =  fsig->param_count - 1; i >= 0; i--) {
8837                                         if (MONO_TYPE_ISSTRUCT (mono_method_signature (cmethod)->params [i])) 
8838                                                 has_vtargs = TRUE;
8839                                 }
8840
8841                                 if (!has_vtargs) {
8842                                         if (need_seq_point) {
8843                                                 emit_seq_point (cfg, method, ip, FALSE, TRUE);
8844                                                 need_seq_point = FALSE;
8845                                         }
8846                                         for (i = 0; i < n; ++i)
8847                                                 EMIT_NEW_ARGSTORE (cfg, ins, i, sp [i]);
8848
8849                                         mini_profiler_emit_tail_call (cfg, cmethod);
8850
8851                                         MONO_INST_NEW (cfg, ins, OP_BR);
8852                                         MONO_ADD_INS (cfg->cbb, ins);
8853                                         tblock = start_bblock->out_bb [0];
8854                                         link_bblock (cfg, cfg->cbb, tblock);
8855                                         ins->inst_target_bb = tblock;
8856                                         start_new_bblock = 1;
8857
8858                                         /* skip the CEE_RET, too */
8859                                         if (ip_in_bb (cfg, cfg->cbb, ip + 5))
8860                                                 skip_ret = TRUE;
8861                                         push_res = FALSE;
8862                                         goto call_end;
8863                                 }
8864                         }
8865
8866                         inline_costs += 10 * num_calls++;
8867
8868                         /*
8869                          * Synchronized wrappers.
8870                          * Its hard to determine where to replace a method with its synchronized
8871                          * wrapper without causing an infinite recursion. The current solution is
8872                          * to add the synchronized wrapper in the trampolines, and to
8873                          * change the called method to a dummy wrapper, and resolve that wrapper
8874                          * to the real method in mono_jit_compile_method ().
8875                          */
8876                         if (cfg->method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED) {
8877                                 MonoMethod *orig = mono_marshal_method_from_wrapper (cfg->method);
8878                                 if (cmethod == orig || (cmethod->is_inflated && mono_method_get_declaring_generic_method (cmethod) == orig))
8879                                         cmethod = mono_marshal_get_synchronized_inner_wrapper (cmethod);
8880                         }
8881
8882                         /*
8883                          * Making generic calls out of gsharedvt methods.
8884                          * This needs to be used for all generic calls, not just ones with a gsharedvt signature, to avoid
8885                          * patching gshared method addresses into a gsharedvt method.
8886                          */
8887                         if (cfg->gsharedvt && (mini_is_gsharedvt_signature (fsig) || cmethod->is_inflated || mono_class_is_ginst (cmethod->klass)) &&
8888                                 !(cmethod->klass->rank && cmethod->klass->byval_arg.type != MONO_TYPE_SZARRAY) &&
8889                                 (!(cfg->llvm_only && virtual_ && (cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL)))) {
8890                                 MonoRgctxInfoType info_type;
8891
8892                                 if (virtual_) {
8893                                         //if (mono_class_is_interface (cmethod->klass))
8894                                                 //GSHAREDVT_FAILURE (*ip);
8895                                         // disable for possible remoting calls
8896                                         if (fsig->hasthis && (mono_class_is_marshalbyref (method->klass) || method->klass == mono_defaults.object_class))
8897                                                 GSHAREDVT_FAILURE (*ip);
8898                                         if (fsig->generic_param_count) {
8899                                                 /* virtual generic call */
8900                                                 g_assert (!imt_arg);
8901                                                 /* Same as the virtual generic case above */
8902                                                 imt_arg = emit_get_rgctx_method (cfg, context_used,
8903                                                                                                                  cmethod, MONO_RGCTX_INFO_METHOD);
8904                                                 /* This is not needed, as the trampoline code will pass one, and it might be passed in the same reg as the imt arg */
8905                                                 vtable_arg = NULL;
8906                                         } else if (mono_class_is_interface (cmethod->klass) && !imt_arg) {
8907                                                 /* This can happen when we call a fully instantiated iface method */
8908                                                 imt_arg = emit_get_rgctx_method (cfg, context_used,
8909                                                                                                                  cmethod, MONO_RGCTX_INFO_METHOD);
8910                                                 vtable_arg = NULL;
8911                                         }
8912                                 }
8913
8914                                 if ((cmethod->klass->parent == mono_defaults.multicastdelegate_class) && (!strcmp (cmethod->name, "Invoke")))
8915                                         keep_this_alive = sp [0];
8916
8917                                 if (virtual_ && (cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL))
8918                                         info_type = MONO_RGCTX_INFO_METHOD_GSHAREDVT_OUT_TRAMPOLINE_VIRT;
8919                                 else
8920                                         info_type = MONO_RGCTX_INFO_METHOD_GSHAREDVT_OUT_TRAMPOLINE;
8921                                 addr = emit_get_rgctx_gsharedvt_call (cfg, context_used, fsig, cmethod, info_type);
8922
8923                                 if (cfg->llvm_only) {
8924                                         // FIXME: Avoid initializing vtable_arg
8925                                         ins = emit_llvmonly_calli (cfg, fsig, sp, addr);
8926                                 } else {
8927                                         ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, imt_arg, vtable_arg);
8928                                 }
8929                                 goto call_end;
8930                         }
8931
8932                         /* Generic sharing */
8933
8934                         /*
8935                          * Use this if the callee is gsharedvt sharable too, since
8936                          * at runtime we might find an instantiation so the call cannot
8937                          * be patched (the 'no_patch' code path in mini-trampolines.c).
8938                          */
8939                         if (context_used && !imt_arg && !array_rank && !delegate_invoke &&
8940                                 (!mono_method_is_generic_sharable_full (cmethod, TRUE, FALSE, FALSE) ||
8941                                  !mono_class_generic_sharing_enabled (cmethod->klass)) &&
8942                                 (!virtual_ || MONO_METHOD_IS_FINAL (cmethod) ||
8943                                  !(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL))) {
8944                                 INLINE_FAILURE ("gshared");
8945
8946                                 g_assert (cfg->gshared && cmethod);
8947                                 g_assert (!addr);
8948
8949                                 /*
8950                                  * We are compiling a call to a
8951                                  * generic method from shared code,
8952                                  * which means that we have to look up
8953                                  * the method in the rgctx and do an
8954                                  * indirect call.
8955                                  */
8956                                 if (fsig->hasthis)
8957                                         MONO_EMIT_NEW_CHECK_THIS (cfg, sp [0]->dreg);
8958
8959                                 if (cfg->llvm_only) {
8960                                         if (cfg->gsharedvt && mini_is_gsharedvt_variable_signature (fsig))
8961                                                 addr = emit_get_rgctx_method (cfg, context_used, cmethod, MONO_RGCTX_INFO_GSHAREDVT_OUT_WRAPPER);
8962                                         else
8963                                                 addr = emit_get_rgctx_method (cfg, context_used, cmethod, MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
8964                                         // FIXME: Avoid initializing imt_arg/vtable_arg
8965                                         ins = emit_llvmonly_calli (cfg, fsig, sp, addr);
8966                                 } else {
8967                                         addr = emit_get_rgctx_method (cfg, context_used, cmethod, MONO_RGCTX_INFO_GENERIC_METHOD_CODE);
8968                                         ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, imt_arg, vtable_arg);
8969                                 }
8970                                 goto call_end;
8971                         }
8972
8973                         /* Direct calls to icalls */
8974                         if (direct_icall) {
8975                                 MonoMethod *wrapper;
8976                                 int costs;
8977
8978                                 /* Inline the wrapper */
8979                                 wrapper = mono_marshal_get_native_wrapper (cmethod, TRUE, cfg->compile_aot);
8980
8981                                 costs = inline_method (cfg, wrapper, fsig, sp, ip, cfg->real_offset, TRUE);
8982                                 g_assert (costs > 0);
8983                                 cfg->real_offset += 5;
8984
8985                                 if (!MONO_TYPE_IS_VOID (fsig->ret)) {
8986                                         /* *sp is already set by inline_method */
8987                                         sp++;
8988                                         push_res = FALSE;
8989                                 }
8990
8991                                 inline_costs += costs;
8992
8993                                 goto call_end;
8994                         }
8995                                         
8996                         /* Array methods */
8997                         if (array_rank) {
8998                                 MonoInst *addr;
8999
9000                                 if (strcmp (cmethod->name, "Set") == 0) { /* array Set */ 
9001                                         MonoInst *val = sp [fsig->param_count];
9002
9003                                         if (val->type == STACK_OBJ) {
9004                                                 MonoInst *iargs [2];
9005
9006                                                 iargs [0] = sp [0];
9007                                                 iargs [1] = val;
9008                                                 
9009                                                 mono_emit_jit_icall (cfg, mono_helper_stelem_ref_check, iargs);
9010                                         }
9011                                         
9012                                         addr = mini_emit_ldelema_ins (cfg, cmethod, sp, ip, TRUE);
9013                                         EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, fsig->params [fsig->param_count - 1], addr->dreg, 0, val->dreg);
9014                                         if (cfg->gen_write_barriers && val->type == STACK_OBJ && !MONO_INS_IS_PCONST_NULL (val))
9015                                                 mini_emit_write_barrier (cfg, addr, val);
9016                                         if (cfg->gen_write_barriers && mini_is_gsharedvt_klass (cmethod->klass))
9017                                                 GSHAREDVT_FAILURE (*ip);
9018                                 } else if (strcmp (cmethod->name, "Get") == 0) { /* array Get */
9019                                         addr = mini_emit_ldelema_ins (cfg, cmethod, sp, ip, FALSE);
9020
9021                                         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, fsig->ret, addr->dreg, 0);
9022                                 } else if (strcmp (cmethod->name, "Address") == 0) { /* array Address */
9023                                         if (!cmethod->klass->element_class->valuetype && !readonly)
9024                                                 mini_emit_check_array_type (cfg, sp [0], cmethod->klass);
9025                                         CHECK_TYPELOAD (cmethod->klass);
9026                                         
9027                                         readonly = FALSE;
9028                                         addr = mini_emit_ldelema_ins (cfg, cmethod, sp, ip, FALSE);
9029                                         ins = addr;
9030                                 } else {
9031                                         g_assert_not_reached ();
9032                                 }
9033
9034                                 emit_widen = FALSE;
9035                                 goto call_end;
9036                         }
9037
9038                         ins = mini_redirect_call (cfg, cmethod, fsig, sp, virtual_ ? sp [0] : NULL);
9039                         if (ins)
9040                                 goto call_end;
9041
9042                         /* Tail prefix / tail call optimization */
9043
9044                         /* FIXME: Enabling TAILC breaks some inlining/stack trace/etc tests */
9045                         /* FIXME: runtime generic context pointer for jumps? */
9046                         /* FIXME: handle this for generic sharing eventually */
9047                         if ((ins_flag & MONO_INST_TAILCALL) &&
9048                                 !vtable_arg && !cfg->gshared && is_supported_tail_call (cfg, method, cmethod, fsig, call_opcode))
9049                                 supported_tail_call = TRUE;
9050
9051                         if (supported_tail_call) {
9052                                 MonoCallInst *call;
9053
9054                                 /* Prevent inlining of methods with tail calls (the call stack would be altered) */
9055                                 INLINE_FAILURE ("tail call");
9056
9057                                 //printf ("HIT: %s -> %s\n", mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
9058
9059                                 if (cfg->backend->have_op_tail_call) {
9060                                         /* Handle tail calls similarly to normal calls */
9061                                         tail_call = TRUE;
9062                                 } else {
9063                                         mini_profiler_emit_tail_call (cfg, cmethod);
9064
9065                                         MONO_INST_NEW_CALL (cfg, call, OP_JMP);
9066                                         call->tail_call = TRUE;
9067                                         call->method = cmethod;
9068                                         call->signature = mono_method_signature (cmethod);
9069
9070                                         /*
9071                                          * We implement tail calls by storing the actual arguments into the 
9072                                          * argument variables, then emitting a CEE_JMP.
9073                                          */
9074                                         for (i = 0; i < n; ++i) {
9075                                                 /* Prevent argument from being register allocated */
9076                                                 arg_array [i]->flags |= MONO_INST_VOLATILE;
9077                                                 EMIT_NEW_ARGSTORE (cfg, ins, i, sp [i]);
9078                                         }
9079                                         ins = (MonoInst*)call;
9080                                         ins->inst_p0 = cmethod;
9081                                         ins->inst_p1 = arg_array [0];
9082                                         MONO_ADD_INS (cfg->cbb, ins);
9083                                         link_bblock (cfg, cfg->cbb, end_bblock);
9084                                         start_new_bblock = 1;
9085
9086                                         // FIXME: Eliminate unreachable epilogs
9087
9088                                         /*
9089                                          * OP_TAILCALL has no return value, so skip the CEE_RET if it is
9090                                          * only reachable from this call.
9091                                          */
9092                                         GET_BBLOCK (cfg, tblock, ip + 5);
9093                                         if (tblock == cfg->cbb || tblock->in_count == 0)
9094                                                 skip_ret = TRUE;
9095                                         push_res = FALSE;
9096
9097                                         goto call_end;
9098                                 }
9099                         }
9100
9101                         /*
9102                          * Virtual calls in llvm-only mode.
9103                          */
9104                         if (cfg->llvm_only && virtual_ && cmethod && (cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
9105                                 ins = emit_llvmonly_virtual_call (cfg, cmethod, fsig, context_used, sp);
9106                                 goto call_end;
9107                         }
9108
9109                         /* Common call */
9110                         if (!(method->iflags & METHOD_IMPL_ATTRIBUTE_AGGRESSIVE_INLINING) && !(cmethod->iflags & METHOD_IMPL_ATTRIBUTE_AGGRESSIVE_INLINING))
9111                                 INLINE_FAILURE ("call");
9112                         ins = mono_emit_method_call_full (cfg, cmethod, fsig, tail_call, sp, virtual_ ? sp [0] : NULL,
9113                                                                                           imt_arg, vtable_arg);
9114
9115                         if (tail_call && !cfg->llvm_only) {
9116                                 link_bblock (cfg, cfg->cbb, end_bblock);
9117                                 start_new_bblock = 1;
9118
9119                                 // FIXME: Eliminate unreachable epilogs
9120
9121                                 /*
9122                                  * OP_TAILCALL has no return value, so skip the CEE_RET if it is
9123                                  * only reachable from this call.
9124                                  */
9125                                 GET_BBLOCK (cfg, tblock, ip + 5);
9126                                 if (tblock == cfg->cbb || tblock->in_count == 0)
9127                                         skip_ret = TRUE;
9128                                 push_res = FALSE;
9129                         }
9130
9131                         call_end:
9132
9133                         /* End of call, INS should contain the result of the call, if any */
9134
9135                         if (push_res && !MONO_TYPE_IS_VOID (fsig->ret)) {
9136                                 g_assert (ins);
9137                                 if (emit_widen)
9138                                         *sp++ = mono_emit_widen_call_res (cfg, ins, fsig);
9139                                 else
9140                                         *sp++ = ins;
9141                         }
9142
9143                         if (keep_this_alive) {
9144                                 MonoInst *dummy_use;
9145
9146                                 /* See mono_emit_method_call_full () */
9147                                 EMIT_NEW_DUMMY_USE (cfg, dummy_use, keep_this_alive);
9148                         }
9149
9150                         if (cfg->llvm_only && cmethod && method_needs_stack_walk (cfg, cmethod)) {
9151                                 /*
9152                                  * Clang can convert these calls to tail calls which screw up the stack
9153                                  * walk. This happens even when the -fno-optimize-sibling-calls
9154                                  * option is passed to clang.
9155                                  * Work around this by emitting a dummy call.
9156                                  */
9157                                 mono_emit_jit_icall (cfg, mono_dummy_jit_icall, NULL);
9158                         }
9159
9160                         CHECK_CFG_EXCEPTION;
9161
9162                         ip += 5;
9163                         if (skip_ret) {
9164                                 g_assert (*ip == CEE_RET);
9165                                 ip += 1;
9166                         }
9167                         ins_flag = 0;
9168                         constrained_class = NULL;
9169                         if (need_seq_point)
9170                                 emit_seq_point (cfg, method, ip, FALSE, TRUE);
9171                         break;
9172                 }
9173                 case CEE_RET:
9174                         mini_profiler_emit_leave (cfg, sig->ret->type != MONO_TYPE_VOID ? sp [-1] : NULL);
9175
9176                         if (cfg->method != method) {
9177                                 /* return from inlined method */
9178                                 /* 
9179                                  * If in_count == 0, that means the ret is unreachable due to
9180                                  * being preceeded by a throw. In that case, inline_method () will
9181                                  * handle setting the return value 
9182                                  * (test case: test_0_inline_throw ()).
9183                                  */
9184                                 if (return_var && cfg->cbb->in_count) {
9185                                         MonoType *ret_type = mono_method_signature (method)->ret;
9186
9187                                         MonoInst *store;
9188                                         CHECK_STACK (1);
9189                                         --sp;
9190
9191                                         if ((method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD || method->wrapper_type == MONO_WRAPPER_NONE) && target_type_is_incompatible (cfg, ret_type, *sp))
9192                                                 UNVERIFIED;
9193
9194                                         //g_assert (returnvar != -1);
9195                                         EMIT_NEW_TEMPSTORE (cfg, store, return_var->inst_c0, *sp);
9196                                         cfg->ret_var_set = TRUE;
9197                                 } 
9198                         } else {
9199                                 if (cfg->lmf_var && cfg->cbb->in_count && !cfg->llvm_only)
9200                                         emit_pop_lmf (cfg);
9201
9202                                 if (cfg->ret) {
9203                                         MonoType *ret_type = mini_get_underlying_type (mono_method_signature (method)->ret);
9204
9205                                         if (seq_points && !sym_seq_points) {
9206                                                 /* 
9207                                                  * Place a seq point here too even through the IL stack is not
9208                                                  * empty, so a step over on
9209                                                  * call <FOO>
9210                                                  * ret
9211                                                  * will work correctly.
9212                                                  */
9213                                                 NEW_SEQ_POINT (cfg, ins, ip - header->code, TRUE);
9214                                                 MONO_ADD_INS (cfg->cbb, ins);
9215                                         }
9216
9217                                         g_assert (!return_var);
9218                                         CHECK_STACK (1);
9219                                         --sp;
9220
9221                                         if ((method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD || method->wrapper_type == MONO_WRAPPER_NONE) && target_type_is_incompatible (cfg, ret_type, *sp))
9222                                                 UNVERIFIED;
9223
9224                                         emit_setret (cfg, *sp);
9225                                 }
9226                         }
9227                         if (sp != stack_start)
9228                                 UNVERIFIED;
9229                         MONO_INST_NEW (cfg, ins, OP_BR);
9230                         ip++;
9231                         ins->inst_target_bb = end_bblock;
9232                         MONO_ADD_INS (cfg->cbb, ins);
9233                         link_bblock (cfg, cfg->cbb, end_bblock);
9234                         start_new_bblock = 1;
9235                         break;
9236                 case CEE_BR_S:
9237                         CHECK_OPSIZE (2);
9238                         MONO_INST_NEW (cfg, ins, OP_BR);
9239                         ip++;
9240                         target = ip + 1 + (signed char)(*ip);
9241                         ++ip;
9242                         GET_BBLOCK (cfg, tblock, target);
9243                         link_bblock (cfg, cfg->cbb, tblock);
9244                         ins->inst_target_bb = tblock;
9245                         if (sp != stack_start) {
9246                                 handle_stack_args (cfg, stack_start, sp - stack_start);
9247                                 sp = stack_start;
9248                                 CHECK_UNVERIFIABLE (cfg);
9249                         }
9250                         MONO_ADD_INS (cfg->cbb, ins);
9251                         start_new_bblock = 1;
9252                         inline_costs += BRANCH_COST;
9253                         break;
9254                 case CEE_BEQ_S:
9255                 case CEE_BGE_S:
9256                 case CEE_BGT_S:
9257                 case CEE_BLE_S:
9258                 case CEE_BLT_S:
9259                 case CEE_BNE_UN_S:
9260                 case CEE_BGE_UN_S:
9261                 case CEE_BGT_UN_S:
9262                 case CEE_BLE_UN_S:
9263                 case CEE_BLT_UN_S:
9264                         CHECK_OPSIZE (2);
9265                         CHECK_STACK (2);
9266                         MONO_INST_NEW (cfg, ins, *ip + BIG_BRANCH_OFFSET);
9267                         ip++;
9268                         target = ip + 1 + *(signed char*)ip;
9269                         ip++;
9270
9271                         ADD_BINCOND (NULL);
9272
9273                         sp = stack_start;
9274                         inline_costs += BRANCH_COST;
9275                         break;
9276                 case CEE_BR:
9277                         CHECK_OPSIZE (5);
9278                         MONO_INST_NEW (cfg, ins, OP_BR);
9279                         ip++;
9280
9281                         target = ip + 4 + (gint32)read32(ip);
9282                         ip += 4;
9283                         GET_BBLOCK (cfg, tblock, target);
9284                         link_bblock (cfg, cfg->cbb, tblock);
9285                         ins->inst_target_bb = tblock;
9286                         if (sp != stack_start) {
9287                                 handle_stack_args (cfg, stack_start, sp - stack_start);
9288                                 sp = stack_start;
9289                                 CHECK_UNVERIFIABLE (cfg);
9290                         }
9291
9292                         MONO_ADD_INS (cfg->cbb, ins);
9293
9294                         start_new_bblock = 1;
9295                         inline_costs += BRANCH_COST;
9296                         break;
9297                 case CEE_BRFALSE_S:
9298                 case CEE_BRTRUE_S:
9299                 case CEE_BRFALSE:
9300                 case CEE_BRTRUE: {
9301                         MonoInst *cmp;
9302                         gboolean is_short = ((*ip) == CEE_BRFALSE_S) || ((*ip) == CEE_BRTRUE_S);
9303                         gboolean is_true = ((*ip) == CEE_BRTRUE_S) || ((*ip) == CEE_BRTRUE);
9304                         guint32 opsize = is_short ? 1 : 4;
9305
9306                         CHECK_OPSIZE (opsize);
9307                         CHECK_STACK (1);
9308                         if (sp [-1]->type == STACK_VTYPE || sp [-1]->type == STACK_R8)
9309                                 UNVERIFIED;
9310                         ip ++;
9311                         target = ip + opsize + (is_short ? *(signed char*)ip : (gint32)read32(ip));
9312                         ip += opsize;
9313
9314                         sp--;
9315
9316                         GET_BBLOCK (cfg, tblock, target);
9317                         link_bblock (cfg, cfg->cbb, tblock);
9318                         GET_BBLOCK (cfg, tblock, ip);
9319                         link_bblock (cfg, cfg->cbb, tblock);
9320
9321                         if (sp != stack_start) {
9322                                 handle_stack_args (cfg, stack_start, sp - stack_start);
9323                                 CHECK_UNVERIFIABLE (cfg);
9324                         }
9325
9326                         MONO_INST_NEW(cfg, cmp, OP_ICOMPARE_IMM);
9327                         cmp->sreg1 = sp [0]->dreg;
9328                         type_from_op (cfg, cmp, sp [0], NULL);
9329                         CHECK_TYPE (cmp);
9330
9331 #if SIZEOF_REGISTER == 4
9332                         if (cmp->opcode == OP_LCOMPARE_IMM) {
9333                                 /* Convert it to OP_LCOMPARE */
9334                                 MONO_INST_NEW (cfg, ins, OP_I8CONST);
9335                                 ins->type = STACK_I8;
9336                                 ins->dreg = alloc_dreg (cfg, STACK_I8);
9337                                 ins->inst_l = 0;
9338                                 MONO_ADD_INS (cfg->cbb, ins);
9339                                 cmp->opcode = OP_LCOMPARE;
9340                                 cmp->sreg2 = ins->dreg;
9341                         }
9342 #endif
9343                         MONO_ADD_INS (cfg->cbb, cmp);
9344
9345                         MONO_INST_NEW (cfg, ins, is_true ? CEE_BNE_UN : CEE_BEQ);
9346                         type_from_op (cfg, ins, sp [0], NULL);
9347                         MONO_ADD_INS (cfg->cbb, ins);
9348                         ins->inst_many_bb = (MonoBasicBlock **)mono_mempool_alloc (cfg->mempool, sizeof(gpointer)*2);
9349                         GET_BBLOCK (cfg, tblock, target);
9350                         ins->inst_true_bb = tblock;
9351                         GET_BBLOCK (cfg, tblock, ip);
9352                         ins->inst_false_bb = tblock;
9353                         start_new_bblock = 2;
9354
9355                         sp = stack_start;
9356                         inline_costs += BRANCH_COST;
9357                         break;
9358                 }
9359                 case CEE_BEQ:
9360                 case CEE_BGE:
9361                 case CEE_BGT:
9362                 case CEE_BLE:
9363                 case CEE_BLT:
9364                 case CEE_BNE_UN:
9365                 case CEE_BGE_UN:
9366                 case CEE_BGT_UN:
9367                 case CEE_BLE_UN:
9368                 case CEE_BLT_UN:
9369                         CHECK_OPSIZE (5);
9370                         CHECK_STACK (2);
9371                         MONO_INST_NEW (cfg, ins, *ip);
9372                         ip++;
9373                         target = ip + 4 + (gint32)read32(ip);
9374                         ip += 4;
9375
9376                         ADD_BINCOND (NULL);
9377
9378                         sp = stack_start;
9379                         inline_costs += BRANCH_COST;
9380                         break;
9381                 case CEE_SWITCH: {
9382                         MonoInst *src1;
9383                         MonoBasicBlock **targets;
9384                         MonoBasicBlock *default_bblock;
9385                         MonoJumpInfoBBTable *table;
9386                         int offset_reg = alloc_preg (cfg);
9387                         int target_reg = alloc_preg (cfg);
9388                         int table_reg = alloc_preg (cfg);
9389                         int sum_reg = alloc_preg (cfg);
9390                         gboolean use_op_switch;
9391
9392                         CHECK_OPSIZE (5);
9393                         CHECK_STACK (1);
9394                         n = read32 (ip + 1);
9395                         --sp;
9396                         src1 = sp [0];
9397                         if ((src1->type != STACK_I4) && (src1->type != STACK_PTR)) 
9398                                 UNVERIFIED;
9399
9400                         ip += 5;
9401                         CHECK_OPSIZE (n * sizeof (guint32));
9402                         target = ip + n * sizeof (guint32);
9403
9404                         GET_BBLOCK (cfg, default_bblock, target);
9405                         default_bblock->flags |= BB_INDIRECT_JUMP_TARGET;
9406
9407                         targets = (MonoBasicBlock **)mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * n);
9408                         for (i = 0; i < n; ++i) {
9409                                 GET_BBLOCK (cfg, tblock, target + (gint32)read32(ip));
9410                                 targets [i] = tblock;
9411                                 targets [i]->flags |= BB_INDIRECT_JUMP_TARGET;
9412                                 ip += 4;
9413                         }
9414
9415                         if (sp != stack_start) {
9416                                 /* 
9417                                  * Link the current bb with the targets as well, so handle_stack_args
9418                                  * will set their in_stack correctly.
9419                                  */
9420                                 link_bblock (cfg, cfg->cbb, default_bblock);
9421                                 for (i = 0; i < n; ++i)
9422                                         link_bblock (cfg, cfg->cbb, targets [i]);
9423
9424                                 handle_stack_args (cfg, stack_start, sp - stack_start);
9425                                 sp = stack_start;
9426                                 CHECK_UNVERIFIABLE (cfg);
9427
9428                                 /* Undo the links */
9429                                 mono_unlink_bblock (cfg, cfg->cbb, default_bblock);
9430                                 for (i = 0; i < n; ++i)
9431                                         mono_unlink_bblock (cfg, cfg->cbb, targets [i]);
9432                         }
9433
9434                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ICOMPARE_IMM, -1, src1->dreg, n);
9435                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_IBGE_UN, default_bblock);
9436
9437                         for (i = 0; i < n; ++i)
9438                                 link_bblock (cfg, cfg->cbb, targets [i]);
9439
9440                         table = (MonoJumpInfoBBTable *)mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfoBBTable));
9441                         table->table = targets;
9442                         table->table_size = n;
9443
9444                         use_op_switch = FALSE;
9445 #ifdef TARGET_ARM
9446                         /* ARM implements SWITCH statements differently */
9447                         /* FIXME: Make it use the generic implementation */
9448                         if (!cfg->compile_aot)
9449                                 use_op_switch = TRUE;
9450 #endif
9451
9452                         if (COMPILE_LLVM (cfg))
9453                                 use_op_switch = TRUE;
9454
9455                         cfg->cbb->has_jump_table = 1;
9456
9457                         if (use_op_switch) {
9458                                 MONO_INST_NEW (cfg, ins, OP_SWITCH);
9459                                 ins->sreg1 = src1->dreg;
9460                                 ins->inst_p0 = table;
9461                                 ins->inst_many_bb = targets;
9462                                 ins->klass = (MonoClass *)GUINT_TO_POINTER (n);
9463                                 MONO_ADD_INS (cfg->cbb, ins);
9464                         } else {
9465                                 if (sizeof (gpointer) == 8)
9466                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHL_IMM, offset_reg, src1->dreg, 3);
9467                                 else
9468                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHL_IMM, offset_reg, src1->dreg, 2);
9469
9470 #if SIZEOF_REGISTER == 8
9471                                 /* The upper word might not be zero, and we add it to a 64 bit address later */
9472                                 MONO_EMIT_NEW_UNALU (cfg, OP_ZEXT_I4, offset_reg, offset_reg);
9473 #endif
9474
9475                                 if (cfg->compile_aot) {
9476                                         MONO_EMIT_NEW_AOTCONST (cfg, table_reg, table, MONO_PATCH_INFO_SWITCH);
9477                                 } else {
9478                                         MONO_INST_NEW (cfg, ins, OP_JUMP_TABLE);
9479                                         ins->inst_c1 = MONO_PATCH_INFO_SWITCH;
9480                                         ins->inst_p0 = table;
9481                                         ins->dreg = table_reg;
9482                                         MONO_ADD_INS (cfg->cbb, ins);
9483                                 }
9484
9485                                 /* FIXME: Use load_memindex */
9486                                 MONO_EMIT_NEW_BIALU (cfg, OP_PADD, sum_reg, table_reg, offset_reg);
9487                                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, target_reg, sum_reg, 0);
9488                                 MONO_EMIT_NEW_UNALU (cfg, OP_BR_REG, -1, target_reg);
9489                         }
9490                         start_new_bblock = 1;
9491                         inline_costs += (BRANCH_COST * 2);
9492                         break;
9493                 }
9494                 case CEE_LDIND_I1:
9495                 case CEE_LDIND_U1:
9496                 case CEE_LDIND_I2:
9497                 case CEE_LDIND_U2:
9498                 case CEE_LDIND_I4:
9499                 case CEE_LDIND_U4:
9500                 case CEE_LDIND_I8:
9501                 case CEE_LDIND_I:
9502                 case CEE_LDIND_R4:
9503                 case CEE_LDIND_R8:
9504                 case CEE_LDIND_REF:
9505                         CHECK_STACK (1);
9506                         --sp;
9507
9508                         ins = mini_emit_memory_load (cfg, &ldind_to_type (*ip)->byval_arg, sp [0], 0, ins_flag);
9509                         *sp++ = ins;
9510                         ins_flag = 0;
9511                         ++ip;
9512                         break;
9513                 case CEE_STIND_REF:
9514                 case CEE_STIND_I1:
9515                 case CEE_STIND_I2:
9516                 case CEE_STIND_I4:
9517                 case CEE_STIND_I8:
9518                 case CEE_STIND_R4:
9519                 case CEE_STIND_R8:
9520                 case CEE_STIND_I:
9521                         CHECK_STACK (2);
9522                         sp -= 2;
9523
9524                         if (ins_flag & MONO_INST_VOLATILE) {
9525                                 /* Volatile stores have release semantics, see 12.6.7 in Ecma 335 */
9526                                 mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_REL);
9527                         }
9528
9529                         NEW_STORE_MEMBASE (cfg, ins, stind_to_store_membase (*ip), sp [0]->dreg, 0, sp [1]->dreg);
9530                         ins->flags |= ins_flag;
9531                         ins_flag = 0;
9532
9533                         MONO_ADD_INS (cfg->cbb, ins);
9534
9535                         if (cfg->gen_write_barriers && *ip == CEE_STIND_REF && method->wrapper_type != MONO_WRAPPER_WRITE_BARRIER && !MONO_INS_IS_PCONST_NULL (sp [1]))
9536                                 mini_emit_write_barrier (cfg, sp [0], sp [1]);
9537
9538                         inline_costs += 1;
9539                         ++ip;
9540                         break;
9541
9542                 case CEE_MUL:
9543                         CHECK_STACK (2);
9544
9545                         MONO_INST_NEW (cfg, ins, (*ip));
9546                         sp -= 2;
9547                         ins->sreg1 = sp [0]->dreg;
9548                         ins->sreg2 = sp [1]->dreg;
9549                         type_from_op (cfg, ins, sp [0], sp [1]);
9550                         CHECK_TYPE (ins);
9551                         ins->dreg = alloc_dreg ((cfg), (MonoStackType)(ins)->type);
9552
9553                         /* Use the immediate opcodes if possible */
9554                         if ((sp [1]->opcode == OP_ICONST) && mono_arch_is_inst_imm (sp [1]->inst_c0)) {
9555                                 int imm_opcode = mono_op_to_op_imm_noemul (ins->opcode);
9556                                 if (imm_opcode != -1) {
9557                                         ins->opcode = imm_opcode;
9558                                         ins->inst_p1 = (gpointer)(gssize)(sp [1]->inst_c0);
9559                                         ins->sreg2 = -1;
9560
9561                                         NULLIFY_INS (sp [1]);
9562                                 }
9563                         }
9564
9565                         MONO_ADD_INS ((cfg)->cbb, (ins));
9566
9567                         *sp++ = mono_decompose_opcode (cfg, ins);
9568                         ip++;
9569                         break;
9570                 case CEE_ADD:
9571                 case CEE_SUB:
9572                 case CEE_DIV:
9573                 case CEE_DIV_UN:
9574                 case CEE_REM:
9575                 case CEE_REM_UN:
9576                 case CEE_AND:
9577                 case CEE_OR:
9578                 case CEE_XOR:
9579                 case CEE_SHL:
9580                 case CEE_SHR:
9581                 case CEE_SHR_UN:
9582                         CHECK_STACK (2);
9583
9584                         MONO_INST_NEW (cfg, ins, (*ip));
9585                         sp -= 2;
9586                         ins->sreg1 = sp [0]->dreg;
9587                         ins->sreg2 = sp [1]->dreg;
9588                         type_from_op (cfg, ins, sp [0], sp [1]);
9589                         CHECK_TYPE (ins);
9590                         add_widen_op (cfg, ins, &sp [0], &sp [1]);
9591                         ins->dreg = alloc_dreg ((cfg), (MonoStackType)(ins)->type);
9592
9593                         /* FIXME: Pass opcode to is_inst_imm */
9594
9595                         /* Use the immediate opcodes if possible */
9596                         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)) {
9597                                 int imm_opcode = mono_op_to_op_imm_noemul (ins->opcode);
9598                                 if (imm_opcode != -1) {
9599                                         ins->opcode = imm_opcode;
9600                                         if (sp [1]->opcode == OP_I8CONST) {
9601 #if SIZEOF_REGISTER == 8
9602                                                 ins->inst_imm = sp [1]->inst_l;
9603 #else
9604                                                 ins->inst_ls_word = sp [1]->inst_ls_word;
9605                                                 ins->inst_ms_word = sp [1]->inst_ms_word;
9606 #endif
9607                                         }
9608                                         else
9609                                                 ins->inst_imm = (gssize)(sp [1]->inst_c0);
9610                                         ins->sreg2 = -1;
9611
9612                                         /* Might be followed by an instruction added by add_widen_op */
9613                                         if (sp [1]->next == NULL)
9614                                                 NULLIFY_INS (sp [1]);
9615                                 }
9616                         }
9617                         MONO_ADD_INS ((cfg)->cbb, (ins));
9618
9619                         *sp++ = mono_decompose_opcode (cfg, ins);
9620                         ip++;
9621                         break;
9622                 case CEE_NEG:
9623                 case CEE_NOT:
9624                 case CEE_CONV_I1:
9625                 case CEE_CONV_I2:
9626                 case CEE_CONV_I4:
9627                 case CEE_CONV_R4:
9628                 case CEE_CONV_R8:
9629                 case CEE_CONV_U4:
9630                 case CEE_CONV_I8:
9631                 case CEE_CONV_U8:
9632                 case CEE_CONV_OVF_I8:
9633                 case CEE_CONV_OVF_U8:
9634                 case CEE_CONV_R_UN:
9635                         CHECK_STACK (1);
9636
9637                         /* Special case this earlier so we have long constants in the IR */
9638                         if ((((*ip) == CEE_CONV_I8) || ((*ip) == CEE_CONV_U8)) && (sp [-1]->opcode == OP_ICONST)) {
9639                                 int data = sp [-1]->inst_c0;
9640                                 sp [-1]->opcode = OP_I8CONST;
9641                                 sp [-1]->type = STACK_I8;
9642 #if SIZEOF_REGISTER == 8
9643                                 if ((*ip) == CEE_CONV_U8)
9644                                         sp [-1]->inst_c0 = (guint32)data;
9645                                 else
9646                                         sp [-1]->inst_c0 = data;
9647 #else
9648                                 sp [-1]->inst_ls_word = data;
9649                                 if ((*ip) == CEE_CONV_U8)
9650                                         sp [-1]->inst_ms_word = 0;
9651                                 else
9652                                         sp [-1]->inst_ms_word = (data < 0) ? -1 : 0;
9653 #endif
9654                                 sp [-1]->dreg = alloc_dreg (cfg, STACK_I8);
9655                         }
9656                         else {
9657                                 ADD_UNOP (*ip);
9658                         }
9659                         ip++;
9660                         break;
9661                 case CEE_CONV_OVF_I4:
9662                 case CEE_CONV_OVF_I1:
9663                 case CEE_CONV_OVF_I2:
9664                 case CEE_CONV_OVF_I:
9665                 case CEE_CONV_OVF_U:
9666                         CHECK_STACK (1);
9667
9668                         if (sp [-1]->type == STACK_R8 || sp [-1]->type == STACK_R4) {
9669                                 ADD_UNOP (CEE_CONV_OVF_I8);
9670                                 ADD_UNOP (*ip);
9671                         } else {
9672                                 ADD_UNOP (*ip);
9673                         }
9674                         ip++;
9675                         break;
9676                 case CEE_CONV_OVF_U1:
9677                 case CEE_CONV_OVF_U2:
9678                 case CEE_CONV_OVF_U4:
9679                         CHECK_STACK (1);
9680
9681                         if (sp [-1]->type == STACK_R8 || sp [-1]->type == STACK_R4) {
9682                                 ADD_UNOP (CEE_CONV_OVF_U8);
9683                                 ADD_UNOP (*ip);
9684                         } else {
9685                                 ADD_UNOP (*ip);
9686                         }
9687                         ip++;
9688                         break;
9689                 case CEE_CONV_OVF_I1_UN:
9690                 case CEE_CONV_OVF_I2_UN:
9691                 case CEE_CONV_OVF_I4_UN:
9692                 case CEE_CONV_OVF_I8_UN:
9693                 case CEE_CONV_OVF_U1_UN:
9694                 case CEE_CONV_OVF_U2_UN:
9695                 case CEE_CONV_OVF_U4_UN:
9696                 case CEE_CONV_OVF_U8_UN:
9697                 case CEE_CONV_OVF_I_UN:
9698                 case CEE_CONV_OVF_U_UN:
9699                 case CEE_CONV_U2:
9700                 case CEE_CONV_U1:
9701                 case CEE_CONV_I:
9702                 case CEE_CONV_U:
9703                         CHECK_STACK (1);
9704                         ADD_UNOP (*ip);
9705                         CHECK_CFG_EXCEPTION;
9706                         ip++;
9707                         break;
9708                 case CEE_ADD_OVF:
9709                 case CEE_ADD_OVF_UN:
9710                 case CEE_MUL_OVF:
9711                 case CEE_MUL_OVF_UN:
9712                 case CEE_SUB_OVF:
9713                 case CEE_SUB_OVF_UN:
9714                         CHECK_STACK (2);
9715                         ADD_BINOP (*ip);
9716                         ip++;
9717                         break;
9718                 case CEE_CPOBJ:
9719                         GSHAREDVT_FAILURE (*ip);
9720                         CHECK_OPSIZE (5);
9721                         CHECK_STACK (2);
9722                         token = read32 (ip + 1);
9723                         klass = mini_get_class (method, token, generic_context);
9724                         CHECK_TYPELOAD (klass);
9725                         sp -= 2;
9726                         mini_emit_memory_copy (cfg, sp [0], sp [1], klass, FALSE, ins_flag);
9727                         ins_flag = 0;
9728                         ip += 5;
9729                         break;
9730                 case CEE_LDOBJ: {
9731                         int loc_index = -1;
9732                         int stloc_len = 0;
9733
9734                         CHECK_OPSIZE (5);
9735                         CHECK_STACK (1);
9736                         --sp;
9737                         token = read32 (ip + 1);
9738                         klass = mini_get_class (method, token, generic_context);
9739                         CHECK_TYPELOAD (klass);
9740
9741                         /* Optimize the common ldobj+stloc combination */
9742                         switch (ip [5]) {
9743                         case CEE_STLOC_S:
9744                                 loc_index = ip [6];
9745                                 stloc_len = 2;
9746                                 break;
9747                         case CEE_STLOC_0:
9748                         case CEE_STLOC_1:
9749                         case CEE_STLOC_2:
9750                         case CEE_STLOC_3:
9751                                 loc_index = ip [5] - CEE_STLOC_0;
9752                                 stloc_len = 1;
9753                                 break;
9754                         default:
9755                                 break;
9756                         }
9757
9758                         if ((loc_index != -1) && ip_in_bb (cfg, cfg->cbb, ip + 5)) {
9759                                 CHECK_LOCAL (loc_index);
9760
9761                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, sp [0]->dreg, 0);
9762                                 ins->dreg = cfg->locals [loc_index]->dreg;
9763                                 ins->flags |= ins_flag;
9764                                 ip += 5;
9765                                 ip += stloc_len;
9766                                 if (ins_flag & MONO_INST_VOLATILE) {
9767                                         /* Volatile loads have acquire semantics, see 12.6.7 in Ecma 335 */
9768                                         mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_ACQ);
9769                                 }
9770                                 ins_flag = 0;
9771                                 break;
9772                         }
9773
9774                         /* Optimize the ldobj+stobj combination */
9775                         if (((ip [5] == CEE_STOBJ) && ip_in_bb (cfg, cfg->cbb, ip + 5) && read32 (ip + 6) == token)) {
9776                                 CHECK_STACK (1);
9777
9778                                 sp --;
9779
9780                                 mini_emit_memory_copy (cfg, sp [0], sp [1], klass, FALSE, ins_flag);
9781
9782                                 ip += 5 + 5;
9783                                 ins_flag = 0;
9784                                 break;
9785                         }
9786
9787                         ins = mini_emit_memory_load (cfg, &klass->byval_arg, sp [0], 0, ins_flag);
9788                         *sp++ = ins;
9789
9790                         ip += 5;
9791                         ins_flag = 0;
9792                         inline_costs += 1;
9793                         break;
9794                 }
9795                 case CEE_LDSTR:
9796                         CHECK_STACK_OVF (1);
9797                         CHECK_OPSIZE (5);
9798                         n = read32 (ip + 1);
9799
9800                         if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
9801                                 EMIT_NEW_PCONST (cfg, ins, mono_method_get_wrapper_data (method, n));
9802                                 ins->type = STACK_OBJ;
9803                                 *sp = ins;
9804                         }
9805                         else if (method->wrapper_type != MONO_WRAPPER_NONE) {
9806                                 MonoInst *iargs [1];
9807                                 char *str = (char *)mono_method_get_wrapper_data (method, n);
9808
9809                                 if (cfg->compile_aot)
9810                                         EMIT_NEW_LDSTRLITCONST (cfg, iargs [0], str);
9811                                 else
9812                                         EMIT_NEW_PCONST (cfg, iargs [0], str);
9813                                 *sp = mono_emit_jit_icall (cfg, mono_string_new_wrapper, iargs);
9814                         } else {
9815                                 if (cfg->opt & MONO_OPT_SHARED) {
9816                                         MonoInst *iargs [3];
9817
9818                                         if (cfg->compile_aot) {
9819                                                 cfg->ldstr_list = g_list_prepend (cfg->ldstr_list, GINT_TO_POINTER (n));
9820                                         }
9821                                         EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
9822                                         EMIT_NEW_IMAGECONST (cfg, iargs [1], image);
9823                                         EMIT_NEW_ICONST (cfg, iargs [2], mono_metadata_token_index (n));
9824                                         *sp = mono_emit_jit_icall (cfg, ves_icall_mono_ldstr, iargs);
9825                                         mono_ldstr_checked (cfg->domain, image, mono_metadata_token_index (n), &cfg->error);
9826                                         CHECK_CFG_ERROR;
9827                                 } else {
9828                                         if (cfg->cbb->out_of_line) {
9829                                                 MonoInst *iargs [2];
9830
9831                                                 if (image == mono_defaults.corlib) {
9832                                                         /* 
9833                                                          * Avoid relocations in AOT and save some space by using a 
9834                                                          * version of helper_ldstr specialized to mscorlib.
9835                                                          */
9836                                                         EMIT_NEW_ICONST (cfg, iargs [0], mono_metadata_token_index (n));
9837                                                         *sp = mono_emit_jit_icall (cfg, mono_helper_ldstr_mscorlib, iargs);
9838                                                 } else {
9839                                                         /* Avoid creating the string object */
9840                                                         EMIT_NEW_IMAGECONST (cfg, iargs [0], image);
9841                                                         EMIT_NEW_ICONST (cfg, iargs [1], mono_metadata_token_index (n));
9842                                                         *sp = mono_emit_jit_icall (cfg, mono_helper_ldstr, iargs);
9843                                                 }
9844                                         } 
9845                                         else
9846                                         if (cfg->compile_aot) {
9847                                                 NEW_LDSTRCONST (cfg, ins, image, n);
9848                                                 *sp = ins;
9849                                                 MONO_ADD_INS (cfg->cbb, ins);
9850                                         } 
9851                                         else {
9852                                                 NEW_PCONST (cfg, ins, NULL);
9853                                                 ins->type = STACK_OBJ;
9854                                                 ins->inst_p0 = mono_ldstr_checked (cfg->domain, image, mono_metadata_token_index (n), &cfg->error);
9855                                                 CHECK_CFG_ERROR;
9856                                                 
9857                                                 if (!ins->inst_p0)
9858                                                         OUT_OF_MEMORY_FAILURE;
9859
9860                                                 *sp = ins;
9861                                                 MONO_ADD_INS (cfg->cbb, ins);
9862                                         }
9863                                 }
9864                         }
9865
9866                         sp++;
9867                         ip += 5;
9868                         break;
9869                 case CEE_NEWOBJ: {
9870                         MonoInst *iargs [2];
9871                         MonoMethodSignature *fsig;
9872                         MonoInst this_ins;
9873                         MonoInst *alloc;
9874                         MonoInst *vtable_arg = NULL;
9875
9876                         CHECK_OPSIZE (5);
9877                         token = read32 (ip + 1);
9878                         cmethod = mini_get_method (cfg, method, token, NULL, generic_context);
9879                         CHECK_CFG_ERROR;
9880
9881                         fsig = mono_method_get_signature_checked (cmethod, image, token, generic_context, &cfg->error);
9882                         CHECK_CFG_ERROR;
9883
9884                         mono_save_token_info (cfg, image, token, cmethod);
9885
9886                         if (!mono_class_init (cmethod->klass))
9887                                 TYPE_LOAD_ERROR (cmethod->klass);
9888
9889                         context_used = mini_method_check_context_used (cfg, cmethod);
9890                                         
9891                         if (!dont_verify && !cfg->skip_visibility) {
9892                                 MonoMethod *cil_method = cmethod;
9893                                 MonoMethod *target_method = cil_method;
9894
9895                                 if (method->is_inflated) {
9896                                         target_method = mini_get_method_allow_open (method, token, NULL, &(mono_method_get_generic_container (method_definition)->context), &cfg->error);
9897                                         CHECK_CFG_ERROR;
9898                                 }
9899                                 
9900                                 if (!mono_method_can_access_method (method_definition, target_method) &&
9901                                         !mono_method_can_access_method (method, cil_method))
9902                                         emit_method_access_failure (cfg, method, cil_method);
9903                         }
9904
9905                         if (mono_security_core_clr_enabled ())
9906                                 ensure_method_is_allowed_to_call_method (cfg, method, cmethod);
9907
9908                         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)) {
9909                                 emit_class_init (cfg, cmethod->klass);
9910                                 CHECK_TYPELOAD (cmethod->klass);
9911                         }
9912
9913                         /*
9914                         if (cfg->gsharedvt) {
9915                                 if (mini_is_gsharedvt_variable_signature (sig))
9916                                         GSHAREDVT_FAILURE (*ip);
9917                         }
9918                         */
9919
9920                         n = fsig->param_count;
9921                         CHECK_STACK (n);
9922
9923                         /* 
9924                          * Generate smaller code for the common newobj <exception> instruction in
9925                          * argument checking code.
9926                          */
9927                         if (cfg->cbb->out_of_line && cmethod->klass->image == mono_defaults.corlib &&
9928                                 is_exception_class (cmethod->klass) && n <= 2 &&
9929                                 ((n < 1) || (!fsig->params [0]->byref && fsig->params [0]->type == MONO_TYPE_STRING)) && 
9930                                 ((n < 2) || (!fsig->params [1]->byref && fsig->params [1]->type == MONO_TYPE_STRING))) {
9931                                 MonoInst *iargs [3];
9932
9933                                 sp -= n;
9934
9935                                 EMIT_NEW_ICONST (cfg, iargs [0], cmethod->klass->type_token);
9936                                 switch (n) {
9937                                 case 0:
9938                                         *sp ++ = mono_emit_jit_icall (cfg, mono_create_corlib_exception_0, iargs);
9939                                         break;
9940                                 case 1:
9941                                         iargs [1] = sp [0];
9942                                         *sp ++ = mono_emit_jit_icall (cfg, mono_create_corlib_exception_1, iargs);
9943                                         break;
9944                                 case 2:
9945                                         iargs [1] = sp [0];
9946                                         iargs [2] = sp [1];
9947                                         *sp ++ = mono_emit_jit_icall (cfg, mono_create_corlib_exception_2, iargs);
9948                                         break;
9949                                 default:
9950                                         g_assert_not_reached ();
9951                                 }
9952
9953                                 ip += 5;
9954                                 inline_costs += 5;
9955                                 break;
9956                         }
9957
9958                         /* move the args to allow room for 'this' in the first position */
9959                         while (n--) {
9960                                 --sp;
9961                                 sp [1] = sp [0];
9962                         }
9963
9964                         /* check_call_signature () requires sp[0] to be set */
9965                         this_ins.type = STACK_OBJ;
9966                         sp [0] = &this_ins;
9967                         if (check_call_signature (cfg, fsig, sp))
9968                                 UNVERIFIED;
9969
9970                         iargs [0] = NULL;
9971
9972                         if (mini_class_is_system_array (cmethod->klass)) {
9973                                 *sp = emit_get_rgctx_method (cfg, context_used,
9974                                                                                          cmethod, MONO_RGCTX_INFO_METHOD);
9975
9976                                 /* Avoid varargs in the common case */
9977                                 if (fsig->param_count == 1)
9978                                         alloc = mono_emit_jit_icall (cfg, mono_array_new_1, sp);
9979                                 else if (fsig->param_count == 2)
9980                                         alloc = mono_emit_jit_icall (cfg, mono_array_new_2, sp);
9981                                 else if (fsig->param_count == 3)
9982                                         alloc = mono_emit_jit_icall (cfg, mono_array_new_3, sp);
9983                                 else if (fsig->param_count == 4)
9984                                         alloc = mono_emit_jit_icall (cfg, mono_array_new_4, sp);
9985                                 else
9986                                         alloc = handle_array_new (cfg, fsig->param_count, sp, ip);
9987                         } else if (cmethod->string_ctor) {
9988                                 g_assert (!context_used);
9989                                 g_assert (!vtable_arg);
9990                                 /* we simply pass a null pointer */
9991                                 EMIT_NEW_PCONST (cfg, *sp, NULL); 
9992                                 /* now call the string ctor */
9993                                 alloc = mono_emit_method_call_full (cfg, cmethod, fsig, FALSE, sp, NULL, NULL, NULL);
9994                         } else {
9995                                 if (cmethod->klass->valuetype) {
9996                                         iargs [0] = mono_compile_create_var (cfg, &cmethod->klass->byval_arg, OP_LOCAL);
9997                                         emit_init_rvar (cfg, iargs [0]->dreg, &cmethod->klass->byval_arg);
9998                                         EMIT_NEW_TEMPLOADA (cfg, *sp, iargs [0]->inst_c0);
9999
10000                                         alloc = NULL;
10001
10002                                         /* 
10003                                          * The code generated by mini_emit_virtual_call () expects
10004                                          * iargs [0] to be a boxed instance, but luckily the vcall
10005                                          * will be transformed into a normal call there.
10006                                          */
10007                                 } else if (context_used) {
10008                                         alloc = handle_alloc (cfg, cmethod->klass, FALSE, context_used);
10009                                         *sp = alloc;
10010                                 } else {
10011                                         MonoVTable *vtable = NULL;
10012
10013                                         if (!cfg->compile_aot)
10014                                                 vtable = mono_class_vtable (cfg->domain, cmethod->klass);
10015                                         CHECK_TYPELOAD (cmethod->klass);
10016
10017                                         /*
10018                                          * TypeInitializationExceptions thrown from the mono_runtime_class_init
10019                                          * call in mono_jit_runtime_invoke () can abort the finalizer thread.
10020                                          * As a workaround, we call class cctors before allocating objects.
10021                                          */
10022                                         if (mini_field_access_needs_cctor_run (cfg, method, cmethod->klass, vtable) && !(g_slist_find (class_inits, cmethod->klass))) {
10023                                                 emit_class_init (cfg, cmethod->klass);
10024                                                 if (cfg->verbose_level > 2)
10025                                                         printf ("class %s.%s needs init call for ctor\n", cmethod->klass->name_space, cmethod->klass->name);
10026                                                 class_inits = g_slist_prepend (class_inits, cmethod->klass);
10027                                         }
10028
10029                                         alloc = handle_alloc (cfg, cmethod->klass, FALSE, 0);
10030                                         *sp = alloc;
10031                                 }
10032                                 CHECK_CFG_EXCEPTION; /*for handle_alloc*/
10033
10034                                 if (alloc)
10035                                         MONO_EMIT_NEW_UNALU (cfg, OP_NOT_NULL, -1, alloc->dreg);
10036
10037                                 /* Now call the actual ctor */
10038                                 handle_ctor_call (cfg, cmethod, fsig, context_used, sp, ip, &inline_costs);
10039                                 CHECK_CFG_EXCEPTION;
10040                         }
10041
10042                         if (alloc == NULL) {
10043                                 /* Valuetype */
10044                                 EMIT_NEW_TEMPLOAD (cfg, ins, iargs [0]->inst_c0);
10045                                 type_to_eval_stack_type (cfg, &ins->klass->byval_arg, ins);
10046                                 *sp++= ins;
10047                         } else {
10048                                 *sp++ = alloc;
10049                         }
10050                         
10051                         ip += 5;
10052                         inline_costs += 5;
10053                         if (!(seq_point_locs && mono_bitset_test_fast (seq_point_locs, ip - header->code)))
10054                                 emit_seq_point (cfg, method, ip, FALSE, TRUE);
10055                         break;
10056                 }
10057                 case CEE_CASTCLASS:
10058                 case CEE_ISINST: {
10059                         CHECK_STACK (1);
10060                         --sp;
10061                         CHECK_OPSIZE (5);
10062                         token = read32 (ip + 1);
10063                         klass = mini_get_class (method, token, generic_context);
10064                         CHECK_TYPELOAD (klass);
10065                         if (sp [0]->type != STACK_OBJ)
10066                                 UNVERIFIED;
10067
10068                         MONO_INST_NEW (cfg, ins, *ip == CEE_ISINST ? OP_ISINST : OP_CASTCLASS);
10069                         ins->dreg = alloc_preg (cfg);
10070                         ins->sreg1 = (*sp)->dreg;
10071                         ins->klass = klass;
10072                         ins->type = STACK_OBJ;
10073                         MONO_ADD_INS (cfg->cbb, ins);
10074
10075                         CHECK_CFG_EXCEPTION;
10076                         *sp++ = ins;
10077                         ip += 5;
10078
10079                         cfg->flags |= MONO_CFG_HAS_TYPE_CHECK;
10080                         break;
10081                 }
10082                 case CEE_UNBOX_ANY: {
10083                         MonoInst *res, *addr;
10084
10085                         CHECK_STACK (1);
10086                         --sp;
10087                         CHECK_OPSIZE (5);
10088                         token = read32 (ip + 1);
10089                         klass = mini_get_class (method, token, generic_context);
10090                         CHECK_TYPELOAD (klass);
10091
10092                         mono_save_token_info (cfg, image, token, klass);
10093
10094                         context_used = mini_class_check_context_used (cfg, klass);
10095
10096                         if (mini_is_gsharedvt_klass (klass)) {
10097                                 res = handle_unbox_gsharedvt (cfg, klass, *sp);
10098                                 inline_costs += 2;
10099                         } else if (generic_class_is_reference_type (cfg, klass)) {
10100                                 if (MONO_INS_IS_PCONST_NULL (*sp)) {
10101                                         EMIT_NEW_PCONST (cfg, res, NULL);
10102                                         res->type = STACK_OBJ;
10103                                 } else {
10104                                         MONO_INST_NEW (cfg, res, OP_CASTCLASS);
10105                                         res->dreg = alloc_preg (cfg);
10106                                         res->sreg1 = (*sp)->dreg;
10107                                         res->klass = klass;
10108                                         res->type = STACK_OBJ;
10109                                         MONO_ADD_INS (cfg->cbb, res);
10110                                         cfg->flags |= MONO_CFG_HAS_TYPE_CHECK;
10111                                 }
10112                         } else if (mono_class_is_nullable (klass)) {
10113                                 res = handle_unbox_nullable (cfg, *sp, klass, context_used);
10114                         } else {
10115                                 addr = handle_unbox (cfg, klass, sp, context_used);
10116                                 /* LDOBJ */
10117                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr->dreg, 0);
10118                                 res = ins;
10119                                 inline_costs += 2;
10120                         }
10121
10122                         *sp ++ = res;
10123                         ip += 5;
10124                         break;
10125                 }
10126                 case CEE_BOX: {
10127                         MonoInst *val;
10128                         MonoClass *enum_class;
10129                         MonoMethod *has_flag;
10130
10131                         CHECK_STACK (1);
10132                         --sp;
10133                         val = *sp;
10134                         CHECK_OPSIZE (5);
10135                         token = read32 (ip + 1);
10136                         klass = mini_get_class (method, token, generic_context);
10137                         CHECK_TYPELOAD (klass);
10138
10139                         mono_save_token_info (cfg, image, token, klass);
10140
10141                         context_used = mini_class_check_context_used (cfg, klass);
10142
10143                         if (generic_class_is_reference_type (cfg, klass)) {
10144                                 *sp++ = val;
10145                                 ip += 5;
10146                                 break;
10147                         }
10148
10149                         if (klass == mono_defaults.void_class)
10150                                 UNVERIFIED;
10151                         if (target_type_is_incompatible (cfg, &klass->byval_arg, *sp))
10152                                 UNVERIFIED;
10153                         /* frequent check in generic code: box (struct), brtrue */
10154
10155                         /*
10156                          * Look for:
10157                          *
10158                          *   <push int/long ptr>
10159                          *   <push int/long>
10160                          *   box MyFlags
10161                          *   constrained. MyFlags
10162                          *   callvirt instace bool class [mscorlib] System.Enum::HasFlag (class [mscorlib] System.Enum)
10163                          *
10164                          * If we find this sequence and the operand types on box and constrained
10165                          * are equal, we can emit a specialized instruction sequence instead of
10166                          * the very slow HasFlag () call.
10167                          */
10168                         if ((cfg->opt & MONO_OPT_INTRINS) &&
10169                             /* Cheap checks first. */
10170                             ip + 5 + 6 + 5 < end &&
10171                             ip [5] == CEE_PREFIX1 &&
10172                             ip [6] == CEE_CONSTRAINED_ &&
10173                             ip [11] == CEE_CALLVIRT &&
10174                             ip_in_bb (cfg, cfg->cbb, ip + 5 + 6 + 5) &&
10175                             mono_class_is_enum (klass) &&
10176                             (enum_class = mini_get_class (method, read32 (ip + 7), generic_context)) &&
10177                             (has_flag = mini_get_method (cfg, method, read32 (ip + 12), NULL, generic_context)) &&
10178                             has_flag->klass == mono_defaults.enum_class &&
10179                             !strcmp (has_flag->name, "HasFlag") &&
10180                             has_flag->signature->hasthis &&
10181                             has_flag->signature->param_count == 1) {
10182                                 CHECK_TYPELOAD (enum_class);
10183
10184                                 if (enum_class == klass) {
10185                                         MonoInst *enum_this, *enum_flag;
10186
10187                                         ip += 5 + 6 + 5;
10188                                         --sp;
10189
10190                                         enum_this = sp [0];
10191                                         enum_flag = sp [1];
10192
10193                                         *sp++ = handle_enum_has_flag (cfg, klass, enum_this, enum_flag);
10194                                         break;
10195                                 }
10196                         }
10197
10198                         // FIXME: LLVM can't handle the inconsistent bb linking
10199                         if (!mono_class_is_nullable (klass) &&
10200                                 !mini_is_gsharedvt_klass (klass) &&
10201                                 ip + 5 < end && ip_in_bb (cfg, cfg->cbb, ip + 5) &&
10202                                 (ip [5] == CEE_BRTRUE || 
10203                                  ip [5] == CEE_BRTRUE_S ||
10204                                  ip [5] == CEE_BRFALSE ||
10205                                  ip [5] == CEE_BRFALSE_S)) {
10206                                 gboolean is_true = ip [5] == CEE_BRTRUE || ip [5] == CEE_BRTRUE_S;
10207                                 int dreg;
10208                                 MonoBasicBlock *true_bb, *false_bb;
10209
10210                                 ip += 5;
10211
10212                                 if (cfg->verbose_level > 3) {
10213                                         printf ("converting (in B%d: stack: %d) %s", cfg->cbb->block_num, (int)(sp - stack_start), mono_disasm_code_one (NULL, method, ip, NULL));
10214                                         printf ("<box+brtrue opt>\n");
10215                                 }
10216
10217                                 switch (*ip) {
10218                                 case CEE_BRTRUE_S:
10219                                 case CEE_BRFALSE_S:
10220                                         CHECK_OPSIZE (2);
10221                                         ip++;
10222                                         target = ip + 1 + (signed char)(*ip);
10223                                         ip++;
10224                                         break;
10225                                 case CEE_BRTRUE:
10226                                 case CEE_BRFALSE:
10227                                         CHECK_OPSIZE (5);
10228                                         ip++;
10229                                         target = ip + 4 + (gint)(read32 (ip));
10230                                         ip += 4;
10231                                         break;
10232                                 default:
10233                                         g_assert_not_reached ();
10234                                 }
10235
10236                                 /* 
10237                                  * We need to link both bblocks, since it is needed for handling stack
10238                                  * arguments correctly (See test_0_box_brtrue_opt_regress_81102).
10239                                  * Branching to only one of them would lead to inconsistencies, so
10240                                  * generate an ICONST+BRTRUE, the branch opts will get rid of them.
10241                                  */
10242                                 GET_BBLOCK (cfg, true_bb, target);
10243                                 GET_BBLOCK (cfg, false_bb, ip);
10244
10245                                 mono_link_bblock (cfg, cfg->cbb, true_bb);
10246                                 mono_link_bblock (cfg, cfg->cbb, false_bb);
10247
10248                                 if (sp != stack_start) {
10249                                         handle_stack_args (cfg, stack_start, sp - stack_start);
10250                                         sp = stack_start;
10251                                         CHECK_UNVERIFIABLE (cfg);
10252                                 }
10253
10254                                 if (COMPILE_LLVM (cfg)) {
10255                                         dreg = alloc_ireg (cfg);
10256                                         MONO_EMIT_NEW_ICONST (cfg, dreg, 0);
10257                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, dreg, is_true ? 0 : 1);
10258
10259                                         MONO_EMIT_NEW_BRANCH_BLOCK2 (cfg, OP_IBEQ, true_bb, false_bb);
10260                                 } else {
10261                                         /* The JIT can't eliminate the iconst+compare */
10262                                         MONO_INST_NEW (cfg, ins, OP_BR);
10263                                         ins->inst_target_bb = is_true ? true_bb : false_bb;
10264                                         MONO_ADD_INS (cfg->cbb, ins);
10265                                 }
10266
10267                                 start_new_bblock = 1;
10268                                 break;
10269                         }
10270
10271                         *sp++ = handle_box (cfg, val, klass, context_used);
10272
10273                         CHECK_CFG_EXCEPTION;
10274                         ip += 5;
10275                         inline_costs += 1;
10276                         break;
10277                 }
10278                 case CEE_UNBOX: {
10279                         CHECK_STACK (1);
10280                         --sp;
10281                         CHECK_OPSIZE (5);
10282                         token = read32 (ip + 1);
10283                         klass = mini_get_class (method, token, generic_context);
10284                         CHECK_TYPELOAD (klass);
10285
10286                         mono_save_token_info (cfg, image, token, klass);
10287
10288                         context_used = mini_class_check_context_used (cfg, klass);
10289
10290                         if (mono_class_is_nullable (klass)) {
10291                                 MonoInst *val;
10292
10293                                 val = handle_unbox_nullable (cfg, *sp, klass, context_used);
10294                                 EMIT_NEW_VARLOADA (cfg, ins, get_vreg_to_inst (cfg, val->dreg), &val->klass->byval_arg);
10295
10296                                 *sp++= ins;
10297                         } else {
10298                                 ins = handle_unbox (cfg, klass, sp, context_used);
10299                                 *sp++ = ins;
10300                         }
10301                         ip += 5;
10302                         inline_costs += 2;
10303                         break;
10304                 }
10305                 case CEE_LDFLD:
10306                 case CEE_LDFLDA:
10307                 case CEE_STFLD:
10308                 case CEE_LDSFLD:
10309                 case CEE_LDSFLDA:
10310                 case CEE_STSFLD: {
10311                         MonoClassField *field;
10312 #ifndef DISABLE_REMOTING
10313                         int costs;
10314 #endif
10315                         guint foffset;
10316                         gboolean is_instance;
10317                         int op;
10318                         gpointer addr = NULL;
10319                         gboolean is_special_static;
10320                         MonoType *ftype;
10321                         MonoInst *store_val = NULL;
10322                         MonoInst *thread_ins;
10323
10324                         op = *ip;
10325                         is_instance = (op == CEE_LDFLD || op == CEE_LDFLDA || op == CEE_STFLD);
10326                         if (is_instance) {
10327                                 if (op == CEE_STFLD) {
10328                                         CHECK_STACK (2);
10329                                         sp -= 2;
10330                                         store_val = sp [1];
10331                                 } else {
10332                                         CHECK_STACK (1);
10333                                         --sp;
10334                                 }
10335                                 if (sp [0]->type == STACK_I4 || sp [0]->type == STACK_I8 || sp [0]->type == STACK_R8)
10336                                         UNVERIFIED;
10337                                 if (*ip != CEE_LDFLD && sp [0]->type == STACK_VTYPE)
10338                                         UNVERIFIED;
10339                         } else {
10340                                 if (op == CEE_STSFLD) {
10341                                         CHECK_STACK (1);
10342                                         sp--;
10343                                         store_val = sp [0];
10344                                 }
10345                         }
10346
10347                         CHECK_OPSIZE (5);
10348                         token = read32 (ip + 1);
10349                         if (method->wrapper_type != MONO_WRAPPER_NONE) {
10350                                 field = (MonoClassField *)mono_method_get_wrapper_data (method, token);
10351                                 klass = field->parent;
10352                         }
10353                         else {
10354                                 field = mono_field_from_token_checked (image, token, &klass, generic_context, &cfg->error);
10355                                 CHECK_CFG_ERROR;
10356                         }
10357                         if (!dont_verify && !cfg->skip_visibility && !mono_method_can_access_field (method, field))
10358                                 FIELD_ACCESS_FAILURE (method, field);
10359                         mono_class_init (klass);
10360
10361                         /* if the class is Critical then transparent code cannot access it's fields */
10362                         if (!is_instance && mono_security_core_clr_enabled ())
10363                                 ensure_method_is_allowed_to_access_field (cfg, method, field);
10364
10365                         /* XXX this is technically required but, so far (SL2), no [SecurityCritical] types (not many exists) have
10366                            any visible *instance* field  (in fact there's a single case for a static field in Marshal) XXX
10367                         if (mono_security_core_clr_enabled ())
10368                                 ensure_method_is_allowed_to_access_field (cfg, method, field);
10369                         */
10370
10371                         ftype = mono_field_get_type (field);
10372
10373                         /*
10374                          * LDFLD etc. is usable on static fields as well, so convert those cases to
10375                          * the static case.
10376                          */
10377                         if (is_instance && ftype->attrs & FIELD_ATTRIBUTE_STATIC) {
10378                                 switch (op) {
10379                                 case CEE_LDFLD:
10380                                         op = CEE_LDSFLD;
10381                                         break;
10382                                 case CEE_STFLD:
10383                                         op = CEE_STSFLD;
10384                                         break;
10385                                 case CEE_LDFLDA:
10386                                         op = CEE_LDSFLDA;
10387                                         break;
10388                                 default:
10389                                         g_assert_not_reached ();
10390                                 }
10391                                 is_instance = FALSE;
10392                         }
10393
10394                         context_used = mini_class_check_context_used (cfg, klass);
10395
10396                         /* INSTANCE CASE */
10397
10398                         foffset = klass->valuetype? field->offset - sizeof (MonoObject): field->offset;
10399                         if (op == CEE_STFLD) {
10400                                 if (target_type_is_incompatible (cfg, field->type, sp [1]))
10401                                         UNVERIFIED;
10402 #ifndef DISABLE_REMOTING
10403                                 if ((mono_class_is_marshalbyref (klass) && !MONO_CHECK_THIS (sp [0])) || mono_class_is_contextbound (klass) || klass == mono_defaults.marshalbyrefobject_class) {
10404                                         MonoMethod *stfld_wrapper = mono_marshal_get_stfld_wrapper (field->type); 
10405                                         MonoInst *iargs [5];
10406
10407                                         GSHAREDVT_FAILURE (op);
10408
10409                                         iargs [0] = sp [0];
10410                                         EMIT_NEW_CLASSCONST (cfg, iargs [1], klass);
10411                                         EMIT_NEW_FIELDCONST (cfg, iargs [2], field);
10412                                         EMIT_NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) : 
10413                                                     field->offset);
10414                                         iargs [4] = sp [1];
10415
10416                                         if (cfg->opt & MONO_OPT_INLINE || cfg->compile_aot) {
10417                                                 costs = inline_method (cfg, stfld_wrapper, mono_method_signature (stfld_wrapper), 
10418                                                                                            iargs, ip, cfg->real_offset, TRUE);
10419                                                 CHECK_CFG_EXCEPTION;
10420                                                 g_assert (costs > 0);
10421                                                       
10422                                                 cfg->real_offset += 5;
10423
10424                                                 inline_costs += costs;
10425                                         } else {
10426                                                 mono_emit_method_call (cfg, stfld_wrapper, iargs, NULL);
10427                                         }
10428                                 } else
10429 #endif
10430                                 {
10431                                         MonoInst *store, *wbarrier_ptr_ins = NULL;
10432
10433                                         MONO_EMIT_NULL_CHECK (cfg, sp [0]->dreg);
10434
10435                                         if (ins_flag & MONO_INST_VOLATILE) {
10436                                                 /* Volatile stores have release semantics, see 12.6.7 in Ecma 335 */
10437                                                 mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_REL);
10438                                         }
10439
10440                                         if (mini_is_gsharedvt_klass (klass)) {
10441                                                 MonoInst *offset_ins;
10442
10443                                                 context_used = mini_class_check_context_used (cfg, klass);
10444
10445                                                 offset_ins = emit_get_gsharedvt_info (cfg, field, MONO_RGCTX_INFO_FIELD_OFFSET);
10446                                                 /* The value is offset by 1 */
10447                                                 EMIT_NEW_BIALU_IMM (cfg, ins, OP_PSUB_IMM, offset_ins->dreg, offset_ins->dreg, 1);
10448                                                 dreg = alloc_ireg_mp (cfg);
10449                                                 EMIT_NEW_BIALU (cfg, ins, OP_PADD, dreg, sp [0]->dreg, offset_ins->dreg);
10450                                                 wbarrier_ptr_ins = ins;
10451                                                 /* The decomposition will call mini_emit_memory_copy () which will emit a wbarrier if needed */
10452                                                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, store, field->type, dreg, 0, sp [1]->dreg);
10453                                         } else {
10454                                                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, store, field->type, sp [0]->dreg, foffset, sp [1]->dreg);
10455                                         }
10456                                         if (sp [0]->opcode != OP_LDADDR)
10457                                                 store->flags |= MONO_INST_FAULT;
10458
10459                                         if (cfg->gen_write_barriers && mini_type_to_stind (cfg, field->type) == CEE_STIND_REF && !MONO_INS_IS_PCONST_NULL (sp [1])) {
10460                                                 if (mini_is_gsharedvt_klass (klass)) {
10461                                                         g_assert (wbarrier_ptr_ins);
10462                                                         mini_emit_write_barrier (cfg, wbarrier_ptr_ins, sp [1]);
10463                                                 } else {
10464                                                         /* insert call to write barrier */
10465                                                         MonoInst *ptr;
10466                                                         int dreg;
10467
10468                                                         dreg = alloc_ireg_mp (cfg);
10469                                                         EMIT_NEW_BIALU_IMM (cfg, ptr, OP_PADD_IMM, dreg, sp [0]->dreg, foffset);
10470                                                         mini_emit_write_barrier (cfg, ptr, sp [1]);
10471                                                 }
10472                                         }
10473
10474                                         store->flags |= ins_flag;
10475                                 }
10476                                 ins_flag = 0;
10477                                 ip += 5;
10478                                 break;
10479                         }
10480
10481 #ifndef DISABLE_REMOTING
10482                         if (is_instance && ((mono_class_is_marshalbyref (klass) && !MONO_CHECK_THIS (sp [0])) || mono_class_is_contextbound (klass) || klass == mono_defaults.marshalbyrefobject_class)) {
10483                                 MonoMethod *wrapper = (op == CEE_LDFLDA) ? mono_marshal_get_ldflda_wrapper (field->type) : mono_marshal_get_ldfld_wrapper (field->type); 
10484                                 MonoInst *iargs [4];
10485
10486                                 GSHAREDVT_FAILURE (op);
10487
10488                                 iargs [0] = sp [0];
10489                                 EMIT_NEW_CLASSCONST (cfg, iargs [1], klass);
10490                                 EMIT_NEW_FIELDCONST (cfg, iargs [2], field);
10491                                 EMIT_NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) : field->offset);
10492                                 if (cfg->opt & MONO_OPT_INLINE || cfg->compile_aot) {
10493                                         costs = inline_method (cfg, wrapper, mono_method_signature (wrapper), 
10494                                                                                    iargs, ip, cfg->real_offset, TRUE);
10495                                         CHECK_CFG_EXCEPTION;
10496                                         g_assert (costs > 0);
10497                                                       
10498                                         cfg->real_offset += 5;
10499
10500                                         *sp++ = iargs [0];
10501
10502                                         inline_costs += costs;
10503                                 } else {
10504                                         ins = mono_emit_method_call (cfg, wrapper, iargs, NULL);
10505                                         *sp++ = ins;
10506                                 }
10507                         } else 
10508 #endif
10509                         if (is_instance) {
10510                                 if (sp [0]->type == STACK_VTYPE) {
10511                                         MonoInst *var;
10512
10513                                         /* Have to compute the address of the variable */
10514
10515                                         var = get_vreg_to_inst (cfg, sp [0]->dreg);
10516                                         if (!var)
10517                                                 var = mono_compile_create_var_for_vreg (cfg, &klass->byval_arg, OP_LOCAL, sp [0]->dreg);
10518                                         else
10519                                                 g_assert (var->klass == klass);
10520                                         
10521                                         EMIT_NEW_VARLOADA (cfg, ins, var, &var->klass->byval_arg);
10522                                         sp [0] = ins;
10523                                 }
10524
10525                                 if (op == CEE_LDFLDA) {
10526                                         if (sp [0]->type == STACK_OBJ) {
10527                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, sp [0]->dreg, 0);
10528                                                 MONO_EMIT_NEW_COND_EXC (cfg, EQ, "NullReferenceException");
10529                                         }
10530
10531                                         dreg = alloc_ireg_mp (cfg);
10532
10533                                         if (mini_is_gsharedvt_klass (klass)) {
10534                                                 MonoInst *offset_ins;
10535
10536                                                 offset_ins = emit_get_gsharedvt_info (cfg, field, MONO_RGCTX_INFO_FIELD_OFFSET);
10537                                                 /* The value is offset by 1 */
10538                                                 EMIT_NEW_BIALU_IMM (cfg, ins, OP_PSUB_IMM, offset_ins->dreg, offset_ins->dreg, 1);
10539                                                 EMIT_NEW_BIALU (cfg, ins, OP_PADD, dreg, sp [0]->dreg, offset_ins->dreg);
10540                                         } else {
10541                                                 EMIT_NEW_BIALU_IMM (cfg, ins, OP_PADD_IMM, dreg, sp [0]->dreg, foffset);
10542                                         }
10543                                         ins->klass = mono_class_from_mono_type (field->type);
10544                                         ins->type = STACK_MP;
10545                                         *sp++ = ins;
10546                                 } else {
10547                                         MonoInst *load;
10548
10549                                         MONO_EMIT_NULL_CHECK (cfg, sp [0]->dreg);
10550
10551                                         if (sp [0]->opcode == OP_LDADDR && klass->simd_type && cfg->opt & MONO_OPT_SIMD) {
10552                                                 ins = mono_emit_simd_field_load (cfg, field, sp [0]);
10553                                                 if (ins) {
10554                                                         *sp++ = ins;
10555                                                         ins_flag = 0;
10556                                                         ip += 5;
10557                                                         break;
10558                                                 }
10559                                         }
10560
10561                                         MonoInst *field_add_inst = sp [0];
10562                                         if (mini_is_gsharedvt_klass (klass)) {
10563                                                 MonoInst *offset_ins;
10564
10565                                                 offset_ins = emit_get_gsharedvt_info (cfg, field, MONO_RGCTX_INFO_FIELD_OFFSET);
10566                                                 /* The value is offset by 1 */
10567                                                 EMIT_NEW_BIALU_IMM (cfg, ins, OP_PSUB_IMM, offset_ins->dreg, offset_ins->dreg, 1);
10568                                                 EMIT_NEW_BIALU (cfg, field_add_inst, OP_PADD, alloc_ireg_mp (cfg), sp [0]->dreg, offset_ins->dreg);
10569                                                 foffset = 0;
10570                                         }
10571
10572                                         load = mini_emit_memory_load (cfg, field->type, field_add_inst, foffset, ins_flag);
10573
10574                                         if (sp [0]->opcode != OP_LDADDR)
10575                                                 load->flags |= MONO_INST_FAULT;
10576                                         *sp++ = load;
10577                                 }
10578                         }
10579
10580                         if (is_instance) {
10581                                 ins_flag = 0;
10582                                 ip += 5;
10583                                 break;
10584                         }
10585
10586                         /* STATIC CASE */
10587                         context_used = mini_class_check_context_used (cfg, klass);
10588
10589                         if (ftype->attrs & FIELD_ATTRIBUTE_LITERAL) {
10590                                 mono_error_set_field_load (&cfg->error, field->parent, field->name, "Using static instructions with literal field");
10591                                 CHECK_CFG_ERROR;
10592                         }
10593
10594                         /* The special_static_fields field is init'd in mono_class_vtable, so it needs
10595                          * to be called here.
10596                          */
10597                         if (!context_used && !(cfg->opt & MONO_OPT_SHARED)) {
10598                                 mono_class_vtable (cfg->domain, klass);
10599                                 CHECK_TYPELOAD (klass);
10600                         }
10601                         mono_domain_lock (cfg->domain);
10602                         if (cfg->domain->special_static_fields)
10603                                 addr = g_hash_table_lookup (cfg->domain->special_static_fields, field);
10604                         mono_domain_unlock (cfg->domain);
10605
10606                         is_special_static = mono_class_field_is_special_static (field);
10607
10608                         if (is_special_static && ((gsize)addr & 0x80000000) == 0)
10609                                 thread_ins = mono_create_tls_get (cfg, TLS_KEY_THREAD);
10610                         else
10611                                 thread_ins = NULL;
10612
10613                         /* Generate IR to compute the field address */
10614                         if (is_special_static && ((gsize)addr & 0x80000000) == 0 && thread_ins && !(cfg->opt & MONO_OPT_SHARED) && !context_used) {
10615                                 /*
10616                                  * Fast access to TLS data
10617                                  * Inline version of get_thread_static_data () in
10618                                  * threads.c.
10619                                  */
10620                                 guint32 offset;
10621                                 int idx, static_data_reg, array_reg, dreg;
10622
10623                                 if (context_used && cfg->gsharedvt && mini_is_gsharedvt_klass (klass))
10624                                         GSHAREDVT_FAILURE (op);
10625
10626                                 static_data_reg = alloc_ireg (cfg);
10627                                 MONO_EMIT_NEW_LOAD_MEMBASE (cfg, static_data_reg, thread_ins->dreg, MONO_STRUCT_OFFSET (MonoInternalThread, static_data));
10628
10629                                 if (cfg->compile_aot) {
10630                                         int offset_reg, offset2_reg, idx_reg;
10631
10632                                         /* For TLS variables, this will return the TLS offset */
10633                                         EMIT_NEW_SFLDACONST (cfg, ins, field);
10634                                         offset_reg = ins->dreg;
10635                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_IAND_IMM, offset_reg, offset_reg, 0x7fffffff);
10636                                         idx_reg = alloc_ireg (cfg);
10637                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_IAND_IMM, idx_reg, offset_reg, 0x3f);
10638                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ISHL_IMM, idx_reg, idx_reg, sizeof (gpointer) == 8 ? 3 : 2);
10639                                         MONO_EMIT_NEW_BIALU (cfg, OP_PADD, static_data_reg, static_data_reg, idx_reg);
10640                                         array_reg = alloc_ireg (cfg);
10641                                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, array_reg, static_data_reg, 0);
10642                                         offset2_reg = alloc_ireg (cfg);
10643                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ISHR_UN_IMM, offset2_reg, offset_reg, 6);
10644                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_IAND_IMM, offset2_reg, offset2_reg, 0x1ffffff);
10645                                         dreg = alloc_ireg (cfg);
10646                                         EMIT_NEW_BIALU (cfg, ins, OP_PADD, dreg, array_reg, offset2_reg);
10647                                 } else {
10648                                         offset = (gsize)addr & 0x7fffffff;
10649                                         idx = offset & 0x3f;
10650
10651                                         array_reg = alloc_ireg (cfg);
10652                                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, array_reg, static_data_reg, idx * sizeof (gpointer));
10653                                         dreg = alloc_ireg (cfg);
10654                                         EMIT_NEW_BIALU_IMM (cfg, ins, OP_ADD_IMM, dreg, array_reg, ((offset >> 6) & 0x1ffffff));
10655                                 }
10656                         } else if ((cfg->opt & MONO_OPT_SHARED) ||
10657                                         (cfg->compile_aot && is_special_static) ||
10658                                         (context_used && is_special_static)) {
10659                                 MonoInst *iargs [2];
10660
10661                                 g_assert (field->parent);
10662                                 EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
10663                                 if (context_used) {
10664                                         iargs [1] = emit_get_rgctx_field (cfg, context_used,
10665                                                 field, MONO_RGCTX_INFO_CLASS_FIELD);
10666                                 } else {
10667                                         EMIT_NEW_FIELDCONST (cfg, iargs [1], field);
10668                                 }
10669                                 ins = mono_emit_jit_icall (cfg, mono_class_static_field_address, iargs);
10670                         } else if (context_used) {
10671                                 MonoInst *static_data;
10672
10673                                 /*
10674                                 g_print ("sharing static field access in %s.%s.%s - depth %d offset %d\n",
10675                                         method->klass->name_space, method->klass->name, method->name,
10676                                         depth, field->offset);
10677                                 */
10678
10679                                 if (mono_class_needs_cctor_run (klass, method))
10680                                         emit_class_init (cfg, klass);
10681
10682                                 /*
10683                                  * The pointer we're computing here is
10684                                  *
10685                                  *   super_info.static_data + field->offset
10686                                  */
10687                                 static_data = mini_emit_get_rgctx_klass (cfg, context_used,
10688                                         klass, MONO_RGCTX_INFO_STATIC_DATA);
10689
10690                                 if (mini_is_gsharedvt_klass (klass)) {
10691                                         MonoInst *offset_ins;
10692
10693                                         offset_ins = emit_get_rgctx_field (cfg, context_used, field, MONO_RGCTX_INFO_FIELD_OFFSET);
10694                                         /* The value is offset by 1 */
10695                                         EMIT_NEW_BIALU_IMM (cfg, ins, OP_PSUB_IMM, offset_ins->dreg, offset_ins->dreg, 1);
10696                                         dreg = alloc_ireg_mp (cfg);
10697                                         EMIT_NEW_BIALU (cfg, ins, OP_PADD, dreg, static_data->dreg, offset_ins->dreg);
10698                                 } else if (field->offset == 0) {
10699                                         ins = static_data;
10700                                 } else {
10701                                         int addr_reg = mono_alloc_preg (cfg);
10702                                         EMIT_NEW_BIALU_IMM (cfg, ins, OP_PADD_IMM, addr_reg, static_data->dreg, field->offset);
10703                                 }
10704                         } else if ((cfg->opt & MONO_OPT_SHARED) || (cfg->compile_aot && addr)) {
10705                                 MonoInst *iargs [2];
10706
10707                                 g_assert (field->parent);
10708                                 EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
10709                                 EMIT_NEW_FIELDCONST (cfg, iargs [1], field);
10710                                 ins = mono_emit_jit_icall (cfg, mono_class_static_field_address, iargs);
10711                         } else {
10712                                 MonoVTable *vtable = NULL;
10713
10714                                 if (!cfg->compile_aot)
10715                                         vtable = mono_class_vtable (cfg->domain, klass);
10716                                 CHECK_TYPELOAD (klass);
10717
10718                                 if (!addr) {
10719                                         if (mini_field_access_needs_cctor_run (cfg, method, klass, vtable)) {
10720                                                 if (!(g_slist_find (class_inits, klass))) {
10721                                                         emit_class_init (cfg, klass);
10722                                                         if (cfg->verbose_level > 2)
10723                                                                 printf ("class %s.%s needs init call for %s\n", klass->name_space, klass->name, mono_field_get_name (field));
10724                                                         class_inits = g_slist_prepend (class_inits, klass);
10725                                                 }
10726                                         } else {
10727                                                 if (cfg->run_cctors) {
10728                                                         /* This makes so that inline cannot trigger */
10729                                                         /* .cctors: too many apps depend on them */
10730                                                         /* running with a specific order... */
10731                                                         g_assert (vtable);
10732                                                         if (! vtable->initialized)
10733                                                                 INLINE_FAILURE ("class init");
10734                                                         if (!mono_runtime_class_init_full (vtable, &cfg->error)) {
10735                                                                 mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
10736                                                                 goto exception_exit;
10737                                                         }
10738                                                 }
10739                                         }
10740                                         if (cfg->compile_aot)
10741                                                 EMIT_NEW_SFLDACONST (cfg, ins, field);
10742                                         else {
10743                                                 g_assert (vtable);
10744                                                 addr = (char*)mono_vtable_get_static_field_data (vtable) + field->offset;
10745                                                 g_assert (addr);
10746                                                 EMIT_NEW_PCONST (cfg, ins, addr);
10747                                         }
10748                                 } else {
10749                                         MonoInst *iargs [1];
10750                                         EMIT_NEW_ICONST (cfg, iargs [0], GPOINTER_TO_UINT (addr));
10751                                         ins = mono_emit_jit_icall (cfg, mono_get_special_static_data, iargs);
10752                                 }
10753                         }
10754
10755                         /* Generate IR to do the actual load/store operation */
10756
10757                         if ((op == CEE_STFLD || op == CEE_STSFLD) && (ins_flag & MONO_INST_VOLATILE)) {
10758                                 /* Volatile stores have release semantics, see 12.6.7 in Ecma 335 */
10759                                 mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_REL);
10760                         }
10761
10762                         if (op == CEE_LDSFLDA) {
10763                                 ins->klass = mono_class_from_mono_type (ftype);
10764                                 ins->type = STACK_PTR;
10765                                 *sp++ = ins;
10766                         } else if (op == CEE_STSFLD) {
10767                                 MonoInst *store;
10768
10769                                 EMIT_NEW_STORE_MEMBASE_TYPE (cfg, store, ftype, ins->dreg, 0, store_val->dreg);
10770                                 store->flags |= ins_flag;
10771                         } else {
10772                                 gboolean is_const = FALSE;
10773                                 MonoVTable *vtable = NULL;
10774                                 gpointer addr = NULL;
10775
10776                                 if (!context_used) {
10777                                         vtable = mono_class_vtable (cfg->domain, klass);
10778                                         CHECK_TYPELOAD (klass);
10779                                 }
10780                                 if ((ftype->attrs & FIELD_ATTRIBUTE_INIT_ONLY) && (((addr = mono_aot_readonly_field_override (field)) != NULL) ||
10781                                                 (!context_used && !((cfg->opt & MONO_OPT_SHARED) || cfg->compile_aot) && vtable->initialized))) {
10782                                         int ro_type = ftype->type;
10783                                         if (!addr)
10784                                                 addr = (char*)mono_vtable_get_static_field_data (vtable) + field->offset;
10785                                         if (ro_type == MONO_TYPE_VALUETYPE && ftype->data.klass->enumtype) {
10786                                                 ro_type = mono_class_enum_basetype (ftype->data.klass)->type;
10787                                         }
10788
10789                                         GSHAREDVT_FAILURE (op);
10790
10791                                         /* printf ("RO-FIELD %s.%s:%s\n", klass->name_space, klass->name, mono_field_get_name (field));*/
10792                                         is_const = TRUE;
10793                                         switch (ro_type) {
10794                                         case MONO_TYPE_BOOLEAN:
10795                                         case MONO_TYPE_U1:
10796                                                 EMIT_NEW_ICONST (cfg, *sp, *((guint8 *)addr));
10797                                                 sp++;
10798                                                 break;
10799                                         case MONO_TYPE_I1:
10800                                                 EMIT_NEW_ICONST (cfg, *sp, *((gint8 *)addr));
10801                                                 sp++;
10802                                                 break;                                          
10803                                         case MONO_TYPE_CHAR:
10804                                         case MONO_TYPE_U2:
10805                                                 EMIT_NEW_ICONST (cfg, *sp, *((guint16 *)addr));
10806                                                 sp++;
10807                                                 break;
10808                                         case MONO_TYPE_I2:
10809                                                 EMIT_NEW_ICONST (cfg, *sp, *((gint16 *)addr));
10810                                                 sp++;
10811                                                 break;
10812                                                 break;
10813                                         case MONO_TYPE_I4:
10814                                                 EMIT_NEW_ICONST (cfg, *sp, *((gint32 *)addr));
10815                                                 sp++;
10816                                                 break;                                          
10817                                         case MONO_TYPE_U4:
10818                                                 EMIT_NEW_ICONST (cfg, *sp, *((guint32 *)addr));
10819                                                 sp++;
10820                                                 break;
10821                                         case MONO_TYPE_I:
10822                                         case MONO_TYPE_U:
10823                                         case MONO_TYPE_PTR:
10824                                         case MONO_TYPE_FNPTR:
10825                                                 EMIT_NEW_PCONST (cfg, *sp, *((gpointer *)addr));
10826                                                 type_to_eval_stack_type ((cfg), field->type, *sp);
10827                                                 sp++;
10828                                                 break;
10829                                         case MONO_TYPE_STRING:
10830                                         case MONO_TYPE_OBJECT:
10831                                         case MONO_TYPE_CLASS:
10832                                         case MONO_TYPE_SZARRAY:
10833                                         case MONO_TYPE_ARRAY:
10834                                                 if (!mono_gc_is_moving ()) {
10835                                                         EMIT_NEW_PCONST (cfg, *sp, *((gpointer *)addr));
10836                                                         type_to_eval_stack_type ((cfg), field->type, *sp);
10837                                                         sp++;
10838                                                 } else {
10839                                                         is_const = FALSE;
10840                                                 }
10841                                                 break;
10842                                         case MONO_TYPE_I8:
10843                                         case MONO_TYPE_U8:
10844                                                 EMIT_NEW_I8CONST (cfg, *sp, *((gint64 *)addr));
10845                                                 sp++;
10846                                                 break;
10847                                         case MONO_TYPE_R4:
10848                                         case MONO_TYPE_R8:
10849                                         case MONO_TYPE_VALUETYPE:
10850                                         default:
10851                                                 is_const = FALSE;
10852                                                 break;
10853                                         }
10854                                 }
10855
10856                                 if (!is_const) {
10857                                         MonoInst *load;
10858
10859                                         CHECK_STACK_OVF (1);
10860
10861                                         EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, load, field->type, ins->dreg, 0);
10862                                         load->flags |= ins_flag;
10863                                         ins_flag = 0;
10864                                         *sp++ = load;
10865                                 }
10866                         }
10867
10868                         if ((op == CEE_LDFLD || op == CEE_LDSFLD) && (ins_flag & MONO_INST_VOLATILE)) {
10869                                 /* Volatile loads have acquire semantics, see 12.6.7 in Ecma 335 */
10870                                 mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_ACQ);
10871                         }
10872
10873                         ins_flag = 0;
10874                         ip += 5;
10875                         break;
10876                 }
10877                 case CEE_STOBJ:
10878                         CHECK_STACK (2);
10879                         sp -= 2;
10880                         CHECK_OPSIZE (5);
10881                         token = read32 (ip + 1);
10882                         klass = mini_get_class (method, token, generic_context);
10883                         CHECK_TYPELOAD (klass);
10884
10885                         /* FIXME: should check item at sp [1] is compatible with the type of the store. */
10886                         mini_emit_memory_store (cfg, &klass->byval_arg, sp [0], sp [1], ins_flag);
10887                         ins_flag = 0;
10888                         ip += 5;
10889                         inline_costs += 1;
10890                         break;
10891
10892                         /*
10893                          * Array opcodes
10894                          */
10895                 case CEE_NEWARR: {
10896                         MonoInst *len_ins;
10897                         const char *data_ptr;
10898                         int data_size = 0;
10899                         guint32 field_token;
10900
10901                         CHECK_STACK (1);
10902                         --sp;
10903
10904                         CHECK_OPSIZE (5);
10905                         token = read32 (ip + 1);
10906
10907                         klass = mini_get_class (method, token, generic_context);
10908                         CHECK_TYPELOAD (klass);
10909                         if (klass->byval_arg.type == MONO_TYPE_VOID)
10910                                 UNVERIFIED;
10911
10912                         context_used = mini_class_check_context_used (cfg, klass);
10913
10914                         if (sp [0]->type == STACK_I8 || (SIZEOF_VOID_P == 8 && sp [0]->type == STACK_PTR)) {
10915                                 MONO_INST_NEW (cfg, ins, OP_LCONV_TO_OVF_U4);
10916                                 ins->sreg1 = sp [0]->dreg;
10917                                 ins->type = STACK_I4;
10918                                 ins->dreg = alloc_ireg (cfg);
10919                                 MONO_ADD_INS (cfg->cbb, ins);
10920                                 *sp = mono_decompose_opcode (cfg, ins);
10921                         }
10922
10923                         if (context_used) {
10924                                 MonoInst *args [3];
10925                                 MonoClass *array_class = mono_array_class_get (klass, 1);
10926                                 MonoMethod *managed_alloc = mono_gc_get_managed_array_allocator (array_class);
10927
10928                                 /* FIXME: Use OP_NEWARR and decompose later to help abcrem */
10929
10930                                 /* vtable */
10931                                 args [0] = mini_emit_get_rgctx_klass (cfg, context_used,
10932                                         array_class, MONO_RGCTX_INFO_VTABLE);
10933                                 /* array len */
10934                                 args [1] = sp [0];
10935
10936                                 if (managed_alloc)
10937                                         ins = mono_emit_method_call (cfg, managed_alloc, args, NULL);
10938                                 else
10939                                         ins = mono_emit_jit_icall (cfg, ves_icall_array_new_specific, args);
10940                         } else {
10941                                 if (cfg->opt & MONO_OPT_SHARED) {
10942                                         /* Decompose now to avoid problems with references to the domainvar */
10943                                         MonoInst *iargs [3];
10944
10945                                         EMIT_NEW_DOMAINCONST (cfg, iargs [0]);
10946                                         EMIT_NEW_CLASSCONST (cfg, iargs [1], klass);
10947                                         iargs [2] = sp [0];
10948
10949                                         ins = mono_emit_jit_icall (cfg, ves_icall_array_new, iargs);
10950                                 } else {
10951                                         /* Decompose later since it is needed by abcrem */
10952                                         MonoClass *array_type = mono_array_class_get (klass, 1);
10953                                         mono_class_vtable (cfg->domain, array_type);
10954                                         CHECK_TYPELOAD (array_type);
10955
10956                                         MONO_INST_NEW (cfg, ins, OP_NEWARR);
10957                                         ins->dreg = alloc_ireg_ref (cfg);
10958                                         ins->sreg1 = sp [0]->dreg;
10959                                         ins->inst_newa_class = klass;
10960                                         ins->type = STACK_OBJ;
10961                                         ins->klass = array_type;
10962                                         MONO_ADD_INS (cfg->cbb, ins);
10963                                         cfg->flags |= MONO_CFG_HAS_ARRAY_ACCESS;
10964                                         cfg->cbb->has_array_access = TRUE;
10965
10966                                         /* Needed so mono_emit_load_get_addr () gets called */
10967                                         mono_get_got_var (cfg);
10968                                 }
10969                         }
10970
10971                         len_ins = sp [0];
10972                         ip += 5;
10973                         *sp++ = ins;
10974                         inline_costs += 1;
10975
10976                         /* 
10977                          * we inline/optimize the initialization sequence if possible.
10978                          * we should also allocate the array as not cleared, since we spend as much time clearing to 0 as initializing
10979                          * for small sizes open code the memcpy
10980                          * ensure the rva field is big enough
10981                          */
10982                         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))) {
10983                                 MonoMethod *memcpy_method = mini_get_memcpy_method ();
10984                                 MonoInst *iargs [3];
10985                                 int add_reg = alloc_ireg_mp (cfg);
10986
10987                                 EMIT_NEW_BIALU_IMM (cfg, iargs [0], OP_PADD_IMM, add_reg, ins->dreg, MONO_STRUCT_OFFSET (MonoArray, vector));
10988                                 if (cfg->compile_aot) {
10989                                         EMIT_NEW_AOTCONST_TOKEN (cfg, iargs [1], MONO_PATCH_INFO_RVA, method->klass->image, GPOINTER_TO_UINT(field_token), STACK_PTR, NULL);
10990                                 } else {
10991                                         EMIT_NEW_PCONST (cfg, iargs [1], (char*)data_ptr);
10992                                 }
10993                                 EMIT_NEW_ICONST (cfg, iargs [2], data_size);
10994                                 mono_emit_method_call (cfg, memcpy_method, iargs, NULL);
10995                                 ip += 11;
10996                         }
10997
10998                         break;
10999                 }
11000                 case CEE_LDLEN:
11001                         CHECK_STACK (1);
11002                         --sp;
11003                         if (sp [0]->type != STACK_OBJ)
11004                                 UNVERIFIED;
11005
11006                         MONO_INST_NEW (cfg, ins, OP_LDLEN);
11007                         ins->dreg = alloc_preg (cfg);
11008                         ins->sreg1 = sp [0]->dreg;
11009                         ins->type = STACK_I4;
11010                         /* This flag will be inherited by the decomposition */
11011                         ins->flags |= MONO_INST_FAULT;
11012                         MONO_ADD_INS (cfg->cbb, ins);
11013                         cfg->flags |= MONO_CFG_HAS_ARRAY_ACCESS;
11014                         cfg->cbb->has_array_access = TRUE;
11015                         ip ++;
11016                         *sp++ = ins;
11017                         break;
11018                 case CEE_LDELEMA:
11019                         CHECK_STACK (2);
11020                         sp -= 2;
11021                         CHECK_OPSIZE (5);
11022                         if (sp [0]->type != STACK_OBJ)
11023                                 UNVERIFIED;
11024
11025                         cfg->flags |= MONO_CFG_HAS_LDELEMA;
11026
11027                         klass = mini_get_class (method, read32 (ip + 1), generic_context);
11028                         CHECK_TYPELOAD (klass);
11029                         /* we need to make sure that this array is exactly the type it needs
11030                          * to be for correctness. the wrappers are lax with their usage
11031                          * so we need to ignore them here
11032                          */
11033                         if (!klass->valuetype && method->wrapper_type == MONO_WRAPPER_NONE && !readonly) {
11034                                 MonoClass *array_class = mono_array_class_get (klass, 1);
11035                                 mini_emit_check_array_type (cfg, sp [0], array_class);
11036                                 CHECK_TYPELOAD (array_class);
11037                         }
11038
11039                         readonly = FALSE;
11040                         ins = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1], TRUE);
11041                         *sp++ = ins;
11042                         ip += 5;
11043                         break;
11044                 case CEE_LDELEM:
11045                 case CEE_LDELEM_I1:
11046                 case CEE_LDELEM_U1:
11047                 case CEE_LDELEM_I2:
11048                 case CEE_LDELEM_U2:
11049                 case CEE_LDELEM_I4:
11050                 case CEE_LDELEM_U4:
11051                 case CEE_LDELEM_I8:
11052                 case CEE_LDELEM_I:
11053                 case CEE_LDELEM_R4:
11054                 case CEE_LDELEM_R8:
11055                 case CEE_LDELEM_REF: {
11056                         MonoInst *addr;
11057
11058                         CHECK_STACK (2);
11059                         sp -= 2;
11060
11061                         if (*ip == CEE_LDELEM) {
11062                                 CHECK_OPSIZE (5);
11063                                 token = read32 (ip + 1);
11064                                 klass = mini_get_class (method, token, generic_context);
11065                                 CHECK_TYPELOAD (klass);
11066                                 mono_class_init (klass);
11067                         }
11068                         else
11069                                 klass = array_access_to_klass (*ip);
11070
11071                         if (sp [0]->type != STACK_OBJ)
11072                                 UNVERIFIED;
11073
11074                         cfg->flags |= MONO_CFG_HAS_LDELEMA;
11075
11076                         if (mini_is_gsharedvt_variable_klass (klass)) {
11077                                 // FIXME-VT: OP_ICONST optimization
11078                                 addr = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1], TRUE);
11079                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr->dreg, 0);
11080                                 ins->opcode = OP_LOADV_MEMBASE;
11081                         } else if (sp [1]->opcode == OP_ICONST) {
11082                                 int array_reg = sp [0]->dreg;
11083                                 int index_reg = sp [1]->dreg;
11084                                 int offset = (mono_class_array_element_size (klass) * sp [1]->inst_c0) + MONO_STRUCT_OFFSET (MonoArray, vector);
11085
11086                                 if (SIZEOF_REGISTER == 8 && COMPILE_LLVM (cfg))
11087                                         MONO_EMIT_NEW_UNALU (cfg, OP_ZEXT_I4, index_reg, index_reg);
11088
11089                                 MONO_EMIT_BOUNDS_CHECK (cfg, array_reg, MonoArray, max_length, index_reg);
11090                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, array_reg, offset);
11091                         } else {
11092                                 addr = mini_emit_ldelema_1_ins (cfg, klass, sp [0], sp [1], TRUE);
11093                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &klass->byval_arg, addr->dreg, 0);
11094                         }
11095                         *sp++ = ins;
11096                         if (*ip == CEE_LDELEM)
11097                                 ip += 5;
11098                         else
11099                                 ++ip;
11100                         break;
11101                 }
11102                 case CEE_STELEM_I:
11103                 case CEE_STELEM_I1:
11104                 case CEE_STELEM_I2:
11105                 case CEE_STELEM_I4:
11106                 case CEE_STELEM_I8:
11107                 case CEE_STELEM_R4:
11108                 case CEE_STELEM_R8:
11109                 case CEE_STELEM_REF:
11110                 case CEE_STELEM: {
11111                         CHECK_STACK (3);
11112                         sp -= 3;
11113
11114                         cfg->flags |= MONO_CFG_HAS_LDELEMA;
11115
11116                         if (*ip == CEE_STELEM) {
11117                                 CHECK_OPSIZE (5);
11118                                 token = read32 (ip + 1);
11119                                 klass = mini_get_class (method, token, generic_context);
11120                                 CHECK_TYPELOAD (klass);
11121                                 mono_class_init (klass);
11122                         }
11123                         else
11124                                 klass = array_access_to_klass (*ip);
11125
11126                         if (sp [0]->type != STACK_OBJ)
11127                                 UNVERIFIED;
11128
11129                         emit_array_store (cfg, klass, sp, TRUE);
11130
11131                         if (*ip == CEE_STELEM)
11132                                 ip += 5;
11133                         else
11134                                 ++ip;
11135                         inline_costs += 1;
11136                         break;
11137                 }
11138                 case CEE_CKFINITE: {
11139                         CHECK_STACK (1);
11140                         --sp;
11141
11142                         if (cfg->llvm_only) {
11143                                 MonoInst *iargs [1];
11144
11145                                 iargs [0] = sp [0];
11146                                 *sp++ = mono_emit_jit_icall (cfg, mono_ckfinite, iargs);
11147                         } else  {
11148                                 MONO_INST_NEW (cfg, ins, OP_CKFINITE);
11149                                 ins->sreg1 = sp [0]->dreg;
11150                                 ins->dreg = alloc_freg (cfg);
11151                                 ins->type = STACK_R8;
11152                                 MONO_ADD_INS (cfg->cbb, ins);
11153
11154                                 *sp++ = mono_decompose_opcode (cfg, ins);
11155                         }
11156
11157                         ++ip;
11158                         break;
11159                 }
11160                 case CEE_REFANYVAL: {
11161                         MonoInst *src_var, *src;
11162
11163                         int klass_reg = alloc_preg (cfg);
11164                         int dreg = alloc_preg (cfg);
11165
11166                         GSHAREDVT_FAILURE (*ip);
11167
11168                         CHECK_STACK (1);
11169                         MONO_INST_NEW (cfg, ins, *ip);
11170                         --sp;
11171                         CHECK_OPSIZE (5);
11172                         klass = mini_get_class (method, read32 (ip + 1), generic_context);
11173                         CHECK_TYPELOAD (klass);
11174
11175                         context_used = mini_class_check_context_used (cfg, klass);
11176
11177                         // FIXME:
11178                         src_var = get_vreg_to_inst (cfg, sp [0]->dreg);
11179                         if (!src_var)
11180                                 src_var = mono_compile_create_var_for_vreg (cfg, &mono_defaults.typed_reference_class->byval_arg, OP_LOCAL, sp [0]->dreg);
11181                         EMIT_NEW_VARLOADA (cfg, src, src_var, src_var->inst_vtype);
11182                         MONO_EMIT_NEW_LOAD_MEMBASE (cfg, klass_reg, src->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, klass));
11183
11184                         if (context_used) {
11185                                 MonoInst *klass_ins;
11186
11187                                 klass_ins = mini_emit_get_rgctx_klass (cfg, context_used,
11188                                                 klass, MONO_RGCTX_INFO_KLASS);
11189
11190                                 // FIXME:
11191                                 MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, klass_reg, klass_ins->dreg);
11192                                 MONO_EMIT_NEW_COND_EXC (cfg, NE_UN, "InvalidCastException");
11193                         } else {
11194                                 mini_emit_class_check (cfg, klass_reg, klass);
11195                         }
11196                         EMIT_NEW_LOAD_MEMBASE (cfg, ins, OP_LOAD_MEMBASE, dreg, src->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, value));
11197                         ins->type = STACK_MP;
11198                         ins->klass = klass;
11199                         *sp++ = ins;
11200                         ip += 5;
11201                         break;
11202                 }
11203                 case CEE_MKREFANY: {
11204                         MonoInst *loc, *addr;
11205
11206                         GSHAREDVT_FAILURE (*ip);
11207
11208                         CHECK_STACK (1);
11209                         MONO_INST_NEW (cfg, ins, *ip);
11210                         --sp;
11211                         CHECK_OPSIZE (5);
11212                         klass = mini_get_class (method, read32 (ip + 1), generic_context);
11213                         CHECK_TYPELOAD (klass);
11214
11215                         context_used = mini_class_check_context_used (cfg, klass);
11216
11217                         loc = mono_compile_create_var (cfg, &mono_defaults.typed_reference_class->byval_arg, OP_LOCAL);
11218                         EMIT_NEW_TEMPLOADA (cfg, addr, loc->inst_c0);
11219
11220                         if (context_used) {
11221                                 MonoInst *const_ins;
11222                                 int type_reg = alloc_preg (cfg);
11223
11224                                 const_ins = mini_emit_get_rgctx_klass (cfg, context_used, klass, MONO_RGCTX_INFO_KLASS);
11225                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, klass), const_ins->dreg);
11226                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ADD_IMM, type_reg, const_ins->dreg, MONO_STRUCT_OFFSET (MonoClass, byval_arg));
11227                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, type), type_reg);
11228                         } else {
11229                                 int const_reg = alloc_preg (cfg);
11230                                 int type_reg = alloc_preg (cfg);
11231
11232                                 MONO_EMIT_NEW_CLASSCONST (cfg, const_reg, klass);
11233                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, klass), const_reg);
11234                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ADD_IMM, type_reg, const_reg, MONO_STRUCT_OFFSET (MonoClass, byval_arg));
11235                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, type), type_reg);
11236                         }
11237                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, addr->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, value), sp [0]->dreg);
11238
11239                         EMIT_NEW_TEMPLOAD (cfg, ins, loc->inst_c0);
11240                         ins->type = STACK_VTYPE;
11241                         ins->klass = mono_defaults.typed_reference_class;
11242                         *sp++ = ins;
11243                         ip += 5;
11244                         break;
11245                 }
11246                 case CEE_LDTOKEN: {
11247                         gpointer handle;
11248                         MonoClass *handle_class;
11249
11250                         CHECK_STACK_OVF (1);
11251
11252                         CHECK_OPSIZE (5);
11253                         n = read32 (ip + 1);
11254
11255                         if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD ||
11256                                         method->wrapper_type == MONO_WRAPPER_SYNCHRONIZED) {
11257                                 handle = mono_method_get_wrapper_data (method, n);
11258                                 handle_class = (MonoClass *)mono_method_get_wrapper_data (method, n + 1);
11259                                 if (handle_class == mono_defaults.typehandle_class)
11260                                         handle = &((MonoClass*)handle)->byval_arg;
11261                         }
11262                         else {
11263                                 handle = mono_ldtoken_checked (image, n, &handle_class, generic_context, &cfg->error);
11264                                 CHECK_CFG_ERROR;
11265                         }
11266                         if (!handle)
11267                                 LOAD_ERROR;
11268                         mono_class_init (handle_class);
11269                         if (cfg->gshared) {
11270                                 if (mono_metadata_token_table (n) == MONO_TABLE_TYPEDEF ||
11271                                                 mono_metadata_token_table (n) == MONO_TABLE_TYPEREF) {
11272                                         /* This case handles ldtoken
11273                                            of an open type, like for
11274                                            typeof(Gen<>). */
11275                                         context_used = 0;
11276                                 } else if (handle_class == mono_defaults.typehandle_class) {
11277                                         context_used = mini_class_check_context_used (cfg, mono_class_from_mono_type ((MonoType *)handle));
11278                                 } else if (handle_class == mono_defaults.fieldhandle_class)
11279                                         context_used = mini_class_check_context_used (cfg, ((MonoClassField*)handle)->parent);
11280                                 else if (handle_class == mono_defaults.methodhandle_class)
11281                                         context_used = mini_method_check_context_used (cfg, (MonoMethod *)handle);
11282                                 else
11283                                         g_assert_not_reached ();
11284                         }
11285
11286                         if ((cfg->opt & MONO_OPT_SHARED) &&
11287                                         method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD &&
11288                                         method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED) {
11289                                 MonoInst *addr, *vtvar, *iargs [3];
11290                                 int method_context_used;
11291
11292                                 method_context_used = mini_method_check_context_used (cfg, method);
11293
11294                                 vtvar = mono_compile_create_var (cfg, &handle_class->byval_arg, OP_LOCAL); 
11295
11296                                 EMIT_NEW_IMAGECONST (cfg, iargs [0], image);
11297                                 EMIT_NEW_ICONST (cfg, iargs [1], n);
11298                                 if (method_context_used) {
11299                                         iargs [2] = emit_get_rgctx_method (cfg, method_context_used,
11300                                                 method, MONO_RGCTX_INFO_METHOD);
11301                                         ins = mono_emit_jit_icall (cfg, mono_ldtoken_wrapper_generic_shared, iargs);
11302                                 } else {
11303                                         EMIT_NEW_PCONST (cfg, iargs [2], generic_context);
11304                                         ins = mono_emit_jit_icall (cfg, mono_ldtoken_wrapper, iargs);
11305                                 }
11306                                 EMIT_NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
11307
11308                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, addr->dreg, 0, ins->dreg);
11309
11310                                 EMIT_NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
11311                         } else {
11312                                 if ((ip + 5 < end) && ip_in_bb (cfg, cfg->cbb, ip + 5) && 
11313                                         ((ip [5] == CEE_CALL) || (ip [5] == CEE_CALLVIRT)) && 
11314                                         (cmethod = mini_get_method (cfg, method, read32 (ip + 6), NULL, generic_context)) &&
11315                                         (cmethod->klass == mono_defaults.systemtype_class) &&
11316                                         (strcmp (cmethod->name, "GetTypeFromHandle") == 0)) {
11317                                         MonoClass *tclass = mono_class_from_mono_type ((MonoType *)handle);
11318
11319                                         mono_class_init (tclass);
11320                                         if (context_used) {
11321                                                 ins = mini_emit_get_rgctx_klass (cfg, context_used,
11322                                                         tclass, MONO_RGCTX_INFO_REFLECTION_TYPE);
11323                                         } else if (cfg->compile_aot) {
11324                                                 if (method->wrapper_type) {
11325                                                         error_init (&error); //got to do it since there are multiple conditionals below
11326                                                         if (mono_class_get_checked (tclass->image, tclass->type_token, &error) == tclass && !generic_context) {
11327                                                                 /* Special case for static synchronized wrappers */
11328                                                                 EMIT_NEW_TYPE_FROM_HANDLE_CONST (cfg, ins, tclass->image, tclass->type_token, generic_context);
11329                                                         } else {
11330                                                                 mono_error_cleanup (&error); /* FIXME don't swallow the error */
11331                                                                 /* FIXME: n is not a normal token */
11332                                                                 DISABLE_AOT (cfg);
11333                                                                 EMIT_NEW_PCONST (cfg, ins, NULL);
11334                                                         }
11335                                                 } else {
11336                                                         EMIT_NEW_TYPE_FROM_HANDLE_CONST (cfg, ins, image, n, generic_context);
11337                                                 }
11338                                         } else {
11339                                                 MonoReflectionType *rt = mono_type_get_object_checked (cfg->domain, (MonoType *)handle, &cfg->error);
11340                                                 CHECK_CFG_ERROR;
11341                                                 EMIT_NEW_PCONST (cfg, ins, rt);
11342                                         }
11343                                         ins->type = STACK_OBJ;
11344                                         ins->klass = cmethod->klass;
11345                                         ip += 5;
11346                                 } else {
11347                                         MonoInst *addr, *vtvar;
11348
11349                                         vtvar = mono_compile_create_var (cfg, &handle_class->byval_arg, OP_LOCAL);
11350
11351                                         if (context_used) {
11352                                                 if (handle_class == mono_defaults.typehandle_class) {
11353                                                         ins = mini_emit_get_rgctx_klass (cfg, context_used,
11354                                                                         mono_class_from_mono_type ((MonoType *)handle),
11355                                                                         MONO_RGCTX_INFO_TYPE);
11356                                                 } else if (handle_class == mono_defaults.methodhandle_class) {
11357                                                         ins = emit_get_rgctx_method (cfg, context_used,
11358                                                                         (MonoMethod *)handle, MONO_RGCTX_INFO_METHOD);
11359                                                 } else if (handle_class == mono_defaults.fieldhandle_class) {
11360                                                         ins = emit_get_rgctx_field (cfg, context_used,
11361                                                                         (MonoClassField *)handle, MONO_RGCTX_INFO_CLASS_FIELD);
11362                                                 } else {
11363                                                         g_assert_not_reached ();
11364                                                 }
11365                                         } else if (cfg->compile_aot) {
11366                                                 EMIT_NEW_LDTOKENCONST (cfg, ins, image, n, generic_context);
11367                                         } else {
11368                                                 EMIT_NEW_PCONST (cfg, ins, handle);
11369                                         }
11370                                         EMIT_NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
11371                                         MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, addr->dreg, 0, ins->dreg);
11372                                         EMIT_NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
11373                                 }
11374                         }
11375
11376                         *sp++ = ins;
11377                         ip += 5;
11378                         break;
11379                 }
11380                 case CEE_THROW:
11381                         CHECK_STACK (1);
11382                         if (sp [-1]->type != STACK_OBJ)
11383                                 UNVERIFIED;
11384
11385                         MONO_INST_NEW (cfg, ins, OP_THROW);
11386                         --sp;
11387                         ins->sreg1 = sp [0]->dreg;
11388                         ip++;
11389                         cfg->cbb->out_of_line = TRUE;
11390                         MONO_ADD_INS (cfg->cbb, ins);
11391                         MONO_INST_NEW (cfg, ins, OP_NOT_REACHED);
11392                         MONO_ADD_INS (cfg->cbb, ins);
11393                         sp = stack_start;
11394                         
11395                         link_bblock (cfg, cfg->cbb, end_bblock);
11396                         start_new_bblock = 1;
11397                         /* This can complicate code generation for llvm since the return value might not be defined */
11398                         if (COMPILE_LLVM (cfg))
11399                                 INLINE_FAILURE ("throw");
11400                         break;
11401                 case CEE_ENDFINALLY:
11402                         if (!ip_in_finally_clause (cfg, ip - header->code))
11403                                 UNVERIFIED;
11404                         /* mono_save_seq_point_info () depends on this */
11405                         if (sp != stack_start)
11406                                 emit_seq_point (cfg, method, ip, FALSE, FALSE);
11407                         MONO_INST_NEW (cfg, ins, OP_ENDFINALLY);
11408                         MONO_ADD_INS (cfg->cbb, ins);
11409                         ip++;
11410                         start_new_bblock = 1;
11411
11412                         /*
11413                          * Control will leave the method so empty the stack, otherwise
11414                          * the next basic block will start with a nonempty stack.
11415                          */
11416                         while (sp != stack_start) {
11417                                 sp--;
11418                         }
11419                         break;
11420                 case CEE_LEAVE:
11421                 case CEE_LEAVE_S: {
11422                         GList *handlers;
11423
11424                         if (*ip == CEE_LEAVE) {
11425                                 CHECK_OPSIZE (5);
11426                                 target = ip + 5 + (gint32)read32(ip + 1);
11427                         } else {
11428                                 CHECK_OPSIZE (2);
11429                                 target = ip + 2 + (signed char)(ip [1]);
11430                         }
11431
11432                         /* empty the stack */
11433                         while (sp != stack_start) {
11434                                 sp--;
11435                         }
11436
11437                         /* 
11438                          * If this leave statement is in a catch block, check for a
11439                          * pending exception, and rethrow it if necessary.
11440                          * We avoid doing this in runtime invoke wrappers, since those are called
11441                          * by native code which excepts the wrapper to catch all exceptions.
11442                          */
11443                         for (i = 0; i < header->num_clauses; ++i) {
11444                                 MonoExceptionClause *clause = &header->clauses [i];
11445
11446                                 /* 
11447                                  * Use <= in the final comparison to handle clauses with multiple
11448                                  * leave statements, like in bug #78024.
11449                                  * The ordering of the exception clauses guarantees that we find the
11450                                  * innermost clause.
11451                                  */
11452                                 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) {
11453                                         MonoInst *exc_ins;
11454                                         MonoBasicBlock *dont_throw;
11455
11456                                         /*
11457                                           MonoInst *load;
11458
11459                                           NEW_TEMPLOAD (cfg, load, mono_find_exvar_for_offset (cfg, clause->handler_offset)->inst_c0);
11460                                         */
11461
11462                                         exc_ins = mono_emit_jit_icall (cfg, mono_thread_get_undeniable_exception, NULL);
11463
11464                                         NEW_BBLOCK (cfg, dont_throw);
11465
11466                                         /*
11467                                          * Currently, we always rethrow the abort exception, despite the 
11468                                          * fact that this is not correct. See thread6.cs for an example. 
11469                                          * But propagating the abort exception is more important than 
11470                                          * getting the sematics right.
11471                                          */
11472                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, exc_ins->dreg, 0);
11473                                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, dont_throw);
11474                                         MONO_EMIT_NEW_UNALU (cfg, OP_THROW, -1, exc_ins->dreg);
11475
11476                                         MONO_START_BB (cfg, dont_throw);
11477                                 }
11478                         }
11479
11480 #ifdef ENABLE_LLVM
11481                         cfg->cbb->try_end = (intptr_t)(ip - header->code);
11482 #endif
11483
11484                         if ((handlers = mono_find_final_block (cfg, ip, target, MONO_EXCEPTION_CLAUSE_FINALLY))) {
11485                                 GList *tmp;
11486
11487                                 for (tmp = handlers; tmp; tmp = tmp->next) {
11488                                         MonoExceptionClause *clause = (MonoExceptionClause *)tmp->data;
11489                                         MonoInst *abort_exc = (MonoInst *)mono_find_exvar_for_offset (cfg, clause->handler_offset);
11490                                         MonoBasicBlock *dont_throw;
11491
11492                                         tblock = cfg->cil_offset_to_bb [clause->handler_offset];
11493                                         g_assert (tblock);
11494                                         link_bblock (cfg, cfg->cbb, tblock);
11495
11496                                         MONO_EMIT_NEW_PCONST (cfg, abort_exc->dreg, 0);
11497
11498                                         MONO_INST_NEW (cfg, ins, OP_CALL_HANDLER);
11499                                         ins->inst_target_bb = tblock;
11500                                         ins->inst_eh_block = clause;
11501                                         MONO_ADD_INS (cfg->cbb, ins);
11502                                         cfg->cbb->has_call_handler = 1;
11503
11504                                         /* Throw exception if exvar is set */
11505                                         /* FIXME Do we need this for calls from catch/filter ? */
11506                                         NEW_BBLOCK (cfg, dont_throw);
11507                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, abort_exc->dreg, 0);
11508                                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, dont_throw);
11509                                         mono_emit_jit_icall (cfg, mono_thread_self_abort, NULL);
11510                                         cfg->cbb->clause_hole = clause;
11511
11512                                         MONO_START_BB (cfg, dont_throw);
11513                                         cfg->cbb->clause_hole = clause;
11514
11515                                         if (COMPILE_LLVM (cfg)) {
11516                                                 MonoBasicBlock *target_bb;
11517
11518                                                 /* 
11519                                                  * Link the finally bblock with the target, since it will
11520                                                  * conceptually branch there.
11521                                                  */
11522                                                 GET_BBLOCK (cfg, tblock, cfg->cil_start + clause->handler_offset + clause->handler_len - 1);
11523                                                 GET_BBLOCK (cfg, target_bb, target);
11524                                                 link_bblock (cfg, tblock, target_bb);
11525                                         }
11526                                 }
11527                                 g_list_free (handlers);
11528                         } 
11529
11530                         MONO_INST_NEW (cfg, ins, OP_BR);
11531                         MONO_ADD_INS (cfg->cbb, ins);
11532                         GET_BBLOCK (cfg, tblock, target);
11533                         link_bblock (cfg, cfg->cbb, tblock);
11534                         ins->inst_target_bb = tblock;
11535
11536                         start_new_bblock = 1;
11537
11538                         if (*ip == CEE_LEAVE)
11539                                 ip += 5;
11540                         else
11541                                 ip += 2;
11542
11543                         break;
11544                 }
11545
11546                         /*
11547                          * Mono specific opcodes
11548                          */
11549                 case MONO_CUSTOM_PREFIX: {
11550
11551                         g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
11552
11553                         CHECK_OPSIZE (2);
11554                         switch (ip [1]) {
11555                         case CEE_MONO_ICALL: {
11556                                 gpointer func;
11557                                 MonoJitICallInfo *info;
11558
11559                                 token = read32 (ip + 2);
11560                                 func = mono_method_get_wrapper_data (method, token);
11561                                 info = mono_find_jit_icall_by_addr (func);
11562                                 if (!info)
11563                                         g_error ("Could not find icall address in wrapper %s", mono_method_full_name (method, 1));
11564                                 g_assert (info);
11565
11566                                 CHECK_STACK (info->sig->param_count);
11567                                 sp -= info->sig->param_count;
11568
11569                                 if (cfg->compile_aot && !strcmp (info->name, "mono_threads_attach_coop")) {
11570                                         MonoInst *addr;
11571
11572                                         /*
11573                                          * This is called on unattached threads, so it cannot go through the trampoline
11574                                          * infrastructure. Use an indirect call through a got slot initialized at load time
11575                                          * instead.
11576                                          */
11577                                         EMIT_NEW_AOTCONST (cfg, addr, MONO_PATCH_INFO_JIT_ICALL_ADDR_NOCALL, (char*)info->name);
11578                                         ins = mini_emit_calli (cfg, info->sig, sp, addr, NULL, NULL);
11579                                 } else {
11580                                         ins = mono_emit_jit_icall (cfg, info->func, sp);
11581                                 }
11582
11583                                 if (!MONO_TYPE_IS_VOID (info->sig->ret))
11584                                         *sp++ = ins;
11585
11586                                 ip += 6;
11587                                 inline_costs += 10 * num_calls++;
11588
11589                                 break;
11590                         }
11591                         case CEE_MONO_LDPTR_CARD_TABLE:
11592                         case CEE_MONO_LDPTR_NURSERY_START:
11593                         case CEE_MONO_LDPTR_NURSERY_BITS:
11594                         case CEE_MONO_LDPTR_INT_REQ_FLAG:
11595                         case CEE_MONO_LDPTR_PROFILER_ALLOCATION_COUNT: {
11596                                 CHECK_STACK_OVF (1);
11597
11598                                 switch (ip [1]) {
11599                                 case CEE_MONO_LDPTR_CARD_TABLE:
11600                                         ins = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_GC_CARD_TABLE_ADDR, NULL);
11601                                         break;
11602                                 case CEE_MONO_LDPTR_NURSERY_START:
11603                                         ins = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_GC_NURSERY_START, NULL);
11604                                         break;
11605                                 case CEE_MONO_LDPTR_NURSERY_BITS:
11606                                         ins = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_GC_NURSERY_BITS, NULL);
11607                                         break;
11608                                 case CEE_MONO_LDPTR_INT_REQ_FLAG:
11609                                         ins = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG, NULL);
11610                                         break;
11611                                 case CEE_MONO_LDPTR_PROFILER_ALLOCATION_COUNT:
11612                                         ins = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_PROFILER_ALLOCATION_COUNT, NULL);
11613                                         break;
11614                                 default:
11615                                         g_assert_not_reached ();
11616                                         break;
11617                                 }
11618
11619                                 *sp++ = ins;
11620                                 ip += 2;
11621                                 inline_costs += 10 * num_calls++;
11622                                 break;
11623                         }
11624                         case CEE_MONO_LDPTR: {
11625                                 gpointer ptr;
11626
11627                                 CHECK_STACK_OVF (1);
11628                                 CHECK_OPSIZE (6);
11629                                 token = read32 (ip + 2);
11630
11631                                 ptr = mono_method_get_wrapper_data (method, token);
11632                                 EMIT_NEW_PCONST (cfg, ins, ptr);
11633                                 *sp++ = ins;
11634                                 ip += 6;
11635                                 inline_costs += 10 * num_calls++;
11636                                 /* Can't embed random pointers into AOT code */
11637                                 DISABLE_AOT (cfg);
11638                                 break;
11639                         }
11640                         case CEE_MONO_JIT_ICALL_ADDR: {
11641                                 MonoJitICallInfo *callinfo;
11642                                 gpointer ptr;
11643
11644                                 CHECK_STACK_OVF (1);
11645                                 CHECK_OPSIZE (6);
11646                                 token = read32 (ip + 2);
11647
11648                                 ptr = mono_method_get_wrapper_data (method, token);
11649                                 callinfo = mono_find_jit_icall_by_addr (ptr);
11650                                 g_assert (callinfo);
11651                                 EMIT_NEW_JIT_ICALL_ADDRCONST (cfg, ins, (char*)callinfo->name);
11652                                 *sp++ = ins;
11653                                 ip += 6;
11654                                 inline_costs += 10 * num_calls++;
11655                                 break;
11656                         }
11657                         case CEE_MONO_ICALL_ADDR: {
11658                                 MonoMethod *cmethod;
11659                                 gpointer ptr;
11660
11661                                 CHECK_STACK_OVF (1);
11662                                 CHECK_OPSIZE (6);
11663                                 token = read32 (ip + 2);
11664
11665                                 cmethod = (MonoMethod *)mono_method_get_wrapper_data (method, token);
11666
11667                                 if (cfg->compile_aot) {
11668                                         if (cfg->direct_pinvoke && ip + 6 < end && (ip [6] == CEE_POP)) {
11669                                                 /*
11670                                                  * This is generated by emit_native_wrapper () to resolve the pinvoke address
11671                                                  * before the call, its not needed when using direct pinvoke.
11672                                                  * This is not an optimization, but its used to avoid looking up pinvokes
11673                                                  * on platforms which don't support dlopen ().
11674                                                  */
11675                                                 EMIT_NEW_PCONST (cfg, ins, NULL);
11676                                         } else {
11677                                                 EMIT_NEW_AOTCONST (cfg, ins, MONO_PATCH_INFO_ICALL_ADDR, cmethod);
11678                                         }
11679                                 } else {
11680                                         ptr = mono_lookup_internal_call (cmethod);
11681                                         g_assert (ptr);
11682                                         EMIT_NEW_PCONST (cfg, ins, ptr);
11683                                 }
11684                                 *sp++ = ins;
11685                                 ip += 6;
11686                                 break;
11687                         }
11688                         case CEE_MONO_VTADDR: {
11689                                 MonoInst *src_var, *src;
11690
11691                                 CHECK_STACK (1);
11692                                 --sp;
11693
11694                                 // FIXME:
11695                                 src_var = get_vreg_to_inst (cfg, sp [0]->dreg);
11696                                 EMIT_NEW_VARLOADA ((cfg), (src), src_var, src_var->inst_vtype);
11697                                 *sp++ = src;
11698                                 ip += 2;
11699                                 break;
11700                         }
11701                         case CEE_MONO_NEWOBJ: {
11702                                 MonoInst *iargs [2];
11703
11704                                 CHECK_STACK_OVF (1);
11705                                 CHECK_OPSIZE (6);
11706                                 token = read32 (ip + 2);
11707                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
11708                                 mono_class_init (klass);
11709                                 NEW_DOMAINCONST (cfg, iargs [0]);
11710                                 MONO_ADD_INS (cfg->cbb, iargs [0]);
11711                                 NEW_CLASSCONST (cfg, iargs [1], klass);
11712                                 MONO_ADD_INS (cfg->cbb, iargs [1]);
11713                                 *sp++ = mono_emit_jit_icall (cfg, ves_icall_object_new, iargs);
11714                                 ip += 6;
11715                                 inline_costs += 10 * num_calls++;
11716                                 break;
11717                         }
11718                         case CEE_MONO_OBJADDR:
11719                                 CHECK_STACK (1);
11720                                 --sp;
11721                                 MONO_INST_NEW (cfg, ins, OP_MOVE);
11722                                 ins->dreg = alloc_ireg_mp (cfg);
11723                                 ins->sreg1 = sp [0]->dreg;
11724                                 ins->type = STACK_MP;
11725                                 MONO_ADD_INS (cfg->cbb, ins);
11726                                 *sp++ = ins;
11727                                 ip += 2;
11728                                 break;
11729                         case CEE_MONO_LDNATIVEOBJ:
11730                                 /*
11731                                  * Similar to LDOBJ, but instead load the unmanaged 
11732                                  * representation of the vtype to the stack.
11733                                  */
11734                                 CHECK_STACK (1);
11735                                 CHECK_OPSIZE (6);
11736                                 --sp;
11737                                 token = read32 (ip + 2);
11738                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
11739                                 g_assert (klass->valuetype);
11740                                 mono_class_init (klass);
11741
11742                                 {
11743                                         MonoInst *src, *dest, *temp;
11744
11745                                         src = sp [0];
11746                                         temp = mono_compile_create_var (cfg, &klass->byval_arg, OP_LOCAL);
11747                                         temp->backend.is_pinvoke = 1;
11748                                         EMIT_NEW_TEMPLOADA (cfg, dest, temp->inst_c0);
11749                                         mini_emit_memory_copy (cfg, dest, src, klass, TRUE, 0);
11750
11751                                         EMIT_NEW_TEMPLOAD (cfg, dest, temp->inst_c0);
11752                                         dest->type = STACK_VTYPE;
11753                                         dest->klass = klass;
11754
11755                                         *sp ++ = dest;
11756                                         ip += 6;
11757                                 }
11758                                 break;
11759                         case CEE_MONO_RETOBJ: {
11760                                 /*
11761                                  * Same as RET, but return the native representation of a vtype
11762                                  * to the caller.
11763                                  */
11764                                 g_assert (cfg->ret);
11765                                 g_assert (mono_method_signature (method)->pinvoke); 
11766                                 CHECK_STACK (1);
11767                                 --sp;
11768                                 
11769                                 CHECK_OPSIZE (6);
11770                                 token = read32 (ip + 2);    
11771                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
11772
11773                                 if (!cfg->vret_addr) {
11774                                         g_assert (cfg->ret_var_is_local);
11775
11776                                         EMIT_NEW_VARLOADA (cfg, ins, cfg->ret, cfg->ret->inst_vtype);
11777                                 } else {
11778                                         EMIT_NEW_RETLOADA (cfg, ins);
11779                                 }
11780                                 mini_emit_memory_copy (cfg, ins, sp [0], klass, TRUE, 0);
11781                                 
11782                                 if (sp != stack_start)
11783                                         UNVERIFIED;
11784                                 
11785                                 mini_profiler_emit_leave (cfg, sp [0]);
11786
11787                                 MONO_INST_NEW (cfg, ins, OP_BR);
11788                                 ins->inst_target_bb = end_bblock;
11789                                 MONO_ADD_INS (cfg->cbb, ins);
11790                                 link_bblock (cfg, cfg->cbb, end_bblock);
11791                                 start_new_bblock = 1;
11792                                 ip += 6;
11793                                 break;
11794                         }
11795                         case CEE_MONO_SAVE_LMF:
11796                         case CEE_MONO_RESTORE_LMF:
11797                                 ip += 2;
11798                                 break;
11799                         case CEE_MONO_CLASSCONST:
11800                                 CHECK_STACK_OVF (1);
11801                                 CHECK_OPSIZE (6);
11802                                 token = read32 (ip + 2);
11803                                 EMIT_NEW_CLASSCONST (cfg, ins, mono_method_get_wrapper_data (method, token));
11804                                 *sp++ = ins;
11805                                 ip += 6;
11806                                 inline_costs += 10 * num_calls++;
11807                                 break;
11808                         case CEE_MONO_NOT_TAKEN:
11809                                 cfg->cbb->out_of_line = TRUE;
11810                                 ip += 2;
11811                                 break;
11812                         case CEE_MONO_TLS: {
11813                                 MonoTlsKey key;
11814
11815                                 CHECK_STACK_OVF (1);
11816                                 CHECK_OPSIZE (6);
11817                                 key = (MonoTlsKey)read32 (ip + 2);
11818                                 g_assert (key < TLS_KEY_NUM);
11819
11820                                 ins = mono_create_tls_get (cfg, key);
11821                                 g_assert (ins);
11822                                 ins->type = STACK_PTR;
11823                                 *sp++ = ins;
11824                                 ip += 6;
11825                                 break;
11826                         }
11827                         case CEE_MONO_DYN_CALL: {
11828                                 MonoCallInst *call;
11829
11830                                 /* It would be easier to call a trampoline, but that would put an
11831                                  * extra frame on the stack, confusing exception handling. So
11832                                  * implement it inline using an opcode for now.
11833                                  */
11834
11835                                 if (!cfg->dyn_call_var) {
11836                                         cfg->dyn_call_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
11837                                         /* prevent it from being register allocated */
11838                                         cfg->dyn_call_var->flags |= MONO_INST_VOLATILE;
11839                                 }
11840
11841                                 /* Has to use a call inst since it local regalloc expects it */
11842                                 MONO_INST_NEW_CALL (cfg, call, OP_DYN_CALL);
11843                                 ins = (MonoInst*)call;
11844                                 sp -= 2;
11845                                 ins->sreg1 = sp [0]->dreg;
11846                                 ins->sreg2 = sp [1]->dreg;
11847                                 MONO_ADD_INS (cfg->cbb, ins);
11848
11849                                 cfg->param_area = MAX (cfg->param_area, cfg->backend->dyn_call_param_area);
11850
11851                                 ip += 2;
11852                                 inline_costs += 10 * num_calls++;
11853
11854                                 break;
11855                         }
11856                         case CEE_MONO_MEMORY_BARRIER: {
11857                                 CHECK_OPSIZE (6);
11858                                 mini_emit_memory_barrier (cfg, (int)read32 (ip + 2));
11859                                 ip += 6;
11860                                 break;
11861                         }
11862                         case CEE_MONO_ATOMIC_STORE_I4: {
11863                                 g_assert (mono_arch_opcode_supported (OP_ATOMIC_STORE_I4));
11864
11865                                 CHECK_OPSIZE (6);
11866                                 CHECK_STACK (2);
11867                                 sp -= 2;
11868
11869                                 MONO_INST_NEW (cfg, ins, OP_ATOMIC_STORE_I4);
11870                                 ins->dreg = sp [0]->dreg;
11871                                 ins->sreg1 = sp [1]->dreg;
11872                                 ins->backend.memory_barrier_kind = (int) read32 (ip + 2);
11873                                 MONO_ADD_INS (cfg->cbb, ins);
11874
11875                                 ip += 6;
11876                                 break;
11877                         }
11878                         case CEE_MONO_JIT_ATTACH: {
11879                                 MonoInst *args [16], *domain_ins;
11880                                 MonoInst *ad_ins, *jit_tls_ins;
11881                                 MonoBasicBlock *next_bb = NULL, *call_bb = NULL;
11882
11883                                 g_assert (!mono_threads_is_blocking_transition_enabled ());
11884
11885                                 cfg->orig_domain_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
11886
11887                                 EMIT_NEW_PCONST (cfg, ins, NULL);
11888                                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, cfg->orig_domain_var->dreg, ins->dreg);
11889
11890                                 ad_ins = mono_create_tls_get (cfg, TLS_KEY_DOMAIN);
11891                                 jit_tls_ins = mono_create_tls_get (cfg, TLS_KEY_JIT_TLS);
11892
11893                                 if (ad_ins && jit_tls_ins) {
11894                                         NEW_BBLOCK (cfg, next_bb);
11895                                         NEW_BBLOCK (cfg, call_bb);
11896
11897                                         if (cfg->compile_aot) {
11898                                                 /* AOT code is only used in the root domain */
11899                                                 EMIT_NEW_PCONST (cfg, domain_ins, NULL);
11900                                         } else {
11901                                                 EMIT_NEW_PCONST (cfg, domain_ins, cfg->domain);
11902                                         }
11903                                         MONO_EMIT_NEW_BIALU (cfg, OP_COMPARE, -1, ad_ins->dreg, domain_ins->dreg);
11904                                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, call_bb);
11905
11906                                         MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, jit_tls_ins->dreg, 0);
11907                                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBEQ, call_bb);
11908
11909                                         MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, next_bb);
11910                                         MONO_START_BB (cfg, call_bb);
11911                                 }
11912
11913                                 /* AOT code is only used in the root domain */
11914                                 EMIT_NEW_PCONST (cfg, args [0], cfg->compile_aot ? NULL : cfg->domain);
11915                                 if (cfg->compile_aot) {
11916                                         MonoInst *addr;
11917
11918                                         /*
11919                                          * This is called on unattached threads, so it cannot go through the trampoline
11920                                          * infrastructure. Use an indirect call through a got slot initialized at load time
11921                                          * instead.
11922                                          */
11923                                         EMIT_NEW_AOTCONST (cfg, addr, MONO_PATCH_INFO_JIT_THREAD_ATTACH, NULL);
11924                                         ins = mini_emit_calli (cfg, helper_sig_jit_thread_attach, args, addr, NULL, NULL);
11925                                 } else {
11926                                         ins = mono_emit_jit_icall (cfg, mono_jit_thread_attach, args);
11927                                 }
11928                                 MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, cfg->orig_domain_var->dreg, ins->dreg);
11929
11930                                 if (next_bb)
11931                                         MONO_START_BB (cfg, next_bb);
11932
11933                                 ip += 2;
11934                                 break;
11935                         }
11936                         case CEE_MONO_JIT_DETACH: {
11937                                 MonoInst *args [16];
11938
11939                                 /* Restore the original domain */
11940                                 dreg = alloc_ireg (cfg);
11941                                 EMIT_NEW_UNALU (cfg, args [0], OP_MOVE, dreg, cfg->orig_domain_var->dreg);
11942                                 mono_emit_jit_icall (cfg, mono_jit_set_domain, args);
11943                                 ip += 2;
11944                                 break;
11945                         }
11946                         case CEE_MONO_CALLI_EXTRA_ARG: {
11947                                 MonoInst *addr;
11948                                 MonoMethodSignature *fsig;
11949                                 MonoInst *arg;
11950
11951                                 /*
11952                                  * This is the same as CEE_CALLI, but passes an additional argument
11953                                  * to the called method in llvmonly mode.
11954                                  * This is only used by delegate invoke wrappers to call the
11955                                  * actual delegate method.
11956                                  */
11957                                 g_assert (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE);
11958
11959                                 CHECK_OPSIZE (6);
11960                                 token = read32 (ip + 2);
11961
11962                                 ins = NULL;
11963
11964                                 cmethod = NULL;
11965                                 CHECK_STACK (1);
11966                                 --sp;
11967                                 addr = *sp;
11968                                 fsig = mini_get_signature (method, token, generic_context, &cfg->error);
11969                                 CHECK_CFG_ERROR;
11970
11971                                 if (cfg->llvm_only)
11972                                         cfg->signatures = g_slist_prepend_mempool (cfg->mempool, cfg->signatures, fsig);
11973
11974                                 n = fsig->param_count + fsig->hasthis + 1;
11975
11976                                 CHECK_STACK (n);
11977
11978                                 sp -= n;
11979                                 arg = sp [n - 1];
11980
11981                                 if (cfg->llvm_only) {
11982                                         /*
11983                                          * The lowest bit of 'arg' determines whenever the callee uses the gsharedvt
11984                                          * cconv. This is set by mono_init_delegate ().
11985                                          */
11986                                         if (cfg->gsharedvt && mini_is_gsharedvt_variable_signature (fsig)) {
11987                                                 MonoInst *callee = addr;
11988                                                 MonoInst *call, *localloc_ins;
11989                                                 MonoBasicBlock *is_gsharedvt_bb, *end_bb;
11990                                                 int low_bit_reg = alloc_preg (cfg);
11991
11992                                                 NEW_BBLOCK (cfg, is_gsharedvt_bb);
11993                                                 NEW_BBLOCK (cfg, end_bb);
11994
11995                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PAND_IMM, low_bit_reg, arg->dreg, 1);
11996                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, low_bit_reg, 0);
11997                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, is_gsharedvt_bb);
11998
11999                                                 /* Normal case: callee uses a normal cconv, have to add an out wrapper */
12000                                                 addr = emit_get_rgctx_sig (cfg, context_used,
12001                                                                                                    fsig, MONO_RGCTX_INFO_SIG_GSHAREDVT_OUT_TRAMPOLINE_CALLI);
12002                                                 /*
12003                                                  * ADDR points to a gsharedvt-out wrapper, have to pass <callee, arg> as an extra arg.
12004                                                  */
12005                                                 MONO_INST_NEW (cfg, ins, OP_LOCALLOC_IMM);
12006                                                 ins->dreg = alloc_preg (cfg);
12007                                                 ins->inst_imm = 2 * SIZEOF_VOID_P;
12008                                                 MONO_ADD_INS (cfg->cbb, ins);
12009                                                 localloc_ins = ins;
12010                                                 cfg->flags |= MONO_CFG_HAS_ALLOCA;
12011                                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, localloc_ins->dreg, 0, callee->dreg);
12012                                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, localloc_ins->dreg, SIZEOF_VOID_P, arg->dreg);
12013
12014                                                 call = emit_extra_arg_calli (cfg, fsig, sp, localloc_ins->dreg, addr);
12015                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
12016
12017                                                 /* Gsharedvt case: callee uses a gsharedvt cconv, no conversion is needed */
12018                                                 MONO_START_BB (cfg, is_gsharedvt_bb);
12019                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PXOR_IMM, arg->dreg, arg->dreg, 1);
12020                                                 ins = emit_extra_arg_calli (cfg, fsig, sp, arg->dreg, callee);
12021                                                 ins->dreg = call->dreg;
12022
12023                                                 MONO_START_BB (cfg, end_bb);
12024                                         } else {
12025                                                 /* Caller uses a normal calling conv */
12026
12027                                                 MonoInst *callee = addr;
12028                                                 MonoInst *call, *localloc_ins;
12029                                                 MonoBasicBlock *is_gsharedvt_bb, *end_bb;
12030                                                 int low_bit_reg = alloc_preg (cfg);
12031
12032                                                 NEW_BBLOCK (cfg, is_gsharedvt_bb);
12033                                                 NEW_BBLOCK (cfg, end_bb);
12034
12035                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PAND_IMM, low_bit_reg, arg->dreg, 1);
12036                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, low_bit_reg, 0);
12037                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, is_gsharedvt_bb);
12038
12039                                                 /* Normal case: callee uses a normal cconv, no conversion is needed */
12040                                                 call = emit_extra_arg_calli (cfg, fsig, sp, arg->dreg, callee);
12041                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
12042                                                 /* Gsharedvt case: callee uses a gsharedvt cconv, have to add an in wrapper */
12043                                                 MONO_START_BB (cfg, is_gsharedvt_bb);
12044                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_PXOR_IMM, arg->dreg, arg->dreg, 1);
12045                                                 NEW_AOTCONST (cfg, addr, MONO_PATCH_INFO_GSHAREDVT_IN_WRAPPER, fsig);
12046                                                 MONO_ADD_INS (cfg->cbb, addr);
12047                                                 /*
12048                                                  * ADDR points to a gsharedvt-in wrapper, have to pass <callee, arg> as an extra arg.
12049                                                  */
12050                                                 MONO_INST_NEW (cfg, ins, OP_LOCALLOC_IMM);
12051                                                 ins->dreg = alloc_preg (cfg);
12052                                                 ins->inst_imm = 2 * SIZEOF_VOID_P;
12053                                                 MONO_ADD_INS (cfg->cbb, ins);
12054                                                 localloc_ins = ins;
12055                                                 cfg->flags |= MONO_CFG_HAS_ALLOCA;
12056                                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, localloc_ins->dreg, 0, callee->dreg);
12057                                                 MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, localloc_ins->dreg, SIZEOF_VOID_P, arg->dreg);
12058
12059                                                 ins = emit_extra_arg_calli (cfg, fsig, sp, localloc_ins->dreg, addr);
12060                                                 ins->dreg = call->dreg;
12061                                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
12062
12063                                                 MONO_START_BB (cfg, end_bb);
12064                                         }
12065                                 } else {
12066                                         /* Same as CEE_CALLI */
12067                                         if (cfg->gsharedvt && mini_is_gsharedvt_signature (fsig)) {
12068                                                 /*
12069                                                  * We pass the address to the gsharedvt trampoline in the rgctx reg
12070                                                  */
12071                                                 MonoInst *callee = addr;
12072
12073                                                 addr = emit_get_rgctx_sig (cfg, context_used,
12074                                                                                                    fsig, MONO_RGCTX_INFO_SIG_GSHAREDVT_OUT_TRAMPOLINE_CALLI);
12075                                                 ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, NULL, callee);
12076                                         } else {
12077                                                 ins = (MonoInst*)mini_emit_calli (cfg, fsig, sp, addr, NULL, NULL);
12078                                         }
12079                                 }
12080
12081                                 if (!MONO_TYPE_IS_VOID (fsig->ret))
12082                                         *sp++ = mono_emit_widen_call_res (cfg, ins, fsig);
12083
12084                                 CHECK_CFG_EXCEPTION;
12085
12086                                 ip += 6;
12087                                 ins_flag = 0;
12088                                 constrained_class = NULL;
12089                                 break;
12090                         }
12091                         case CEE_MONO_LDDOMAIN:
12092                                 CHECK_STACK_OVF (1);
12093                                 EMIT_NEW_PCONST (cfg, ins, cfg->compile_aot ? NULL : cfg->domain);
12094                                 ip += 2;
12095                                 *sp++ = ins;
12096                                 break;
12097                         case CEE_MONO_GET_LAST_ERROR:
12098                                 CHECK_OPSIZE (2);
12099                                 CHECK_STACK_OVF (1);
12100
12101                                 MONO_INST_NEW (cfg, ins, OP_GET_LAST_ERROR);
12102                                 ins->dreg = alloc_dreg (cfg, STACK_I4);
12103                                 ins->type = STACK_I4;
12104                                 MONO_ADD_INS (cfg->cbb, ins);
12105
12106                                 ip += 2;
12107                                 *sp++ = ins;
12108                                 break;
12109                         case CEE_MONO_GET_RGCTX_ARG:
12110                                 CHECK_OPSIZE (2);
12111                                 CHECK_STACK_OVF (1);
12112
12113                                 mono_create_rgctx_var (cfg);
12114
12115                                 MONO_INST_NEW (cfg, ins, OP_MOVE);
12116                                 ins->dreg = alloc_dreg (cfg, STACK_PTR);
12117                                 ins->sreg1 = cfg->rgctx_var->dreg;
12118                                 ins->type = STACK_PTR;
12119                                 MONO_ADD_INS (cfg->cbb, ins);
12120
12121                                 ip += 2;
12122                                 *sp++ = ins;
12123                                 break;
12124                         default:
12125                                 g_error ("opcode 0x%02x 0x%02x not handled", MONO_CUSTOM_PREFIX, ip [1]);
12126                                 break;
12127                         }
12128                         break;
12129                 }
12130
12131                 case CEE_PREFIX1: {
12132                         CHECK_OPSIZE (2);
12133                         switch (ip [1]) {
12134                         case CEE_ARGLIST: {
12135                                 /* somewhat similar to LDTOKEN */
12136                                 MonoInst *addr, *vtvar;
12137                                 CHECK_STACK_OVF (1);
12138                                 vtvar = mono_compile_create_var (cfg, &mono_defaults.argumenthandle_class->byval_arg, OP_LOCAL); 
12139
12140                                 EMIT_NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
12141                                 EMIT_NEW_UNALU (cfg, ins, OP_ARGLIST, -1, addr->dreg);
12142
12143                                 EMIT_NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
12144                                 ins->type = STACK_VTYPE;
12145                                 ins->klass = mono_defaults.argumenthandle_class;
12146                                 *sp++ = ins;
12147                                 ip += 2;
12148                                 break;
12149                         }
12150                         case CEE_CEQ:
12151                         case CEE_CGT:
12152                         case CEE_CGT_UN:
12153                         case CEE_CLT:
12154                         case CEE_CLT_UN: {
12155                                 MonoInst *cmp, *arg1, *arg2;
12156
12157                                 CHECK_STACK (2);
12158                                 sp -= 2;
12159                                 arg1 = sp [0];
12160                                 arg2 = sp [1];
12161
12162                                 /*
12163                                  * The following transforms:
12164                                  *    CEE_CEQ    into OP_CEQ
12165                                  *    CEE_CGT    into OP_CGT
12166                                  *    CEE_CGT_UN into OP_CGT_UN
12167                                  *    CEE_CLT    into OP_CLT
12168                                  *    CEE_CLT_UN into OP_CLT_UN
12169                                  */
12170                                 MONO_INST_NEW (cfg, cmp, (OP_CEQ - CEE_CEQ) + ip [1]);
12171
12172                                 MONO_INST_NEW (cfg, ins, cmp->opcode);
12173                                 cmp->sreg1 = arg1->dreg;
12174                                 cmp->sreg2 = arg2->dreg;
12175                                 type_from_op (cfg, cmp, arg1, arg2);
12176                                 CHECK_TYPE (cmp);
12177                                 add_widen_op (cfg, cmp, &arg1, &arg2);
12178                                 if ((arg1->type == STACK_I8) || ((SIZEOF_VOID_P == 8) && ((arg1->type == STACK_PTR) || (arg1->type == STACK_OBJ) || (arg1->type == STACK_MP))))
12179                                         cmp->opcode = OP_LCOMPARE;
12180                                 else if (arg1->type == STACK_R4)
12181                                         cmp->opcode = OP_RCOMPARE;
12182                                 else if (arg1->type == STACK_R8)
12183                                         cmp->opcode = OP_FCOMPARE;
12184                                 else
12185                                         cmp->opcode = OP_ICOMPARE;
12186                                 MONO_ADD_INS (cfg->cbb, cmp);
12187                                 ins->type = STACK_I4;
12188                                 ins->dreg = alloc_dreg (cfg, (MonoStackType)ins->type);
12189                                 type_from_op (cfg, ins, arg1, arg2);
12190
12191                                 if (cmp->opcode == OP_FCOMPARE || cmp->opcode == OP_RCOMPARE) {
12192                                         /*
12193                                          * The backends expect the fceq opcodes to do the
12194                                          * comparison too.
12195                                          */
12196                                         ins->sreg1 = cmp->sreg1;
12197                                         ins->sreg2 = cmp->sreg2;
12198                                         NULLIFY_INS (cmp);
12199                                 }
12200                                 MONO_ADD_INS (cfg->cbb, ins);
12201                                 *sp++ = ins;
12202                                 ip += 2;
12203                                 break;
12204                         }
12205                         case CEE_LDFTN: {
12206                                 MonoInst *argconst;
12207                                 MonoMethod *cil_method;
12208
12209                                 CHECK_STACK_OVF (1);
12210                                 CHECK_OPSIZE (6);
12211                                 n = read32 (ip + 2);
12212                                 cmethod = mini_get_method (cfg, method, n, NULL, generic_context);
12213                                 CHECK_CFG_ERROR;
12214
12215                                 mono_class_init (cmethod->klass);
12216
12217                                 mono_save_token_info (cfg, image, n, cmethod);
12218
12219                                 context_used = mini_method_check_context_used (cfg, cmethod);
12220
12221                                 cil_method = cmethod;
12222                                 if (!dont_verify && !cfg->skip_visibility && !mono_method_can_access_method (method, cmethod))
12223                                         emit_method_access_failure (cfg, method, cil_method);
12224
12225                                 if (mono_security_core_clr_enabled ())
12226                                         ensure_method_is_allowed_to_call_method (cfg, method, cmethod);
12227
12228                                 /* 
12229                                  * Optimize the common case of ldftn+delegate creation
12230                                  */
12231                                 if ((sp > stack_start) && (ip + 6 + 5 < end) && ip_in_bb (cfg, cfg->cbb, ip + 6) && (ip [6] == CEE_NEWOBJ)) {
12232                                         MonoMethod *ctor_method = mini_get_method (cfg, method, read32 (ip + 7), NULL, generic_context);
12233                                         if (ctor_method && (ctor_method->klass->parent == mono_defaults.multicastdelegate_class)) {
12234                                                 MonoInst *target_ins, *handle_ins;
12235                                                 MonoMethod *invoke;
12236                                                 int invoke_context_used;
12237
12238                                                 invoke = mono_get_delegate_invoke (ctor_method->klass);
12239                                                 if (!invoke || !mono_method_signature (invoke))
12240                                                         LOAD_ERROR;
12241
12242                                                 invoke_context_used = mini_method_check_context_used (cfg, invoke);
12243
12244                                                 target_ins = sp [-1];
12245
12246                                                 if (mono_security_core_clr_enabled ())
12247                                                         ensure_method_is_allowed_to_call_method (cfg, method, ctor_method);
12248
12249                                                 if (!(cmethod->flags & METHOD_ATTRIBUTE_STATIC)) {
12250                                                         /*LAME IMPL: We must not add a null check for virtual invoke delegates.*/
12251                                                         if (mono_method_signature (invoke)->param_count == mono_method_signature (cmethod)->param_count) {
12252                                                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, target_ins->dreg, 0);
12253                                                                 MONO_EMIT_NEW_COND_EXC (cfg, EQ, "ArgumentException");
12254                                                         }
12255                                                 }
12256
12257                                                 /* FIXME: SGEN support */
12258                                                 if (invoke_context_used == 0 || cfg->llvm_only) {
12259                                                         ip += 6;
12260                                                         if (cfg->verbose_level > 3)
12261                                                                 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));
12262                                                         if ((handle_ins = handle_delegate_ctor (cfg, ctor_method->klass, target_ins, cmethod, context_used, FALSE))) {
12263                                                                 sp --;
12264                                                                 *sp = handle_ins;
12265                                                                 CHECK_CFG_EXCEPTION;
12266                                                                 ip += 5;
12267                                                                 sp ++;
12268                                                                 break;
12269                                                         }
12270                                                         ip -= 6;
12271                                                 }
12272                                         }
12273                                 }
12274
12275                                 argconst = emit_get_rgctx_method (cfg, context_used, cmethod, MONO_RGCTX_INFO_METHOD);
12276                                 ins = mono_emit_jit_icall (cfg, mono_ldftn, &argconst);
12277                                 *sp++ = ins;
12278                                 
12279                                 ip += 6;
12280                                 inline_costs += 10 * num_calls++;
12281                                 break;
12282                         }
12283                         case CEE_LDVIRTFTN: {
12284                                 MonoInst *args [2];
12285
12286                                 CHECK_STACK (1);
12287                                 CHECK_OPSIZE (6);
12288                                 n = read32 (ip + 2);
12289                                 cmethod = mini_get_method (cfg, method, n, NULL, generic_context);
12290                                 CHECK_CFG_ERROR;
12291
12292                                 mono_class_init (cmethod->klass);
12293  
12294                                 context_used = mini_method_check_context_used (cfg, cmethod);
12295
12296                                 if (mono_security_core_clr_enabled ())
12297                                         ensure_method_is_allowed_to_call_method (cfg, method, cmethod);
12298
12299                                 /*
12300                                  * Optimize the common case of ldvirtftn+delegate creation
12301                                  */
12302                                 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)) {
12303                                         MonoMethod *ctor_method = mini_get_method (cfg, method, read32 (ip + 7), NULL, generic_context);
12304                                         if (ctor_method && (ctor_method->klass->parent == mono_defaults.multicastdelegate_class)) {
12305                                                 MonoInst *target_ins, *handle_ins;
12306                                                 MonoMethod *invoke;
12307                                                 int invoke_context_used;
12308                                                 gboolean is_virtual = cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL;
12309
12310                                                 invoke = mono_get_delegate_invoke (ctor_method->klass);
12311                                                 if (!invoke || !mono_method_signature (invoke))
12312                                                         LOAD_ERROR;
12313
12314                                                 invoke_context_used = mini_method_check_context_used (cfg, invoke);
12315
12316                                                 target_ins = sp [-1];
12317
12318                                                 if (mono_security_core_clr_enabled ())
12319                                                         ensure_method_is_allowed_to_call_method (cfg, method, ctor_method);
12320
12321                                                 /* FIXME: SGEN support */
12322                                                 if (invoke_context_used == 0 || cfg->llvm_only) {
12323                                                         ip += 6;
12324                                                         if (cfg->verbose_level > 3)
12325                                                                 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));
12326                                                         if ((handle_ins = handle_delegate_ctor (cfg, ctor_method->klass, target_ins, cmethod, context_used, is_virtual))) {
12327                                                                 sp -= 2;
12328                                                                 *sp = handle_ins;
12329                                                                 CHECK_CFG_EXCEPTION;
12330                                                                 ip += 5;
12331                                                                 sp ++;
12332                                                                 break;
12333                                                         }
12334                                                         ip -= 6;
12335                                                 }
12336                                         }
12337                                 }
12338
12339                                 --sp;
12340                                 args [0] = *sp;
12341
12342                                 args [1] = emit_get_rgctx_method (cfg, context_used,
12343                                                                                                   cmethod, MONO_RGCTX_INFO_METHOD);
12344
12345                                 if (context_used)
12346                                         *sp++ = mono_emit_jit_icall (cfg, mono_ldvirtfn_gshared, args);
12347                                 else
12348                                         *sp++ = mono_emit_jit_icall (cfg, mono_ldvirtfn, args);
12349
12350                                 ip += 6;
12351                                 inline_costs += 10 * num_calls++;
12352                                 break;
12353                         }
12354                         case CEE_LDARG:
12355                                 CHECK_STACK_OVF (1);
12356                                 CHECK_OPSIZE (4);
12357                                 n = read16 (ip + 2);
12358                                 CHECK_ARG (n);
12359                                 EMIT_NEW_ARGLOAD (cfg, ins, n);
12360                                 *sp++ = ins;
12361                                 ip += 4;
12362                                 break;
12363                         case CEE_LDARGA:
12364                                 CHECK_STACK_OVF (1);
12365                                 CHECK_OPSIZE (4);
12366                                 n = read16 (ip + 2);
12367                                 CHECK_ARG (n);
12368                                 NEW_ARGLOADA (cfg, ins, n);
12369                                 MONO_ADD_INS (cfg->cbb, ins);
12370                                 *sp++ = ins;
12371                                 ip += 4;
12372                                 break;
12373                         case CEE_STARG:
12374                                 CHECK_STACK (1);
12375                                 --sp;
12376                                 CHECK_OPSIZE (4);
12377                                 n = read16 (ip + 2);
12378                                 CHECK_ARG (n);
12379                                 if (!dont_verify_stloc && target_type_is_incompatible (cfg, param_types [n], *sp))
12380                                         UNVERIFIED;
12381                                 emit_starg_ir (cfg, sp, n);
12382                                 ip += 4;
12383                                 break;
12384                         case CEE_LDLOC:
12385                                 CHECK_STACK_OVF (1);
12386                                 CHECK_OPSIZE (4);
12387                                 n = read16 (ip + 2);
12388                                 CHECK_LOCAL (n);
12389                                 if ((ip [4] == CEE_LDFLD) && ip_in_bb (cfg, cfg->cbb, ip + 4) && header->locals [n]->type == MONO_TYPE_VALUETYPE) {
12390                                         /* Avoid loading a struct just to load one of its fields */
12391                                         EMIT_NEW_LOCLOADA (cfg, ins, n);
12392                                 } else {
12393                                         EMIT_NEW_LOCLOAD (cfg, ins, n);
12394                                 }
12395                                 *sp++ = ins;
12396                                 ip += 4;
12397                                 break;
12398                         case CEE_LDLOCA: {
12399                                 unsigned char *tmp_ip;
12400                                 CHECK_STACK_OVF (1);
12401                                 CHECK_OPSIZE (4);
12402                                 n = read16 (ip + 2);
12403                                 CHECK_LOCAL (n);
12404
12405                                 if ((tmp_ip = emit_optimized_ldloca_ir (cfg, ip, end, 2))) {
12406                                         ip = tmp_ip;
12407                                         inline_costs += 1;
12408                                         break;
12409                                 }                       
12410                                 
12411                                 EMIT_NEW_LOCLOADA (cfg, ins, n);
12412                                 *sp++ = ins;
12413                                 ip += 4;
12414                                 break;
12415                         }
12416                         case CEE_STLOC:
12417                                 CHECK_STACK (1);
12418                                 --sp;
12419                                 CHECK_OPSIZE (4);
12420                                 n = read16 (ip + 2);
12421                                 CHECK_LOCAL (n);
12422                                 if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [n], *sp))
12423                                         UNVERIFIED;
12424                                 emit_stloc_ir (cfg, sp, header, n);
12425                                 ip += 4;
12426                                 inline_costs += 1;
12427                                 break;
12428                         case CEE_LOCALLOC: {
12429                                 CHECK_STACK (1);
12430                                 MonoBasicBlock *non_zero_bb, *end_bb;
12431                                 int alloc_ptr = alloc_preg (cfg);
12432                                 --sp;
12433                                 if (sp != stack_start) 
12434                                         UNVERIFIED;
12435                                 if (cfg->method != method) 
12436                                         /* 
12437                                          * Inlining this into a loop in a parent could lead to 
12438                                          * stack overflows which is different behavior than the
12439                                          * non-inlined case, thus disable inlining in this case.
12440                                          */
12441                                         INLINE_FAILURE("localloc");
12442
12443                                 NEW_BBLOCK (cfg, non_zero_bb);
12444                                 NEW_BBLOCK (cfg, end_bb);
12445
12446                                 /* if size != zero */
12447                                 MONO_EMIT_NEW_BIALU_IMM (cfg, OP_COMPARE_IMM, -1, sp [0]->dreg, 0);
12448                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_PBNE_UN, non_zero_bb);
12449
12450                                 //size is zero, so result is NULL
12451                                 MONO_EMIT_NEW_PCONST (cfg, alloc_ptr, NULL);
12452                                 MONO_EMIT_NEW_BRANCH_BLOCK (cfg, OP_BR, end_bb);
12453
12454                                 MONO_START_BB (cfg, non_zero_bb);
12455                                 MONO_INST_NEW (cfg, ins, OP_LOCALLOC);
12456                                 ins->dreg = alloc_ptr;
12457                                 ins->sreg1 = sp [0]->dreg;
12458                                 ins->type = STACK_PTR;
12459                                 MONO_ADD_INS (cfg->cbb, ins);
12460
12461                                 cfg->flags |= MONO_CFG_HAS_ALLOCA;
12462                                 if (init_locals)
12463                                         ins->flags |= MONO_INST_INIT;
12464
12465                                 MONO_START_BB (cfg, end_bb);
12466                                 EMIT_NEW_UNALU (cfg, ins, OP_MOVE, alloc_preg (cfg), alloc_ptr);
12467                                 ins->type = STACK_PTR;
12468
12469                                 *sp++ = ins;
12470                                 ip += 2;
12471                                 break;
12472                         }
12473                         case CEE_ENDFILTER: {
12474                                 MonoExceptionClause *clause, *nearest;
12475                                 int cc;
12476
12477                                 CHECK_STACK (1);
12478                                 --sp;
12479                                 if ((sp != stack_start) || (sp [0]->type != STACK_I4)) 
12480                                         UNVERIFIED;
12481                                 MONO_INST_NEW (cfg, ins, OP_ENDFILTER);
12482                                 ins->sreg1 = (*sp)->dreg;
12483                                 MONO_ADD_INS (cfg->cbb, ins);
12484                                 start_new_bblock = 1;
12485                                 ip += 2;
12486
12487                                 nearest = NULL;
12488                                 for (cc = 0; cc < header->num_clauses; ++cc) {
12489                                         clause = &header->clauses [cc];
12490                                         if ((clause->flags & MONO_EXCEPTION_CLAUSE_FILTER) &&
12491                                                 ((ip - header->code) > clause->data.filter_offset && (ip - header->code) <= clause->handler_offset) &&
12492                                             (!nearest || (clause->data.filter_offset < nearest->data.filter_offset)))
12493                                                 nearest = clause;
12494                                 }
12495                                 g_assert (nearest);
12496                                 if ((ip - header->code) != nearest->handler_offset)
12497                                         UNVERIFIED;
12498
12499                                 break;
12500                         }
12501                         case CEE_UNALIGNED_:
12502                                 ins_flag |= MONO_INST_UNALIGNED;
12503                                 /* FIXME: record alignment? we can assume 1 for now */
12504                                 CHECK_OPSIZE (3);
12505                                 ip += 3;
12506                                 break;
12507                         case CEE_VOLATILE_:
12508                                 ins_flag |= MONO_INST_VOLATILE;
12509                                 ip += 2;
12510                                 break;
12511                         case CEE_TAIL_:
12512                                 ins_flag   |= MONO_INST_TAILCALL;
12513                                 cfg->flags |= MONO_CFG_HAS_TAIL;
12514                                 /* Can't inline tail calls at this time */
12515                                 inline_costs += 100000;
12516                                 ip += 2;
12517                                 break;
12518                         case CEE_INITOBJ:
12519                                 CHECK_STACK (1);
12520                                 --sp;
12521                                 CHECK_OPSIZE (6);
12522                                 token = read32 (ip + 2);
12523                                 klass = mini_get_class (method, token, generic_context);
12524                                 CHECK_TYPELOAD (klass);
12525                                 if (generic_class_is_reference_type (cfg, klass))
12526                                         MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STORE_MEMBASE_IMM, sp [0]->dreg, 0, 0);
12527                                 else
12528                                         mini_emit_initobj (cfg, *sp, NULL, klass);
12529                                 ip += 6;
12530                                 inline_costs += 1;
12531                                 break;
12532                         case CEE_CONSTRAINED_:
12533                                 CHECK_OPSIZE (6);
12534                                 token = read32 (ip + 2);
12535                                 constrained_class = mini_get_class (method, token, generic_context);
12536                                 CHECK_TYPELOAD (constrained_class);
12537                                 ip += 6;
12538                                 break;
12539                         case CEE_CPBLK:
12540                                 CHECK_STACK (3);
12541                                 sp -= 3;
12542                                 mini_emit_memory_copy_bytes (cfg, sp [0], sp [1], sp [2], ins_flag);
12543                                 ip += 2;
12544                                 ins_flag = 0;
12545                                 inline_costs += 1;
12546                                 break;
12547                         case CEE_INITBLK:
12548                                 CHECK_STACK (3);
12549                                 sp -= 3;
12550                                 mini_emit_memory_init_bytes (cfg, sp [0], sp [1], sp [2], ins_flag);
12551                                 ip += 2;
12552                                 ins_flag = 0;
12553                                 inline_costs += 1;
12554                                 break;
12555                         case CEE_NO_:
12556                                 CHECK_OPSIZE (3);
12557                                 if (ip [2] & 0x1)
12558                                         ins_flag |= MONO_INST_NOTYPECHECK;
12559                                 if (ip [2] & 0x2)
12560                                         ins_flag |= MONO_INST_NORANGECHECK;
12561                                 /* we ignore the no-nullcheck for now since we
12562                                  * really do it explicitly only when doing callvirt->call
12563                                  */
12564                                 ip += 3;
12565                                 break;
12566                         case CEE_RETHROW: {
12567                                 MonoInst *load;
12568                                 int handler_offset = -1;
12569
12570                                 for (i = 0; i < header->num_clauses; ++i) {
12571                                         MonoExceptionClause *clause = &header->clauses [i];
12572                                         if (MONO_OFFSET_IN_HANDLER (clause, ip - header->code) && !(clause->flags & MONO_EXCEPTION_CLAUSE_FINALLY)) {
12573                                                 handler_offset = clause->handler_offset;
12574                                                 break;
12575                                         }
12576                                 }
12577
12578                                 cfg->cbb->flags |= BB_EXCEPTION_UNSAFE;
12579
12580                                 if (handler_offset == -1)
12581                                         UNVERIFIED;
12582
12583                                 EMIT_NEW_TEMPLOAD (cfg, load, mono_find_exvar_for_offset (cfg, handler_offset)->inst_c0);
12584                                 MONO_INST_NEW (cfg, ins, OP_RETHROW);
12585                                 ins->sreg1 = load->dreg;
12586                                 MONO_ADD_INS (cfg->cbb, ins);
12587
12588                                 MONO_INST_NEW (cfg, ins, OP_NOT_REACHED);
12589                                 MONO_ADD_INS (cfg->cbb, ins);
12590
12591                                 sp = stack_start;
12592                                 link_bblock (cfg, cfg->cbb, end_bblock);
12593                                 start_new_bblock = 1;
12594                                 ip += 2;
12595                                 break;
12596                         }
12597                         case CEE_SIZEOF: {
12598                                 guint32 val;
12599                                 int ialign;
12600
12601                                 CHECK_STACK_OVF (1);
12602                                 CHECK_OPSIZE (6);
12603                                 token = read32 (ip + 2);
12604                                 if (mono_metadata_token_table (token) == MONO_TABLE_TYPESPEC && !image_is_dynamic (method->klass->image) && !generic_context) {
12605                                         MonoType *type = mono_type_create_from_typespec_checked (image, token, &cfg->error);
12606                                         CHECK_CFG_ERROR;
12607
12608                                         val = mono_type_size (type, &ialign);
12609                                 } else {
12610                                         MonoClass *klass = mini_get_class (method, token, generic_context);
12611                                         CHECK_TYPELOAD (klass);
12612
12613                                         val = mono_type_size (&klass->byval_arg, &ialign);
12614
12615                                         if (mini_is_gsharedvt_klass (klass))
12616                                                 GSHAREDVT_FAILURE (*ip);
12617                                 }
12618                                 EMIT_NEW_ICONST (cfg, ins, val);
12619                                 *sp++= ins;
12620                                 ip += 6;
12621                                 break;
12622                         }
12623                         case CEE_REFANYTYPE: {
12624                                 MonoInst *src_var, *src;
12625
12626                                 GSHAREDVT_FAILURE (*ip);
12627
12628                                 CHECK_STACK (1);
12629                                 --sp;
12630
12631                                 // FIXME:
12632                                 src_var = get_vreg_to_inst (cfg, sp [0]->dreg);
12633                                 if (!src_var)
12634                                         src_var = mono_compile_create_var_for_vreg (cfg, &mono_defaults.typed_reference_class->byval_arg, OP_LOCAL, sp [0]->dreg);
12635                                 EMIT_NEW_VARLOADA (cfg, src, src_var, src_var->inst_vtype);
12636                                 EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, &mono_defaults.typehandle_class->byval_arg, src->dreg, MONO_STRUCT_OFFSET (MonoTypedRef, type));
12637                                 *sp++ = ins;
12638                                 ip += 2;
12639                                 break;
12640                         }
12641                         case CEE_READONLY_:
12642                                 readonly = TRUE;
12643                                 ip += 2;
12644                                 break;
12645
12646                         case CEE_UNUSED56:
12647                         case CEE_UNUSED57:
12648                         case CEE_UNUSED70:
12649                         case CEE_UNUSED:
12650                         case CEE_UNUSED99:
12651                                 UNVERIFIED;
12652                                 
12653                         default:
12654                                 g_warning ("opcode 0xfe 0x%02x not handled", ip [1]);
12655                                 UNVERIFIED;
12656                         }
12657                         break;
12658                 }
12659                 case CEE_UNUSED58:
12660                 case CEE_UNUSED1:
12661                         UNVERIFIED;
12662
12663                 default:
12664                         g_warning ("opcode 0x%02x not handled", *ip);
12665                         UNVERIFIED;
12666                 }
12667         }
12668         if (start_new_bblock != 1)
12669                 UNVERIFIED;
12670
12671         cfg->cbb->cil_length = ip - cfg->cbb->cil_code;
12672         if (cfg->cbb->next_bb) {
12673                 /* This could already be set because of inlining, #693905 */
12674                 MonoBasicBlock *bb = cfg->cbb;
12675
12676                 while (bb->next_bb)
12677                         bb = bb->next_bb;
12678                 bb->next_bb = end_bblock;
12679         } else {
12680                 cfg->cbb->next_bb = end_bblock;
12681         }
12682
12683         if (cfg->method == method && cfg->domainvar) {
12684                 MonoInst *store;
12685                 MonoInst *get_domain;
12686
12687                 cfg->cbb = init_localsbb;
12688
12689                 get_domain = mono_create_tls_get (cfg, TLS_KEY_DOMAIN);
12690                 NEW_TEMPSTORE (cfg, store, cfg->domainvar->inst_c0, get_domain);
12691                 MONO_ADD_INS (cfg->cbb, store);
12692         }
12693
12694 #if defined(TARGET_POWERPC) || defined(TARGET_X86)
12695         if (cfg->compile_aot)
12696                 /* FIXME: The plt slots require a GOT var even if the method doesn't use it */
12697                 mono_get_got_var (cfg);
12698 #endif
12699
12700         if (cfg->method == method && cfg->got_var)
12701                 mono_emit_load_got_addr (cfg);
12702
12703         if (init_localsbb) {
12704                 cfg->cbb = init_localsbb;
12705                 cfg->ip = NULL;
12706                 for (i = 0; i < header->num_locals; ++i) {
12707                         emit_init_local (cfg, i, header->locals [i], init_locals);
12708                 }
12709         }
12710
12711         if (cfg->init_ref_vars && cfg->method == method) {
12712                 /* Emit initialization for ref vars */
12713                 // FIXME: Avoid duplication initialization for IL locals.
12714                 for (i = 0; i < cfg->num_varinfo; ++i) {
12715                         MonoInst *ins = cfg->varinfo [i];
12716
12717                         if (ins->opcode == OP_LOCAL && ins->type == STACK_OBJ)
12718                                 MONO_EMIT_NEW_PCONST (cfg, ins->dreg, NULL);
12719                 }
12720         }
12721
12722         if (cfg->lmf_var && cfg->method == method && !cfg->llvm_only) {
12723                 cfg->cbb = init_localsbb;
12724                 emit_push_lmf (cfg);
12725         }
12726
12727         cfg->cbb = init_localsbb;
12728         mini_profiler_emit_enter (cfg);
12729
12730         if (seq_points) {
12731                 MonoBasicBlock *bb;
12732
12733                 /*
12734                  * Make seq points at backward branch targets interruptable.
12735                  */
12736                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
12737                         if (bb->code && bb->in_count > 1 && bb->code->opcode == OP_SEQ_POINT)
12738                                 bb->code->flags |= MONO_INST_SINGLE_STEP_LOC;
12739         }
12740
12741         /* Add a sequence point for method entry/exit events */
12742         if (seq_points && cfg->gen_sdb_seq_points) {
12743                 NEW_SEQ_POINT (cfg, ins, METHOD_ENTRY_IL_OFFSET, FALSE);
12744                 MONO_ADD_INS (init_localsbb, ins);
12745                 NEW_SEQ_POINT (cfg, ins, METHOD_EXIT_IL_OFFSET, FALSE);
12746                 MONO_ADD_INS (cfg->bb_exit, ins);
12747         }
12748
12749         /*
12750          * Add seq points for IL offsets which have line number info, but wasn't generated a seq point during JITting because
12751          * the code they refer to was dead (#11880).
12752          */
12753         if (sym_seq_points) {
12754                 for (i = 0; i < header->code_size; ++i) {
12755                         if (mono_bitset_test_fast (seq_point_locs, i) && !mono_bitset_test_fast (seq_point_set_locs, i)) {
12756                                 MonoInst *ins;
12757
12758                                 NEW_SEQ_POINT (cfg, ins, i, FALSE);
12759                                 mono_add_seq_point (cfg, NULL, ins, SEQ_POINT_NATIVE_OFFSET_DEAD_CODE);
12760                         }
12761                 }
12762         }
12763
12764         cfg->ip = NULL;
12765
12766         if (cfg->method == method) {
12767                 MonoBasicBlock *bb;
12768                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
12769                         if (bb == cfg->bb_init)
12770                                 bb->region = -1;
12771                         else
12772                                 bb->region = mono_find_block_region (cfg, bb->real_offset);
12773                         if (cfg->spvars)
12774                                 mono_create_spvar_for_region (cfg, bb->region);
12775                         if (cfg->verbose_level > 2)
12776                                 printf ("REGION BB%d IL_%04x ID_%08X\n", bb->block_num, bb->real_offset, bb->region);
12777                 }
12778         } else {
12779                 MonoBasicBlock *bb;
12780                 /* get_most_deep_clause () in mini-llvm.c depends on this for inlined bblocks */
12781                 for (bb = start_bblock; bb != end_bblock; bb  = bb->next_bb) {
12782                         bb->real_offset = inline_offset;
12783                 }
12784         }
12785
12786         if (inline_costs < 0) {
12787                 char *mname;
12788
12789                 /* Method is too large */
12790                 mname = mono_method_full_name (method, TRUE);
12791                 mono_cfg_set_exception_invalid_program (cfg, g_strdup_printf ("Method %s is too complex.", mname));
12792                 g_free (mname);
12793         }
12794
12795         if ((cfg->verbose_level > 2) && (cfg->method == method)) 
12796                 mono_print_code (cfg, "AFTER METHOD-TO-IR");
12797
12798         goto cleanup;
12799
12800 mono_error_exit:
12801         g_assert (!mono_error_ok (&cfg->error));
12802         goto cleanup;
12803  
12804  exception_exit:
12805         g_assert (cfg->exception_type != MONO_EXCEPTION_NONE);
12806         goto cleanup;
12807
12808  unverified:
12809         set_exception_type_from_invalid_il (cfg, method, ip);
12810         goto cleanup;
12811
12812  cleanup:
12813         g_slist_free (class_inits);
12814         mono_basic_block_free (original_bb);
12815         cfg->dont_inline = g_list_remove (cfg->dont_inline, method);
12816         if (cfg->exception_type)
12817                 return -1;
12818         else
12819                 return inline_costs;
12820 }
12821
12822 static int
12823 store_membase_reg_to_store_membase_imm (int opcode)
12824 {
12825         switch (opcode) {
12826         case OP_STORE_MEMBASE_REG:
12827                 return OP_STORE_MEMBASE_IMM;
12828         case OP_STOREI1_MEMBASE_REG:
12829                 return OP_STOREI1_MEMBASE_IMM;
12830         case OP_STOREI2_MEMBASE_REG:
12831                 return OP_STOREI2_MEMBASE_IMM;
12832         case OP_STOREI4_MEMBASE_REG:
12833                 return OP_STOREI4_MEMBASE_IMM;
12834         case OP_STOREI8_MEMBASE_REG:
12835                 return OP_STOREI8_MEMBASE_IMM;
12836         default:
12837                 g_assert_not_reached ();
12838         }
12839
12840         return -1;
12841 }               
12842
12843 int
12844 mono_op_to_op_imm (int opcode)
12845 {
12846         switch (opcode) {
12847         case OP_IADD:
12848                 return OP_IADD_IMM;
12849         case OP_ISUB:
12850                 return OP_ISUB_IMM;
12851         case OP_IDIV:
12852                 return OP_IDIV_IMM;
12853         case OP_IDIV_UN:
12854                 return OP_IDIV_UN_IMM;
12855         case OP_IREM:
12856                 return OP_IREM_IMM;
12857         case OP_IREM_UN:
12858                 return OP_IREM_UN_IMM;
12859         case OP_IMUL:
12860                 return OP_IMUL_IMM;
12861         case OP_IAND:
12862                 return OP_IAND_IMM;
12863         case OP_IOR:
12864                 return OP_IOR_IMM;
12865         case OP_IXOR:
12866                 return OP_IXOR_IMM;
12867         case OP_ISHL:
12868                 return OP_ISHL_IMM;
12869         case OP_ISHR:
12870                 return OP_ISHR_IMM;
12871         case OP_ISHR_UN:
12872                 return OP_ISHR_UN_IMM;
12873
12874         case OP_LADD:
12875                 return OP_LADD_IMM;
12876         case OP_LSUB:
12877                 return OP_LSUB_IMM;
12878         case OP_LAND:
12879                 return OP_LAND_IMM;
12880         case OP_LOR:
12881                 return OP_LOR_IMM;
12882         case OP_LXOR:
12883                 return OP_LXOR_IMM;
12884         case OP_LSHL:
12885                 return OP_LSHL_IMM;
12886         case OP_LSHR:
12887                 return OP_LSHR_IMM;
12888         case OP_LSHR_UN:
12889                 return OP_LSHR_UN_IMM;
12890 #if SIZEOF_REGISTER == 8
12891         case OP_LREM:
12892                 return OP_LREM_IMM;
12893 #endif
12894
12895         case OP_COMPARE:
12896                 return OP_COMPARE_IMM;
12897         case OP_ICOMPARE:
12898                 return OP_ICOMPARE_IMM;
12899         case OP_LCOMPARE:
12900                 return OP_LCOMPARE_IMM;
12901
12902         case OP_STORE_MEMBASE_REG:
12903                 return OP_STORE_MEMBASE_IMM;
12904         case OP_STOREI1_MEMBASE_REG:
12905                 return OP_STOREI1_MEMBASE_IMM;
12906         case OP_STOREI2_MEMBASE_REG:
12907                 return OP_STOREI2_MEMBASE_IMM;
12908         case OP_STOREI4_MEMBASE_REG:
12909                 return OP_STOREI4_MEMBASE_IMM;
12910
12911 #if defined(TARGET_X86) || defined (TARGET_AMD64)
12912         case OP_X86_PUSH:
12913                 return OP_X86_PUSH_IMM;
12914         case OP_X86_COMPARE_MEMBASE_REG:
12915                 return OP_X86_COMPARE_MEMBASE_IMM;
12916 #endif
12917 #if defined(TARGET_AMD64)
12918         case OP_AMD64_ICOMPARE_MEMBASE_REG:
12919                 return OP_AMD64_ICOMPARE_MEMBASE_IMM;
12920 #endif
12921         case OP_VOIDCALL_REG:
12922                 return OP_VOIDCALL;
12923         case OP_CALL_REG:
12924                 return OP_CALL;
12925         case OP_LCALL_REG:
12926                 return OP_LCALL;
12927         case OP_FCALL_REG:
12928                 return OP_FCALL;
12929         case OP_LOCALLOC:
12930                 return OP_LOCALLOC_IMM;
12931         }
12932
12933         return -1;
12934 }
12935
12936 static int
12937 ldind_to_load_membase (int opcode)
12938 {
12939         switch (opcode) {
12940         case CEE_LDIND_I1:
12941                 return OP_LOADI1_MEMBASE;
12942         case CEE_LDIND_U1:
12943                 return OP_LOADU1_MEMBASE;
12944         case CEE_LDIND_I2:
12945                 return OP_LOADI2_MEMBASE;
12946         case CEE_LDIND_U2:
12947                 return OP_LOADU2_MEMBASE;
12948         case CEE_LDIND_I4:
12949                 return OP_LOADI4_MEMBASE;
12950         case CEE_LDIND_U4:
12951                 return OP_LOADU4_MEMBASE;
12952         case CEE_LDIND_I:
12953                 return OP_LOAD_MEMBASE;
12954         case CEE_LDIND_REF:
12955                 return OP_LOAD_MEMBASE;
12956         case CEE_LDIND_I8:
12957                 return OP_LOADI8_MEMBASE;
12958         case CEE_LDIND_R4:
12959                 return OP_LOADR4_MEMBASE;
12960         case CEE_LDIND_R8:
12961                 return OP_LOADR8_MEMBASE;
12962         default:
12963                 g_assert_not_reached ();
12964         }
12965
12966         return -1;
12967 }
12968
12969 static int
12970 stind_to_store_membase (int opcode)
12971 {
12972         switch (opcode) {
12973         case CEE_STIND_I1:
12974                 return OP_STOREI1_MEMBASE_REG;
12975         case CEE_STIND_I2:
12976                 return OP_STOREI2_MEMBASE_REG;
12977         case CEE_STIND_I4:
12978                 return OP_STOREI4_MEMBASE_REG;
12979         case CEE_STIND_I:
12980         case CEE_STIND_REF:
12981                 return OP_STORE_MEMBASE_REG;
12982         case CEE_STIND_I8:
12983                 return OP_STOREI8_MEMBASE_REG;
12984         case CEE_STIND_R4:
12985                 return OP_STORER4_MEMBASE_REG;
12986         case CEE_STIND_R8:
12987                 return OP_STORER8_MEMBASE_REG;
12988         default:
12989                 g_assert_not_reached ();
12990         }
12991
12992         return -1;
12993 }
12994
12995 int
12996 mono_load_membase_to_load_mem (int opcode)
12997 {
12998         // FIXME: Add a MONO_ARCH_HAVE_LOAD_MEM macro
12999 #if defined(TARGET_X86) || defined(TARGET_AMD64)
13000         switch (opcode) {
13001         case OP_LOAD_MEMBASE:
13002                 return OP_LOAD_MEM;
13003         case OP_LOADU1_MEMBASE:
13004                 return OP_LOADU1_MEM;
13005         case OP_LOADU2_MEMBASE:
13006                 return OP_LOADU2_MEM;
13007         case OP_LOADI4_MEMBASE:
13008                 return OP_LOADI4_MEM;
13009         case OP_LOADU4_MEMBASE:
13010                 return OP_LOADU4_MEM;
13011 #if SIZEOF_REGISTER == 8
13012         case OP_LOADI8_MEMBASE:
13013                 return OP_LOADI8_MEM;
13014 #endif
13015         }
13016 #endif
13017
13018         return -1;
13019 }
13020
13021 static inline int
13022 op_to_op_dest_membase (int store_opcode, int opcode)
13023 {
13024 #if defined(TARGET_X86)
13025         if (!((store_opcode == OP_STORE_MEMBASE_REG) || (store_opcode == OP_STOREI4_MEMBASE_REG)))
13026                 return -1;
13027
13028         switch (opcode) {
13029         case OP_IADD:
13030                 return OP_X86_ADD_MEMBASE_REG;
13031         case OP_ISUB:
13032                 return OP_X86_SUB_MEMBASE_REG;
13033         case OP_IAND:
13034                 return OP_X86_AND_MEMBASE_REG;
13035         case OP_IOR:
13036                 return OP_X86_OR_MEMBASE_REG;
13037         case OP_IXOR:
13038                 return OP_X86_XOR_MEMBASE_REG;
13039         case OP_ADD_IMM:
13040         case OP_IADD_IMM:
13041                 return OP_X86_ADD_MEMBASE_IMM;
13042         case OP_SUB_IMM:
13043         case OP_ISUB_IMM:
13044                 return OP_X86_SUB_MEMBASE_IMM;
13045         case OP_AND_IMM:
13046         case OP_IAND_IMM:
13047                 return OP_X86_AND_MEMBASE_IMM;
13048         case OP_OR_IMM:
13049         case OP_IOR_IMM:
13050                 return OP_X86_OR_MEMBASE_IMM;
13051         case OP_XOR_IMM:
13052         case OP_IXOR_IMM:
13053                 return OP_X86_XOR_MEMBASE_IMM;
13054         case OP_MOVE:
13055                 return OP_NOP;
13056         }
13057 #endif
13058
13059 #if defined(TARGET_AMD64)
13060         if (!((store_opcode == OP_STORE_MEMBASE_REG) || (store_opcode == OP_STOREI4_MEMBASE_REG) || (store_opcode == OP_STOREI8_MEMBASE_REG)))
13061                 return -1;
13062
13063         switch (opcode) {
13064         case OP_IADD:
13065                 return OP_X86_ADD_MEMBASE_REG;
13066         case OP_ISUB:
13067                 return OP_X86_SUB_MEMBASE_REG;
13068         case OP_IAND:
13069                 return OP_X86_AND_MEMBASE_REG;
13070         case OP_IOR:
13071                 return OP_X86_OR_MEMBASE_REG;
13072         case OP_IXOR:
13073                 return OP_X86_XOR_MEMBASE_REG;
13074         case OP_IADD_IMM:
13075                 return OP_X86_ADD_MEMBASE_IMM;
13076         case OP_ISUB_IMM:
13077                 return OP_X86_SUB_MEMBASE_IMM;
13078         case OP_IAND_IMM:
13079                 return OP_X86_AND_MEMBASE_IMM;
13080         case OP_IOR_IMM:
13081                 return OP_X86_OR_MEMBASE_IMM;
13082         case OP_IXOR_IMM:
13083                 return OP_X86_XOR_MEMBASE_IMM;
13084         case OP_LADD:
13085                 return OP_AMD64_ADD_MEMBASE_REG;
13086         case OP_LSUB:
13087                 return OP_AMD64_SUB_MEMBASE_REG;
13088         case OP_LAND:
13089                 return OP_AMD64_AND_MEMBASE_REG;
13090         case OP_LOR:
13091                 return OP_AMD64_OR_MEMBASE_REG;
13092         case OP_LXOR:
13093                 return OP_AMD64_XOR_MEMBASE_REG;
13094         case OP_ADD_IMM:
13095         case OP_LADD_IMM:
13096                 return OP_AMD64_ADD_MEMBASE_IMM;
13097         case OP_SUB_IMM:
13098         case OP_LSUB_IMM:
13099                 return OP_AMD64_SUB_MEMBASE_IMM;
13100         case OP_AND_IMM:
13101         case OP_LAND_IMM:
13102                 return OP_AMD64_AND_MEMBASE_IMM;
13103         case OP_OR_IMM:
13104         case OP_LOR_IMM:
13105                 return OP_AMD64_OR_MEMBASE_IMM;
13106         case OP_XOR_IMM:
13107         case OP_LXOR_IMM:
13108                 return OP_AMD64_XOR_MEMBASE_IMM;
13109         case OP_MOVE:
13110                 return OP_NOP;
13111         }
13112 #endif
13113
13114         return -1;
13115 }
13116
13117 static inline int
13118 op_to_op_store_membase (int store_opcode, int opcode)
13119 {
13120 #if defined(TARGET_X86) || defined(TARGET_AMD64)
13121         switch (opcode) {
13122         case OP_ICEQ:
13123                 if (store_opcode == OP_STOREI1_MEMBASE_REG)
13124                         return OP_X86_SETEQ_MEMBASE;
13125         case OP_CNE:
13126                 if (store_opcode == OP_STOREI1_MEMBASE_REG)
13127                         return OP_X86_SETNE_MEMBASE;
13128         }
13129 #endif
13130
13131         return -1;
13132 }
13133
13134 static inline int
13135 op_to_op_src1_membase (MonoCompile *cfg, int load_opcode, int opcode)
13136 {
13137 #ifdef TARGET_X86
13138         /* FIXME: This has sign extension issues */
13139         /*
13140         if ((opcode == OP_ICOMPARE_IMM) && (load_opcode == OP_LOADU1_MEMBASE))
13141                 return OP_X86_COMPARE_MEMBASE8_IMM;
13142         */
13143
13144         if (!((load_opcode == OP_LOAD_MEMBASE) || (load_opcode == OP_LOADI4_MEMBASE) || (load_opcode == OP_LOADU4_MEMBASE)))
13145                 return -1;
13146
13147         switch (opcode) {
13148         case OP_X86_PUSH:
13149                 return OP_X86_PUSH_MEMBASE;
13150         case OP_COMPARE_IMM:
13151         case OP_ICOMPARE_IMM:
13152                 return OP_X86_COMPARE_MEMBASE_IMM;
13153         case OP_COMPARE:
13154         case OP_ICOMPARE:
13155                 return OP_X86_COMPARE_MEMBASE_REG;
13156         }
13157 #endif
13158
13159 #ifdef TARGET_AMD64
13160         /* FIXME: This has sign extension issues */
13161         /*
13162         if ((opcode == OP_ICOMPARE_IMM) && (load_opcode == OP_LOADU1_MEMBASE))
13163                 return OP_X86_COMPARE_MEMBASE8_IMM;
13164         */
13165
13166         switch (opcode) {
13167         case OP_X86_PUSH:
13168                 if ((load_opcode == OP_LOAD_MEMBASE && !cfg->backend->ilp32) || (load_opcode == OP_LOADI8_MEMBASE))
13169                         return OP_X86_PUSH_MEMBASE;
13170                 break;
13171                 /* FIXME: This only works for 32 bit immediates
13172         case OP_COMPARE_IMM:
13173         case OP_LCOMPARE_IMM:
13174                 if ((load_opcode == OP_LOAD_MEMBASE) || (load_opcode == OP_LOADI8_MEMBASE))
13175                         return OP_AMD64_COMPARE_MEMBASE_IMM;
13176                 */
13177         case OP_ICOMPARE_IMM:
13178                 if ((load_opcode == OP_LOADI4_MEMBASE) || (load_opcode == OP_LOADU4_MEMBASE))
13179                         return OP_AMD64_ICOMPARE_MEMBASE_IMM;
13180                 break;
13181         case OP_COMPARE:
13182         case OP_LCOMPARE:
13183                 if (cfg->backend->ilp32 && load_opcode == OP_LOAD_MEMBASE)
13184                         return OP_AMD64_ICOMPARE_MEMBASE_REG;
13185                 if ((load_opcode == OP_LOAD_MEMBASE && !cfg->backend->ilp32) || (load_opcode == OP_LOADI8_MEMBASE))
13186                         return OP_AMD64_COMPARE_MEMBASE_REG;
13187                 break;
13188         case OP_ICOMPARE:
13189                 if ((load_opcode == OP_LOADI4_MEMBASE) || (load_opcode == OP_LOADU4_MEMBASE))
13190                         return OP_AMD64_ICOMPARE_MEMBASE_REG;
13191                 break;
13192         }
13193 #endif
13194
13195         return -1;
13196 }
13197
13198 static inline int
13199 op_to_op_src2_membase (MonoCompile *cfg, int load_opcode, int opcode)
13200 {
13201 #ifdef TARGET_X86
13202         if (!((load_opcode == OP_LOAD_MEMBASE) || (load_opcode == OP_LOADI4_MEMBASE) || (load_opcode == OP_LOADU4_MEMBASE)))
13203                 return -1;
13204         
13205         switch (opcode) {
13206         case OP_COMPARE:
13207         case OP_ICOMPARE:
13208                 return OP_X86_COMPARE_REG_MEMBASE;
13209         case OP_IADD:
13210                 return OP_X86_ADD_REG_MEMBASE;
13211         case OP_ISUB:
13212                 return OP_X86_SUB_REG_MEMBASE;
13213         case OP_IAND:
13214                 return OP_X86_AND_REG_MEMBASE;
13215         case OP_IOR:
13216                 return OP_X86_OR_REG_MEMBASE;
13217         case OP_IXOR:
13218                 return OP_X86_XOR_REG_MEMBASE;
13219         }
13220 #endif
13221
13222 #ifdef TARGET_AMD64
13223         if ((load_opcode == OP_LOADI4_MEMBASE) || (load_opcode == OP_LOADU4_MEMBASE) || (load_opcode == OP_LOAD_MEMBASE && cfg->backend->ilp32)) {
13224                 switch (opcode) {
13225                 case OP_ICOMPARE:
13226                         return OP_AMD64_ICOMPARE_REG_MEMBASE;
13227                 case OP_IADD:
13228                         return OP_X86_ADD_REG_MEMBASE;
13229                 case OP_ISUB:
13230                         return OP_X86_SUB_REG_MEMBASE;
13231                 case OP_IAND:
13232                         return OP_X86_AND_REG_MEMBASE;
13233                 case OP_IOR:
13234                         return OP_X86_OR_REG_MEMBASE;
13235                 case OP_IXOR:
13236                         return OP_X86_XOR_REG_MEMBASE;
13237                 }
13238         } else if ((load_opcode == OP_LOADI8_MEMBASE) || (load_opcode == OP_LOAD_MEMBASE && !cfg->backend->ilp32)) {
13239                 switch (opcode) {
13240                 case OP_COMPARE:
13241                 case OP_LCOMPARE:
13242                         return OP_AMD64_COMPARE_REG_MEMBASE;
13243                 case OP_LADD:
13244                         return OP_AMD64_ADD_REG_MEMBASE;
13245                 case OP_LSUB:
13246                         return OP_AMD64_SUB_REG_MEMBASE;
13247                 case OP_LAND:
13248                         return OP_AMD64_AND_REG_MEMBASE;
13249                 case OP_LOR:
13250                         return OP_AMD64_OR_REG_MEMBASE;
13251                 case OP_LXOR:
13252                         return OP_AMD64_XOR_REG_MEMBASE;
13253                 }
13254         }
13255 #endif
13256
13257         return -1;
13258 }
13259
13260 int
13261 mono_op_to_op_imm_noemul (int opcode)
13262 {
13263         switch (opcode) {
13264 #if SIZEOF_REGISTER == 4 && !defined(MONO_ARCH_NO_EMULATE_LONG_SHIFT_OPS)
13265         case OP_LSHR:
13266         case OP_LSHL:
13267         case OP_LSHR_UN:
13268                 return -1;
13269 #endif
13270 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_EMULATE_DIV)
13271         case OP_IDIV:
13272         case OP_IDIV_UN:
13273         case OP_IREM:
13274         case OP_IREM_UN:
13275                 return -1;
13276 #endif
13277 #if defined(MONO_ARCH_EMULATE_MUL_DIV)
13278         case OP_IMUL:
13279                 return -1;
13280 #endif
13281         default:
13282                 return mono_op_to_op_imm (opcode);
13283         }
13284 }
13285
13286 /**
13287  * mono_handle_global_vregs:
13288  *
13289  *   Make vregs used in more than one bblock 'global', i.e. allocate a variable
13290  * for them.
13291  */
13292 void
13293 mono_handle_global_vregs (MonoCompile *cfg)
13294 {
13295         gint32 *vreg_to_bb;
13296         MonoBasicBlock *bb;
13297         int i, pos;
13298
13299         vreg_to_bb = (gint32 *)mono_mempool_alloc0 (cfg->mempool, sizeof (gint32*) * cfg->next_vreg + 1);
13300
13301 #ifdef MONO_ARCH_SIMD_INTRINSICS
13302         if (cfg->uses_simd_intrinsics)
13303                 mono_simd_simplify_indirection (cfg);
13304 #endif
13305
13306         /* Find local vregs used in more than one bb */
13307         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
13308                 MonoInst *ins = bb->code;       
13309                 int block_num = bb->block_num;
13310
13311                 if (cfg->verbose_level > 2)
13312                         printf ("\nHANDLE-GLOBAL-VREGS BLOCK %d:\n", bb->block_num);
13313
13314                 cfg->cbb = bb;
13315                 for (; ins; ins = ins->next) {
13316                         const char *spec = INS_INFO (ins->opcode);
13317                         int regtype = 0, regindex;
13318                         gint32 prev_bb;
13319
13320                         if (G_UNLIKELY (cfg->verbose_level > 2))
13321                                 mono_print_ins (ins);
13322
13323                         g_assert (ins->opcode >= MONO_CEE_LAST);
13324
13325                         for (regindex = 0; regindex < 4; regindex ++) {
13326                                 int vreg = 0;
13327
13328                                 if (regindex == 0) {
13329                                         regtype = spec [MONO_INST_DEST];
13330                                         if (regtype == ' ')
13331                                                 continue;
13332                                         vreg = ins->dreg;
13333                                 } else if (regindex == 1) {
13334                                         regtype = spec [MONO_INST_SRC1];
13335                                         if (regtype == ' ')
13336                                                 continue;
13337                                         vreg = ins->sreg1;
13338                                 } else if (regindex == 2) {
13339                                         regtype = spec [MONO_INST_SRC2];
13340                                         if (regtype == ' ')
13341                                                 continue;
13342                                         vreg = ins->sreg2;
13343                                 } else if (regindex == 3) {
13344                                         regtype = spec [MONO_INST_SRC3];
13345                                         if (regtype == ' ')
13346                                                 continue;
13347                                         vreg = ins->sreg3;
13348                                 }
13349
13350 #if SIZEOF_REGISTER == 4
13351                                 /* In the LLVM case, the long opcodes are not decomposed */
13352                                 if (regtype == 'l' && !COMPILE_LLVM (cfg)) {
13353                                         /*
13354                                          * Since some instructions reference the original long vreg,
13355                                          * and some reference the two component vregs, it is quite hard
13356                                          * to determine when it needs to be global. So be conservative.
13357                                          */
13358                                         if (!get_vreg_to_inst (cfg, vreg)) {
13359                                                 mono_compile_create_var_for_vreg (cfg, &mono_defaults.int64_class->byval_arg, OP_LOCAL, vreg);
13360
13361                                                 if (cfg->verbose_level > 2)
13362                                                         printf ("LONG VREG R%d made global.\n", vreg);
13363                                         }
13364
13365                                         /*
13366                                          * Make the component vregs volatile since the optimizations can
13367                                          * get confused otherwise.
13368                                          */
13369                                         get_vreg_to_inst (cfg, MONO_LVREG_LS (vreg))->flags |= MONO_INST_VOLATILE;
13370                                         get_vreg_to_inst (cfg, MONO_LVREG_MS (vreg))->flags |= MONO_INST_VOLATILE;
13371                                 }
13372 #endif
13373
13374                                 g_assert (vreg != -1);
13375
13376                                 prev_bb = vreg_to_bb [vreg];
13377                                 if (prev_bb == 0) {
13378                                         /* 0 is a valid block num */
13379                                         vreg_to_bb [vreg] = block_num + 1;
13380                                 } else if ((prev_bb != block_num + 1) && (prev_bb != -1)) {
13381                                         if (((regtype == 'i' && (vreg < MONO_MAX_IREGS))) || (regtype == 'f' && (vreg < MONO_MAX_FREGS)))
13382                                                 continue;
13383
13384                                         if (!get_vreg_to_inst (cfg, vreg)) {
13385                                                 if (G_UNLIKELY (cfg->verbose_level > 2))
13386                                                         printf ("VREG R%d used in BB%d and BB%d made global.\n", vreg, vreg_to_bb [vreg], block_num);
13387
13388                                                 switch (regtype) {
13389                                                 case 'i':
13390                                                         if (vreg_is_ref (cfg, vreg))
13391                                                                 mono_compile_create_var_for_vreg (cfg, &mono_defaults.object_class->byval_arg, OP_LOCAL, vreg);
13392                                                         else
13393                                                                 mono_compile_create_var_for_vreg (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL, vreg);
13394                                                         break;
13395                                                 case 'l':
13396                                                         mono_compile_create_var_for_vreg (cfg, &mono_defaults.int64_class->byval_arg, OP_LOCAL, vreg);
13397                                                         break;
13398                                                 case 'f':
13399                                                         mono_compile_create_var_for_vreg (cfg, &mono_defaults.double_class->byval_arg, OP_LOCAL, vreg);
13400                                                         break;
13401                                                 case 'v':
13402                                                 case 'x':
13403                                                         mono_compile_create_var_for_vreg (cfg, &ins->klass->byval_arg, OP_LOCAL, vreg);
13404                                                         break;
13405                                                 default:
13406                                                         g_assert_not_reached ();
13407                                                 }
13408                                         }
13409
13410                                         /* Flag as having been used in more than one bb */
13411                                         vreg_to_bb [vreg] = -1;
13412                                 }
13413                         }
13414                 }
13415         }
13416
13417         /* If a variable is used in only one bblock, convert it into a local vreg */
13418         for (i = 0; i < cfg->num_varinfo; i++) {
13419                 MonoInst *var = cfg->varinfo [i];
13420                 MonoMethodVar *vmv = MONO_VARINFO (cfg, i);
13421
13422                 switch (var->type) {
13423                 case STACK_I4:
13424                 case STACK_OBJ:
13425                 case STACK_PTR:
13426                 case STACK_MP:
13427                 case STACK_VTYPE:
13428 #if SIZEOF_REGISTER == 8
13429                 case STACK_I8:
13430 #endif
13431 #if !defined(TARGET_X86)
13432                 /* Enabling this screws up the fp stack on x86 */
13433                 case STACK_R8:
13434 #endif
13435                         if (mono_arch_is_soft_float ())
13436                                 break;
13437
13438                         /*
13439                         if (var->type == STACK_VTYPE && cfg->gsharedvt && mini_is_gsharedvt_variable_type (var->inst_vtype))
13440                                 break;
13441                         */
13442
13443                         /* Arguments are implicitly global */
13444                         /* Putting R4 vars into registers doesn't work currently */
13445                         /* The gsharedvt vars are implicitly referenced by ldaddr opcodes, but those opcodes are only generated later */
13446                         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) {
13447                                 /* 
13448                                  * Make that the variable's liveness interval doesn't contain a call, since
13449                                  * that would cause the lvreg to be spilled, making the whole optimization
13450                                  * useless.
13451                                  */
13452                                 /* This is too slow for JIT compilation */
13453 #if 0
13454                                 if (cfg->compile_aot && vreg_to_bb [var->dreg]) {
13455                                         MonoInst *ins;
13456                                         int def_index, call_index, ins_index;
13457                                         gboolean spilled = FALSE;
13458
13459                                         def_index = -1;
13460                                         call_index = -1;
13461                                         ins_index = 0;
13462                                         for (ins = vreg_to_bb [var->dreg]->code; ins; ins = ins->next) {
13463                                                 const char *spec = INS_INFO (ins->opcode);
13464
13465                                                 if ((spec [MONO_INST_DEST] != ' ') && (ins->dreg == var->dreg))
13466                                                         def_index = ins_index;
13467
13468                                                 if (((spec [MONO_INST_SRC1] != ' ') && (ins->sreg1 == var->dreg)) ||
13469                                                         ((spec [MONO_INST_SRC1] != ' ') && (ins->sreg1 == var->dreg))) {
13470                                                         if (call_index > def_index) {
13471                                                                 spilled = TRUE;
13472                                                                 break;
13473                                                         }
13474                                                 }
13475
13476                                                 if (MONO_IS_CALL (ins))
13477                                                         call_index = ins_index;
13478
13479                                                 ins_index ++;
13480                                         }
13481
13482                                         if (spilled)
13483                                                 break;
13484                                 }
13485 #endif
13486
13487                                 if (G_UNLIKELY (cfg->verbose_level > 2))
13488                                         printf ("CONVERTED R%d(%d) TO VREG.\n", var->dreg, vmv->idx);
13489                                 var->flags |= MONO_INST_IS_DEAD;
13490                                 cfg->vreg_to_inst [var->dreg] = NULL;
13491                         }
13492                         break;
13493                 }
13494         }
13495
13496         /* 
13497          * Compress the varinfo and vars tables so the liveness computation is faster and
13498          * takes up less space.
13499          */
13500         pos = 0;
13501         for (i = 0; i < cfg->num_varinfo; ++i) {
13502                 MonoInst *var = cfg->varinfo [i];
13503                 if (pos < i && cfg->locals_start == i)
13504                         cfg->locals_start = pos;
13505                 if (!(var->flags & MONO_INST_IS_DEAD)) {
13506                         if (pos < i) {
13507                                 cfg->varinfo [pos] = cfg->varinfo [i];
13508                                 cfg->varinfo [pos]->inst_c0 = pos;
13509                                 memcpy (&cfg->vars [pos], &cfg->vars [i], sizeof (MonoMethodVar));
13510                                 cfg->vars [pos].idx = pos;
13511 #if SIZEOF_REGISTER == 4
13512                                 if (cfg->varinfo [pos]->type == STACK_I8) {
13513                                         /* Modify the two component vars too */
13514                                         MonoInst *var1;
13515
13516                                         var1 = get_vreg_to_inst (cfg, MONO_LVREG_LS (cfg->varinfo [pos]->dreg));
13517                                         var1->inst_c0 = pos;
13518                                         var1 = get_vreg_to_inst (cfg, MONO_LVREG_MS (cfg->varinfo [pos]->dreg));
13519                                         var1->inst_c0 = pos;
13520                                 }
13521 #endif
13522                         }
13523                         pos ++;
13524                 }
13525         }
13526         cfg->num_varinfo = pos;
13527         if (cfg->locals_start > cfg->num_varinfo)
13528                 cfg->locals_start = cfg->num_varinfo;
13529 }
13530
13531 /*
13532  * mono_allocate_gsharedvt_vars:
13533  *
13534  *   Allocate variables with gsharedvt types to entries in the MonoGSharedVtMethodRuntimeInfo.entries array.
13535  * Initialize cfg->gsharedvt_vreg_to_idx with the mapping between vregs and indexes.
13536  */
13537 void
13538 mono_allocate_gsharedvt_vars (MonoCompile *cfg)
13539 {
13540         int i;
13541
13542         cfg->gsharedvt_vreg_to_idx = (int *)mono_mempool_alloc0 (cfg->mempool, sizeof (int) * cfg->next_vreg);
13543
13544         for (i = 0; i < cfg->num_varinfo; ++i) {
13545                 MonoInst *ins = cfg->varinfo [i];
13546                 int idx;
13547
13548                 if (mini_is_gsharedvt_variable_type (ins->inst_vtype)) {
13549                         if (i >= cfg->locals_start) {
13550                                 /* Local */
13551                                 idx = get_gsharedvt_info_slot (cfg, ins->inst_vtype, MONO_RGCTX_INFO_LOCAL_OFFSET);
13552                                 cfg->gsharedvt_vreg_to_idx [ins->dreg] = idx + 1;
13553                                 ins->opcode = OP_GSHAREDVT_LOCAL;
13554                                 ins->inst_imm = idx;
13555                         } else {
13556                                 /* Arg */
13557                                 cfg->gsharedvt_vreg_to_idx [ins->dreg] = -1;
13558                                 ins->opcode = OP_GSHAREDVT_ARG_REGOFFSET;
13559                         }
13560                 }
13561         }
13562 }
13563
13564 /**
13565  * mono_spill_global_vars:
13566  *
13567  *   Generate spill code for variables which are not allocated to registers, 
13568  * and replace vregs with their allocated hregs. *need_local_opts is set to TRUE if
13569  * code is generated which could be optimized by the local optimization passes.
13570  */
13571 void
13572 mono_spill_global_vars (MonoCompile *cfg, gboolean *need_local_opts)
13573 {
13574         MonoBasicBlock *bb;
13575         char spec2 [16];
13576         int orig_next_vreg;
13577         guint32 *vreg_to_lvreg;
13578         guint32 *lvregs;
13579         guint32 i, lvregs_len, lvregs_size;
13580         gboolean dest_has_lvreg = FALSE;
13581         MonoStackType stacktypes [128];
13582         MonoInst **live_range_start, **live_range_end;
13583         MonoBasicBlock **live_range_start_bb, **live_range_end_bb;
13584
13585         *need_local_opts = FALSE;
13586
13587         memset (spec2, 0, sizeof (spec2));
13588
13589         /* FIXME: Move this function to mini.c */
13590         stacktypes ['i'] = STACK_PTR;
13591         stacktypes ['l'] = STACK_I8;
13592         stacktypes ['f'] = STACK_R8;
13593 #ifdef MONO_ARCH_SIMD_INTRINSICS
13594         stacktypes ['x'] = STACK_VTYPE;
13595 #endif
13596
13597 #if SIZEOF_REGISTER == 4
13598         /* Create MonoInsts for longs */
13599         for (i = 0; i < cfg->num_varinfo; i++) {
13600                 MonoInst *ins = cfg->varinfo [i];
13601
13602                 if ((ins->opcode != OP_REGVAR) && !(ins->flags & MONO_INST_IS_DEAD)) {
13603                         switch (ins->type) {
13604                         case STACK_R8:
13605                         case STACK_I8: {
13606                                 MonoInst *tree;
13607
13608                                 if (ins->type == STACK_R8 && !COMPILE_SOFT_FLOAT (cfg))
13609                                         break;
13610
13611                                 g_assert (ins->opcode == OP_REGOFFSET);
13612
13613                                 tree = get_vreg_to_inst (cfg, MONO_LVREG_LS (ins->dreg));
13614                                 g_assert (tree);
13615                                 tree->opcode = OP_REGOFFSET;
13616                                 tree->inst_basereg = ins->inst_basereg;
13617                                 tree->inst_offset = ins->inst_offset + MINI_LS_WORD_OFFSET;
13618
13619                                 tree = get_vreg_to_inst (cfg, MONO_LVREG_MS (ins->dreg));
13620                                 g_assert (tree);
13621                                 tree->opcode = OP_REGOFFSET;
13622                                 tree->inst_basereg = ins->inst_basereg;
13623                                 tree->inst_offset = ins->inst_offset + MINI_MS_WORD_OFFSET;
13624                                 break;
13625                         }
13626                         default:
13627                                 break;
13628                         }
13629                 }
13630         }
13631 #endif
13632
13633         if (cfg->compute_gc_maps) {
13634                 /* registers need liveness info even for !non refs */
13635                 for (i = 0; i < cfg->num_varinfo; i++) {
13636                         MonoInst *ins = cfg->varinfo [i];
13637
13638                         if (ins->opcode == OP_REGVAR)
13639                                 ins->flags |= MONO_INST_GC_TRACK;
13640                 }
13641         }
13642                 
13643         /* FIXME: widening and truncation */
13644
13645         /*
13646          * As an optimization, when a variable allocated to the stack is first loaded into 
13647          * an lvreg, we will remember the lvreg and use it the next time instead of loading
13648          * the variable again.
13649          */
13650         orig_next_vreg = cfg->next_vreg;
13651         vreg_to_lvreg = (guint32 *)mono_mempool_alloc0 (cfg->mempool, sizeof (guint32) * cfg->next_vreg);
13652         lvregs_size = 1024;
13653         lvregs = (guint32 *)mono_mempool_alloc (cfg->mempool, sizeof (guint32) * lvregs_size);
13654         lvregs_len = 0;
13655
13656         /* 
13657          * These arrays contain the first and last instructions accessing a given
13658          * variable.
13659          * Since we emit bblocks in the same order we process them here, and we
13660          * don't split live ranges, these will precisely describe the live range of
13661          * the variable, i.e. the instruction range where a valid value can be found
13662          * in the variables location.
13663          * The live range is computed using the liveness info computed by the liveness pass.
13664          * We can't use vmv->range, since that is an abstract live range, and we need
13665          * one which is instruction precise.
13666          * FIXME: Variables used in out-of-line bblocks have a hole in their live range.
13667          */
13668         /* FIXME: Only do this if debugging info is requested */
13669         live_range_start = g_new0 (MonoInst*, cfg->next_vreg);
13670         live_range_end = g_new0 (MonoInst*, cfg->next_vreg);
13671         live_range_start_bb = g_new (MonoBasicBlock*, cfg->next_vreg);
13672         live_range_end_bb = g_new (MonoBasicBlock*, cfg->next_vreg);
13673         
13674         /* Add spill loads/stores */
13675         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
13676                 MonoInst *ins;
13677
13678                 if (cfg->verbose_level > 2)
13679                         printf ("\nSPILL BLOCK %d:\n", bb->block_num);
13680
13681                 /* Clear vreg_to_lvreg array */
13682                 for (i = 0; i < lvregs_len; i++)
13683                         vreg_to_lvreg [lvregs [i]] = 0;
13684                 lvregs_len = 0;
13685
13686                 cfg->cbb = bb;
13687                 MONO_BB_FOR_EACH_INS (bb, ins) {
13688                         const char *spec = INS_INFO (ins->opcode);
13689                         int regtype, srcindex, sreg, tmp_reg, prev_dreg, num_sregs;
13690                         gboolean store, no_lvreg;
13691                         int sregs [MONO_MAX_SRC_REGS];
13692
13693                         if (G_UNLIKELY (cfg->verbose_level > 2))
13694                                 mono_print_ins (ins);
13695
13696                         if (ins->opcode == OP_NOP)
13697                                 continue;
13698
13699                         /* 
13700                          * We handle LDADDR here as well, since it can only be decomposed
13701                          * when variable addresses are known.
13702                          */
13703                         if (ins->opcode == OP_LDADDR) {
13704                                 MonoInst *var = (MonoInst *)ins->inst_p0;
13705
13706                                 if (var->opcode == OP_VTARG_ADDR) {
13707                                         /* Happens on SPARC/S390 where vtypes are passed by reference */
13708                                         MonoInst *vtaddr = var->inst_left;
13709                                         if (vtaddr->opcode == OP_REGVAR) {
13710                                                 ins->opcode = OP_MOVE;
13711                                                 ins->sreg1 = vtaddr->dreg;
13712                                         }
13713                                         else if (var->inst_left->opcode == OP_REGOFFSET) {
13714                                                 ins->opcode = OP_LOAD_MEMBASE;
13715                                                 ins->inst_basereg = vtaddr->inst_basereg;
13716                                                 ins->inst_offset = vtaddr->inst_offset;
13717                                         } else
13718                                                 NOT_IMPLEMENTED;
13719                                 } else if (cfg->gsharedvt && cfg->gsharedvt_vreg_to_idx [var->dreg] < 0) {
13720                                         /* gsharedvt arg passed by ref */
13721                                         g_assert (var->opcode == OP_GSHAREDVT_ARG_REGOFFSET);
13722
13723                                         ins->opcode = OP_LOAD_MEMBASE;
13724                                         ins->inst_basereg = var->inst_basereg;
13725                                         ins->inst_offset = var->inst_offset;
13726                                 } else if (cfg->gsharedvt && cfg->gsharedvt_vreg_to_idx [var->dreg]) {
13727                                         MonoInst *load, *load2, *load3;
13728                                         int idx = cfg->gsharedvt_vreg_to_idx [var->dreg] - 1;
13729                                         int reg1, reg2, reg3;
13730                                         MonoInst *info_var = cfg->gsharedvt_info_var;
13731                                         MonoInst *locals_var = cfg->gsharedvt_locals_var;
13732
13733                                         /*
13734                                          * gsharedvt local.
13735                                          * Compute the address of the local as gsharedvt_locals_var + gsharedvt_info_var->locals_offsets [idx].
13736                                          */
13737
13738                                         g_assert (var->opcode == OP_GSHAREDVT_LOCAL);
13739
13740                                         g_assert (info_var);
13741                                         g_assert (locals_var);
13742
13743                                         /* Mark the instruction used to compute the locals var as used */
13744                                         cfg->gsharedvt_locals_var_ins = NULL;
13745
13746                                         /* Load the offset */
13747                                         if (info_var->opcode == OP_REGOFFSET) {
13748                                                 reg1 = alloc_ireg (cfg);
13749                                                 NEW_LOAD_MEMBASE (cfg, load, OP_LOAD_MEMBASE, reg1, info_var->inst_basereg, info_var->inst_offset);
13750                                         } else if (info_var->opcode == OP_REGVAR) {
13751                                                 load = NULL;
13752                                                 reg1 = info_var->dreg;
13753                                         } else {
13754                                                 g_assert_not_reached ();
13755                                         }
13756                                         reg2 = alloc_ireg (cfg);
13757                                         NEW_LOAD_MEMBASE (cfg, load2, OP_LOADI4_MEMBASE, reg2, reg1, MONO_STRUCT_OFFSET (MonoGSharedVtMethodRuntimeInfo, entries) + (idx * sizeof (gpointer)));
13758                                         /* Load the locals area address */
13759                                         reg3 = alloc_ireg (cfg);
13760                                         if (locals_var->opcode == OP_REGOFFSET) {
13761                                                 NEW_LOAD_MEMBASE (cfg, load3, OP_LOAD_MEMBASE, reg3, locals_var->inst_basereg, locals_var->inst_offset);
13762                                         } else if (locals_var->opcode == OP_REGVAR) {
13763                                                 NEW_UNALU (cfg, load3, OP_MOVE, reg3, locals_var->dreg);
13764                                         } else {
13765                                                 g_assert_not_reached ();
13766                                         }
13767                                         /* Compute the address */
13768                                         ins->opcode = OP_PADD;
13769                                         ins->sreg1 = reg3;
13770                                         ins->sreg2 = reg2;
13771
13772                                         mono_bblock_insert_before_ins (bb, ins, load3);
13773                                         mono_bblock_insert_before_ins (bb, load3, load2);
13774                                         if (load)
13775                                                 mono_bblock_insert_before_ins (bb, load2, load);
13776                                 } else {
13777                                         g_assert (var->opcode == OP_REGOFFSET);
13778
13779                                         ins->opcode = OP_ADD_IMM;
13780                                         ins->sreg1 = var->inst_basereg;
13781                                         ins->inst_imm = var->inst_offset;
13782                                 }
13783
13784                                 *need_local_opts = TRUE;
13785                                 spec = INS_INFO (ins->opcode);
13786                         }
13787
13788                         if (ins->opcode < MONO_CEE_LAST) {
13789                                 mono_print_ins (ins);
13790                                 g_assert_not_reached ();
13791                         }
13792
13793                         /*
13794                          * Store opcodes have destbasereg in the dreg, but in reality, it is an
13795                          * src register.
13796                          * FIXME:
13797                          */
13798                         if (MONO_IS_STORE_MEMBASE (ins)) {
13799                                 tmp_reg = ins->dreg;
13800                                 ins->dreg = ins->sreg2;
13801                                 ins->sreg2 = tmp_reg;
13802                                 store = TRUE;
13803
13804                                 spec2 [MONO_INST_DEST] = ' ';
13805                                 spec2 [MONO_INST_SRC1] = spec [MONO_INST_SRC1];
13806                                 spec2 [MONO_INST_SRC2] = spec [MONO_INST_DEST];
13807                                 spec2 [MONO_INST_SRC3] = ' ';
13808                                 spec = spec2;
13809                         } else if (MONO_IS_STORE_MEMINDEX (ins))
13810                                 g_assert_not_reached ();
13811                         else
13812                                 store = FALSE;
13813                         no_lvreg = FALSE;
13814
13815                         if (G_UNLIKELY (cfg->verbose_level > 2)) {
13816                                 printf ("\t %.3s %d", spec, ins->dreg);
13817                                 num_sregs = mono_inst_get_src_registers (ins, sregs);
13818                                 for (srcindex = 0; srcindex < num_sregs; ++srcindex)
13819                                         printf (" %d", sregs [srcindex]);
13820                                 printf ("\n");
13821                         }
13822
13823                         /***************/
13824                         /*    DREG     */
13825                         /***************/
13826                         regtype = spec [MONO_INST_DEST];
13827                         g_assert (((ins->dreg == -1) && (regtype == ' ')) || ((ins->dreg != -1) && (regtype != ' ')));
13828                         prev_dreg = -1;
13829
13830                         if ((ins->dreg != -1) && get_vreg_to_inst (cfg, ins->dreg)) {
13831                                 MonoInst *var = get_vreg_to_inst (cfg, ins->dreg);
13832                                 MonoInst *store_ins;
13833                                 int store_opcode;
13834                                 MonoInst *def_ins = ins;
13835                                 int dreg = ins->dreg; /* The original vreg */
13836
13837                                 store_opcode = mono_type_to_store_membase (cfg, var->inst_vtype);
13838
13839                                 if (var->opcode == OP_REGVAR) {
13840                                         ins->dreg = var->dreg;
13841                                 } 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)) {
13842                                         /* 
13843                                          * Instead of emitting a load+store, use a _membase opcode.
13844                                          */
13845                                         g_assert (var->opcode == OP_REGOFFSET);
13846                                         if (ins->opcode == OP_MOVE) {
13847                                                 NULLIFY_INS (ins);
13848                                                 def_ins = NULL;
13849                                         } else {
13850                                                 ins->opcode = op_to_op_dest_membase (store_opcode, ins->opcode);
13851                                                 ins->inst_basereg = var->inst_basereg;
13852                                                 ins->inst_offset = var->inst_offset;
13853                                                 ins->dreg = -1;
13854                                         }
13855                                         spec = INS_INFO (ins->opcode);
13856                                 } else {
13857                                         guint32 lvreg;
13858
13859                                         g_assert (var->opcode == OP_REGOFFSET);
13860
13861                                         prev_dreg = ins->dreg;
13862
13863                                         /* Invalidate any previous lvreg for this vreg */
13864                                         vreg_to_lvreg [ins->dreg] = 0;
13865
13866                                         lvreg = 0;
13867
13868                                         if (COMPILE_SOFT_FLOAT (cfg) && store_opcode == OP_STORER8_MEMBASE_REG) {
13869                                                 regtype = 'l';
13870                                                 store_opcode = OP_STOREI8_MEMBASE_REG;
13871                                         }
13872
13873                                         ins->dreg = alloc_dreg (cfg, stacktypes [regtype]);
13874
13875 #if SIZEOF_REGISTER != 8
13876                                         if (regtype == 'l') {
13877                                                 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));
13878                                                 mono_bblock_insert_after_ins (bb, ins, store_ins);
13879                                                 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));
13880                                                 mono_bblock_insert_after_ins (bb, ins, store_ins);
13881                                                 def_ins = store_ins;
13882                                         }
13883                                         else
13884 #endif
13885                                         {
13886                                                 g_assert (store_opcode != OP_STOREV_MEMBASE);
13887
13888                                                 /* Try to fuse the store into the instruction itself */
13889                                                 /* FIXME: Add more instructions */
13890                                                 if (!lvreg && ((ins->opcode == OP_ICONST) || ((ins->opcode == OP_I8CONST) && (ins->inst_c0 == 0)))) {
13891                                                         ins->opcode = store_membase_reg_to_store_membase_imm (store_opcode);
13892                                                         ins->inst_imm = ins->inst_c0;
13893                                                         ins->inst_destbasereg = var->inst_basereg;
13894                                                         ins->inst_offset = var->inst_offset;
13895                                                         spec = INS_INFO (ins->opcode);
13896                                                 } else if (!lvreg && ((ins->opcode == OP_MOVE) || (ins->opcode == OP_FMOVE) || (ins->opcode == OP_LMOVE) || (ins->opcode == OP_RMOVE))) {
13897                                                         ins->opcode = store_opcode;
13898                                                         ins->inst_destbasereg = var->inst_basereg;
13899                                                         ins->inst_offset = var->inst_offset;
13900
13901                                                         no_lvreg = TRUE;
13902
13903                                                         tmp_reg = ins->dreg;
13904                                                         ins->dreg = ins->sreg2;
13905                                                         ins->sreg2 = tmp_reg;
13906                                                         store = TRUE;
13907
13908                                                         spec2 [MONO_INST_DEST] = ' ';
13909                                                         spec2 [MONO_INST_SRC1] = spec [MONO_INST_SRC1];
13910                                                         spec2 [MONO_INST_SRC2] = spec [MONO_INST_DEST];
13911                                                         spec2 [MONO_INST_SRC3] = ' ';
13912                                                         spec = spec2;
13913                                                 } else if (!lvreg && (op_to_op_store_membase (store_opcode, ins->opcode) != -1)) {
13914                                                         // FIXME: The backends expect the base reg to be in inst_basereg
13915                                                         ins->opcode = op_to_op_store_membase (store_opcode, ins->opcode);
13916                                                         ins->dreg = -1;
13917                                                         ins->inst_basereg = var->inst_basereg;
13918                                                         ins->inst_offset = var->inst_offset;
13919                                                         spec = INS_INFO (ins->opcode);
13920                                                 } else {
13921                                                         /* printf ("INS: "); mono_print_ins (ins); */
13922                                                         /* Create a store instruction */
13923                                                         NEW_STORE_MEMBASE (cfg, store_ins, store_opcode, var->inst_basereg, var->inst_offset, ins->dreg);
13924
13925                                                         /* Insert it after the instruction */
13926                                                         mono_bblock_insert_after_ins (bb, ins, store_ins);
13927
13928                                                         def_ins = store_ins;
13929
13930                                                         /* 
13931                                                          * We can't assign ins->dreg to var->dreg here, since the
13932                                                          * sregs could use it. So set a flag, and do it after
13933                                                          * the sregs.
13934                                                          */
13935                                                         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)))
13936                                                                 dest_has_lvreg = TRUE;
13937                                                 }
13938                                         }
13939                                 }
13940
13941                                 if (def_ins && !live_range_start [dreg]) {
13942                                         live_range_start [dreg] = def_ins;
13943                                         live_range_start_bb [dreg] = bb;
13944                                 }
13945
13946                                 if (cfg->compute_gc_maps && def_ins && (var->flags & MONO_INST_GC_TRACK)) {
13947                                         MonoInst *tmp;
13948
13949                                         MONO_INST_NEW (cfg, tmp, OP_GC_LIVENESS_DEF);
13950                                         tmp->inst_c1 = dreg;
13951                                         mono_bblock_insert_after_ins (bb, def_ins, tmp);
13952                                 }
13953                         }
13954
13955                         /************/
13956                         /*  SREGS   */
13957                         /************/
13958                         num_sregs = mono_inst_get_src_registers (ins, sregs);
13959                         for (srcindex = 0; srcindex < 3; ++srcindex) {
13960                                 regtype = spec [MONO_INST_SRC1 + srcindex];
13961                                 sreg = sregs [srcindex];
13962
13963                                 g_assert (((sreg == -1) && (regtype == ' ')) || ((sreg != -1) && (regtype != ' ')));
13964                                 if ((sreg != -1) && get_vreg_to_inst (cfg, sreg)) {
13965                                         MonoInst *var = get_vreg_to_inst (cfg, sreg);
13966                                         MonoInst *use_ins = ins;
13967                                         MonoInst *load_ins;
13968                                         guint32 load_opcode;
13969
13970                                         if (var->opcode == OP_REGVAR) {
13971                                                 sregs [srcindex] = var->dreg;
13972                                                 //mono_inst_set_src_registers (ins, sregs);
13973                                                 live_range_end [sreg] = use_ins;
13974                                                 live_range_end_bb [sreg] = bb;
13975
13976                                                 if (cfg->compute_gc_maps && var->dreg < orig_next_vreg && (var->flags & MONO_INST_GC_TRACK)) {
13977                                                         MonoInst *tmp;
13978
13979                                                         MONO_INST_NEW (cfg, tmp, OP_GC_LIVENESS_USE);
13980                                                         /* var->dreg is a hreg */
13981                                                         tmp->inst_c1 = sreg;
13982                                                         mono_bblock_insert_after_ins (bb, ins, tmp);
13983                                                 }
13984
13985                                                 continue;
13986                                         }
13987
13988                                         g_assert (var->opcode == OP_REGOFFSET);
13989                                                 
13990                                         load_opcode = mono_type_to_load_membase (cfg, var->inst_vtype);
13991
13992                                         g_assert (load_opcode != OP_LOADV_MEMBASE);
13993
13994                                         if (vreg_to_lvreg [sreg]) {
13995                                                 g_assert (vreg_to_lvreg [sreg] != -1);
13996
13997                                                 /* The variable is already loaded to an lvreg */
13998                                                 if (G_UNLIKELY (cfg->verbose_level > 2))
13999                                                         printf ("\t\tUse lvreg R%d for R%d.\n", vreg_to_lvreg [sreg], sreg);
14000                                                 sregs [srcindex] = vreg_to_lvreg [sreg];
14001                                                 //mono_inst_set_src_registers (ins, sregs);
14002                                                 continue;
14003                                         }
14004
14005                                         /* Try to fuse the load into the instruction */
14006                                         if ((srcindex == 0) && (op_to_op_src1_membase (cfg, load_opcode, ins->opcode) != -1)) {
14007                                                 ins->opcode = op_to_op_src1_membase (cfg, load_opcode, ins->opcode);
14008                                                 sregs [0] = var->inst_basereg;
14009                                                 //mono_inst_set_src_registers (ins, sregs);
14010                                                 ins->inst_offset = var->inst_offset;
14011                                         } else if ((srcindex == 1) && (op_to_op_src2_membase (cfg, load_opcode, ins->opcode) != -1)) {
14012                                                 ins->opcode = op_to_op_src2_membase (cfg, load_opcode, ins->opcode);
14013                                                 sregs [1] = var->inst_basereg;
14014                                                 //mono_inst_set_src_registers (ins, sregs);
14015                                                 ins->inst_offset = var->inst_offset;
14016                                         } else {
14017                                                 if (MONO_IS_REAL_MOVE (ins)) {
14018                                                         ins->opcode = OP_NOP;
14019                                                         sreg = ins->dreg;
14020                                                 } else {
14021                                                         //printf ("%d ", srcindex); mono_print_ins (ins);
14022
14023                                                         sreg = alloc_dreg (cfg, stacktypes [regtype]);
14024
14025                                                         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) {
14026                                                                 if (var->dreg == prev_dreg) {
14027                                                                         /*
14028                                                                          * sreg refers to the value loaded by the load
14029                                                                          * emitted below, but we need to use ins->dreg
14030                                                                          * since it refers to the store emitted earlier.
14031                                                                          */
14032                                                                         sreg = ins->dreg;
14033                                                                 }
14034                                                                 g_assert (sreg != -1);
14035                                                                 vreg_to_lvreg [var->dreg] = sreg;
14036                                                                 if (lvregs_len >= lvregs_size) {
14037                                                                         guint32 *new_lvregs = mono_mempool_alloc0 (cfg->mempool, sizeof (guint32) * lvregs_size * 2);
14038                                                                         memcpy (new_lvregs, lvregs, sizeof (guint32) * lvregs_size);
14039                                                                         lvregs = new_lvregs;
14040                                                                         lvregs_size *= 2;
14041                                                                 }
14042                                                                 lvregs [lvregs_len ++] = var->dreg;
14043                                                         }
14044                                                 }
14045
14046                                                 sregs [srcindex] = sreg;
14047                                                 //mono_inst_set_src_registers (ins, sregs);
14048
14049 #if SIZEOF_REGISTER != 8
14050                                                 if (regtype == 'l') {
14051                                                         NEW_LOAD_MEMBASE (cfg, load_ins, OP_LOADI4_MEMBASE, MONO_LVREG_MS (sreg), var->inst_basereg, var->inst_offset + MINI_MS_WORD_OFFSET);
14052                                                         mono_bblock_insert_before_ins (bb, ins, load_ins);
14053                                                         NEW_LOAD_MEMBASE (cfg, load_ins, OP_LOADI4_MEMBASE, MONO_LVREG_LS (sreg), var->inst_basereg, var->inst_offset + MINI_LS_WORD_OFFSET);
14054                                                         mono_bblock_insert_before_ins (bb, ins, load_ins);
14055                                                         use_ins = load_ins;
14056                                                 }
14057                                                 else
14058 #endif
14059                                                 {
14060 #if SIZEOF_REGISTER == 4
14061                                                         g_assert (load_opcode != OP_LOADI8_MEMBASE);
14062 #endif
14063                                                         NEW_LOAD_MEMBASE (cfg, load_ins, load_opcode, sreg, var->inst_basereg, var->inst_offset);
14064                                                         mono_bblock_insert_before_ins (bb, ins, load_ins);
14065                                                         use_ins = load_ins;
14066                                                 }
14067                                         }
14068
14069                                         if (var->dreg < orig_next_vreg) {
14070                                                 live_range_end [var->dreg] = use_ins;
14071                                                 live_range_end_bb [var->dreg] = bb;
14072                                         }
14073
14074                                         if (cfg->compute_gc_maps && var->dreg < orig_next_vreg && (var->flags & MONO_INST_GC_TRACK)) {
14075                                                 MonoInst *tmp;
14076
14077                                                 MONO_INST_NEW (cfg, tmp, OP_GC_LIVENESS_USE);
14078                                                 tmp->inst_c1 = var->dreg;
14079                                                 mono_bblock_insert_after_ins (bb, ins, tmp);
14080                                         }
14081                                 }
14082                         }
14083                         mono_inst_set_src_registers (ins, sregs);
14084
14085                         if (dest_has_lvreg) {
14086                                 g_assert (ins->dreg != -1);
14087                                 vreg_to_lvreg [prev_dreg] = ins->dreg;
14088                                 if (lvregs_len >= lvregs_size) {
14089                                         guint32 *new_lvregs = mono_mempool_alloc0 (cfg->mempool, sizeof (guint32) * lvregs_size * 2);
14090                                         memcpy (new_lvregs, lvregs, sizeof (guint32) * lvregs_size);
14091                                         lvregs = new_lvregs;
14092                                         lvregs_size *= 2;
14093                                 }
14094                                 lvregs [lvregs_len ++] = prev_dreg;
14095                                 dest_has_lvreg = FALSE;
14096                         }
14097
14098                         if (store) {
14099                                 tmp_reg = ins->dreg;
14100                                 ins->dreg = ins->sreg2;
14101                                 ins->sreg2 = tmp_reg;
14102                         }
14103
14104                         if (MONO_IS_CALL (ins)) {
14105                                 /* Clear vreg_to_lvreg array */
14106                                 for (i = 0; i < lvregs_len; i++)
14107                                         vreg_to_lvreg [lvregs [i]] = 0;
14108                                 lvregs_len = 0;
14109                         } else if (ins->opcode == OP_NOP) {
14110                                 ins->dreg = -1;
14111                                 MONO_INST_NULLIFY_SREGS (ins);
14112                         }
14113
14114                         if (cfg->verbose_level > 2)
14115                                 mono_print_ins_index (1, ins);
14116                 }
14117
14118                 /* Extend the live range based on the liveness info */
14119                 if (cfg->compute_precise_live_ranges && bb->live_out_set && bb->code) {
14120                         for (i = 0; i < cfg->num_varinfo; i ++) {
14121                                 MonoMethodVar *vi = MONO_VARINFO (cfg, i);
14122
14123                                 if (vreg_is_volatile (cfg, vi->vreg))
14124                                         /* The liveness info is incomplete */
14125                                         continue;
14126
14127                                 if (mono_bitset_test_fast (bb->live_in_set, i) && !live_range_start [vi->vreg]) {
14128                                         /* Live from at least the first ins of this bb */
14129                                         live_range_start [vi->vreg] = bb->code;
14130                                         live_range_start_bb [vi->vreg] = bb;
14131                                 }
14132
14133                                 if (mono_bitset_test_fast (bb->live_out_set, i)) {
14134                                         /* Live at least until the last ins of this bb */
14135                                         live_range_end [vi->vreg] = bb->last_ins;
14136                                         live_range_end_bb [vi->vreg] = bb;
14137                                 }
14138                         }
14139                 }
14140         }
14141         
14142         /*
14143          * Emit LIVERANGE_START/LIVERANGE_END opcodes, the backend will implement them
14144          * by storing the current native offset into MonoMethodVar->live_range_start/end.
14145          */
14146         if (cfg->backend->have_liverange_ops && cfg->compute_precise_live_ranges && cfg->comp_done & MONO_COMP_LIVENESS) {
14147                 for (i = 0; i < cfg->num_varinfo; ++i) {
14148                         int vreg = MONO_VARINFO (cfg, i)->vreg;
14149                         MonoInst *ins;
14150
14151                         if (live_range_start [vreg]) {
14152                                 MONO_INST_NEW (cfg, ins, OP_LIVERANGE_START);
14153                                 ins->inst_c0 = i;
14154                                 ins->inst_c1 = vreg;
14155                                 mono_bblock_insert_after_ins (live_range_start_bb [vreg], live_range_start [vreg], ins);
14156                         }
14157                         if (live_range_end [vreg]) {
14158                                 MONO_INST_NEW (cfg, ins, OP_LIVERANGE_END);
14159                                 ins->inst_c0 = i;
14160                                 ins->inst_c1 = vreg;
14161                                 if (live_range_end [vreg] == live_range_end_bb [vreg]->last_ins)
14162                                         mono_add_ins_to_end (live_range_end_bb [vreg], ins);
14163                                 else
14164                                         mono_bblock_insert_after_ins (live_range_end_bb [vreg], live_range_end [vreg], ins);
14165                         }
14166                 }
14167         }
14168
14169         if (cfg->gsharedvt_locals_var_ins) {
14170                 /* Nullify if unused */
14171                 cfg->gsharedvt_locals_var_ins->opcode = OP_PCONST;
14172                 cfg->gsharedvt_locals_var_ins->inst_imm = 0;
14173         }
14174
14175         g_free (live_range_start);
14176         g_free (live_range_end);
14177         g_free (live_range_start_bb);
14178         g_free (live_range_end_bb);
14179 }
14180
14181
14182 /**
14183  * FIXME:
14184  * - use 'iadd' instead of 'int_add'
14185  * - handling ovf opcodes: decompose in method_to_ir.
14186  * - unify iregs/fregs
14187  *   -> partly done, the missing parts are:
14188  *   - a more complete unification would involve unifying the hregs as well, so
14189  *     code wouldn't need if (fp) all over the place. but that would mean the hregs
14190  *     would no longer map to the machine hregs, so the code generators would need to
14191  *     be modified. Also, on ia64 for example, niregs + nfregs > 256 -> bitmasks
14192  *     wouldn't work any more. Duplicating the code in mono_local_regalloc () into
14193  *     fp/non-fp branches speeds it up by about 15%.
14194  * - use sext/zext opcodes instead of shifts
14195  * - add OP_ICALL
14196  * - get rid of TEMPLOADs if possible and use vregs instead
14197  * - clean up usage of OP_P/OP_ opcodes
14198  * - cleanup usage of DUMMY_USE
14199  * - cleanup the setting of ins->type for MonoInst's which are pushed on the 
14200  *   stack
14201  * - set the stack type and allocate a dreg in the EMIT_NEW macros
14202  * - get rid of all the <foo>2 stuff when the new JIT is ready.
14203  * - make sure handle_stack_args () is called before the branch is emitted
14204  * - when the new IR is done, get rid of all unused stuff
14205  * - COMPARE/BEQ as separate instructions or unify them ?
14206  *   - keeping them separate allows specialized compare instructions like
14207  *     compare_imm, compare_membase
14208  *   - most back ends unify fp compare+branch, fp compare+ceq
14209  * - integrate mono_save_args into inline_method
14210  * - get rid of the empty bblocks created by MONO_EMIT_NEW_BRACH_BLOCK2
14211  * - handle long shift opts on 32 bit platforms somehow: they require 
14212  *   3 sregs (2 for arg1 and 1 for arg2)
14213  * - make byref a 'normal' type.
14214  * - use vregs for bb->out_stacks if possible, handle_global_vreg will make them a
14215  *   variable if needed.
14216  * - do not start a new IL level bblock when cfg->cbb is changed by a function call
14217  *   like inline_method.
14218  * - remove inlining restrictions
14219  * - fix LNEG and enable cfold of INEG
14220  * - generalize x86 optimizations like ldelema as a peephole optimization
14221  * - add store_mem_imm for amd64
14222  * - optimize the loading of the interruption flag in the managed->native wrappers
14223  * - avoid special handling of OP_NOP in passes
14224  * - move code inserting instructions into one function/macro.
14225  * - try a coalescing phase after liveness analysis
14226  * - add float -> vreg conversion + local optimizations on !x86
14227  * - figure out how to handle decomposed branches during optimizations, ie.
14228  *   compare+branch, op_jump_table+op_br etc.
14229  * - promote RuntimeXHandles to vregs
14230  * - vtype cleanups:
14231  *   - add a NEW_VARLOADA_VREG macro
14232  * - the vtype optimizations are blocked by the LDADDR opcodes generated for 
14233  *   accessing vtype fields.
14234  * - get rid of I8CONST on 64 bit platforms
14235  * - dealing with the increase in code size due to branches created during opcode
14236  *   decomposition:
14237  *   - use extended basic blocks
14238  *     - all parts of the JIT
14239  *     - handle_global_vregs () && local regalloc
14240  *   - avoid introducing global vregs during decomposition, like 'vtable' in isinst
14241  * - sources of increase in code size:
14242  *   - vtypes
14243  *   - long compares
14244  *   - isinst and castclass
14245  *   - lvregs not allocated to global registers even if used multiple times
14246  * - call cctors outside the JIT, to make -v output more readable and JIT timings more
14247  *   meaningful.
14248  * - check for fp stack leakage in other opcodes too. (-> 'exceptions' optimization)
14249  * - add all micro optimizations from the old JIT
14250  * - put tree optimizations into the deadce pass
14251  * - decompose op_start_handler/op_endfilter/op_endfinally earlier using an arch
14252  *   specific function.
14253  * - unify the float comparison opcodes with the other comparison opcodes, i.e.
14254  *   fcompare + branchCC.
14255  * - create a helper function for allocating a stack slot, taking into account 
14256  *   MONO_CFG_HAS_SPILLUP.
14257  * - merge r68207.
14258  * - optimize mono_regstate2_alloc_int/float.
14259  * - fix the pessimistic handling of variables accessed in exception handler blocks.
14260  * - need to write a tree optimization pass, but the creation of trees is difficult, i.e.
14261  *   parts of the tree could be separated by other instructions, killing the tree
14262  *   arguments, or stores killing loads etc. Also, should we fold loads into other
14263  *   instructions if the result of the load is used multiple times ?
14264  * - make the REM_IMM optimization in mini-x86.c arch-independent.
14265  * - LAST MERGE: 108395.
14266  * - when returning vtypes in registers, generate IR and append it to the end of the
14267  *   last bb instead of doing it in the epilog.
14268  * - change the store opcodes so they use sreg1 instead of dreg to store the base register.
14269  */
14270
14271 /*
14272
14273 NOTES
14274 -----
14275
14276 - When to decompose opcodes:
14277   - earlier: this makes some optimizations hard to implement, since the low level IR
14278   no longer contains the neccessary information. But it is easier to do.
14279   - later: harder to implement, enables more optimizations.
14280 - Branches inside bblocks:
14281   - created when decomposing complex opcodes. 
14282     - branches to another bblock: harmless, but not tracked by the branch 
14283       optimizations, so need to branch to a label at the start of the bblock.
14284     - branches to inside the same bblock: very problematic, trips up the local
14285       reg allocator. Can be fixed by spitting the current bblock, but that is a
14286       complex operation, since some local vregs can become global vregs etc.
14287 - Local/global vregs:
14288   - local vregs: temporary vregs used inside one bblock. Assigned to hregs by the
14289     local register allocator.
14290   - global vregs: used in more than one bblock. Have an associated MonoMethodVar
14291     structure, created by mono_create_var (). Assigned to hregs or the stack by
14292     the global register allocator.
14293 - When to do optimizations like alu->alu_imm:
14294   - earlier -> saves work later on since the IR will be smaller/simpler
14295   - later -> can work on more instructions
14296 - Handling of valuetypes:
14297   - When a vtype is pushed on the stack, a new temporary is created, an 
14298     instruction computing its address (LDADDR) is emitted and pushed on
14299     the stack. Need to optimize cases when the vtype is used immediately as in
14300     argument passing, stloc etc.
14301 - Instead of the to_end stuff in the old JIT, simply call the function handling
14302   the values on the stack before emitting the last instruction of the bb.
14303 */
14304
14305 #endif /* !DISABLE_JIT */