Do not emit cld in the CopyB prologue. The ABI mandates that DF is cleared, so do...
[libfirm] / ir / be / bejavacoal.c
1 /*
2  * Copyright (C) 1995-2008 University of Karlsruhe.  All right reserved.
3  *
4  * This file is part of libFirm.
5  *
6  * This file may be distributed and/or modified under the terms of the
7  * GNU General Public License version 2 as published by the Free Software
8  * Foundation and appearing in the file LICENSE.GPL included in the
9  * packaging of this file.
10  *
11  * Licensees holding valid libFirm Professional Edition licenses may use
12  * this file in accordance with the libFirm Commercial License.
13  * Agreement provided with the Software.
14  *
15  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE.
18  */
19
20 /**
21  * @file
22  * @brief       Interface for external Java coalescer.
23  * @author      Sebastian Hack
24  * @version     $Id$
25  */
26 #ifdef HAVE_CONFIG_H
27 #include "config.h"
28 #endif
29
30 #include "lc_opts.h"
31 #include "lc_opts_enum.h"
32
33 #ifdef _WIN32
34 #include <windows.h>
35 #else
36 #include <dlfcn.h>
37 #endif
38
39 #include <signal.h>
40 #include <stdlib.h>
41 #include <assert.h>
42 #include <stdio.h>
43
44 #include "xmalloc.h"
45 #include "bejavacoal.h"
46 #include "irtools.h"
47 #include "bemodule.h"
48
49 #ifdef WITH_JVM
50
51 /* Path to the jar file. A little OS dependent convenience. */
52 #ifdef _WIN32
53 static char jar_file[512] = "y:\\user\\hack\\public\\coal.jar";
54 #else
55 static char jar_file[512] = "/ben/hack/public/coal.jar";
56 #endif
57
58 static char cls_name[256] = "coalescing/mst/safe/Algo";
59
60 /* Name of the JVM dll/so */
61 static char jvm_lib[512] = { 0 };
62
63 static const lc_opt_table_entry_t options[] = {
64         LC_OPT_ENT_STR      ("jvm",  "absolute path to jvm dll",                    jvm_lib, sizeof(jvm_lib)),
65         LC_OPT_ENT_STR      ("jar",  "jar file of the coalescer",                   jar_file, sizeof(jar_file)),
66         LC_OPT_ENT_STR      ("cls",  "name of the class providing the factory",     cls_name, sizeof(cls_name)),
67         LC_OPT_LAST
68 };
69
70 void be_init_javacoal(void)
71 {
72         lc_opt_entry_t *be_grp = lc_opt_get_grp(firm_opt_get_root(), "be");
73         lc_opt_entry_t *ra_grp = lc_opt_get_grp(be_grp, "ra");
74         lc_opt_entry_t *chordal_grp = lc_opt_get_grp(ra_grp, "chordal");
75         lc_opt_entry_t *jc_grp = lc_opt_get_grp(chordal_grp, "jc");
76         lc_opt_add_table(jc_grp, options);
77 }
78
79 BE_REGISTER_MODULE_CONSTRUCTOR(be_init_javacoal);
80
81 #include <jni.h>
82
83 typedef struct _jni_env_t {
84         JavaVM *jvm;
85         JNIEnv *jni;
86 } jni_env_t;
87
88 /*
89
90         Ugly code to retrieve the JVM dll/so file.
91
92 */
93
94 #ifdef _WIN32
95 /* Win32 version */
96 static void *find_jvm_symbol(const char *vmlibpath, const char *sym)
97 {
98         HINSTANCE hVM = LoadLibrary(vmlibpath);
99         return hVM ? GetProcAddress(hVM, sym) : NULL;
100 }
101
102 #define JRE_KEY "SOFTWARE\\JavaSoft\\Java Development Kit"
103
104 static char *locate_jvm_lib(char *path, size_t path_len)
105 {
106         char version[32];
107         char buf[256];
108         DWORD version_len = sizeof(version);
109         DWORD dwPathLen = path_len;
110         HKEY hKey;
111
112         RegOpenKeyEx(HKEY_LOCAL_MACHINE, JRE_KEY, 0, KEY_QUERY_VALUE, &hKey);
113         RegQueryValueEx(hKey, "CurrentVersion", NULL, NULL, (LPBYTE) version, &version_len);
114         RegCloseKey(hKey);
115
116         _snprintf(buf, sizeof(buf), JRE_KEY "\\%s", version);
117         RegOpenKeyEx(HKEY_LOCAL_MACHINE, buf, 0, KEY_QUERY_VALUE, &hKey);
118         RegQueryValueEx(hKey, "JavaHome", NULL, NULL, (LPBYTE) path, &dwPathLen);
119         RegCloseKey(hKey);
120
121         strncat(path, "\\jre\\bin\\server\\jvm.dll", path_len);
122         return path;
123 }
124
125 #else /* ! _WIN32 */
126 /* Unix version */
127 static void *find_jvm_symbol(const char *vmlibpath, const char *sym)
128 {
129         void *libVM = dlopen(vmlibpath, RTLD_LAZY);
130         return libVM ? dlsym(libVM, sym) : NULL;
131 }
132
133 static char *locate_jvm_lib(char *path, size_t n)
134 {
135         (void) path;
136         (void) n;
137         return NULL;
138 }
139 #endif /* _WIN32 */
140
141 static int start_vm(jni_env_t *env, int argc, char *argv[])
142 {
143         int i;
144         long ret;
145         JavaVMInitArgs args;
146         JavaVMOption *opts;
147
148         long (JNICALL * create_func)(JavaVM **, void **, void *) = find_jvm_symbol(jvm_lib, "JNI_CreateJavaVM");
149
150         if(!create_func) {
151                 fprintf(stderr, "could not find JVM creation function\n");
152                 exit(1);
153         }
154
155         memset(&args, 0, sizeof(args));
156         opts = XMALLOCN(JavaVMOption, argc);
157         for(i = 0; i < argc; ++i) {
158                 opts[i].optionString = argv[i];
159                 opts[i].extraInfo    = NULL;
160         }
161
162         args.version  = JNI_VERSION_1_4;
163         args.nOptions = argc;
164         args.options  = opts;
165         args.ignoreUnrecognized = JNI_FALSE;
166
167         ret = create_func(&env->jvm, (void **) &env->jni, &args);
168         free(opts);
169         if(ret != JNI_OK) {
170                 fprintf(stderr, "JNI_CreateJavaVM returned errrocode %ld\n" , ret);
171                 return 0;
172         }
173
174         return 1;
175 }
176
177 static void stop_vm(jni_env_t *env)
178 {
179         JavaVM *jvm = env->jvm;
180         (*jvm)->DetachCurrentThread(jvm);
181         (*jvm)->DestroyJavaVM(jvm);
182 }
183
184 static int jvm_inited = 0;
185 static jni_env_t env;
186 void (*old_int_handler)(int);
187 void (*old_abrt_handler)(int);
188
189 static void sig_jvm_destroy_at_exit(int signal)
190 {
191         if(jvm_inited)
192                 stop_vm(&env);
193
194         switch(signal) {
195         case SIGABRT:
196                 old_abrt_handler(signal);
197                 break;
198         case SIGINT:
199                 old_int_handler(signal);
200                 break;
201         default:;
202         }
203 }
204
205 static void jvm_destroy_at_exit(void)
206 {
207         sig_jvm_destroy_at_exit(0);
208 }
209
210 static jni_env_t *get_jvm(void)
211 {
212         char cp_param[512];
213         char *args[1];
214
215         if(!jvm_inited) {
216                 /* Find the dll */
217                 if(strlen(jvm_lib) == 0) {
218                         if(!locate_jvm_lib(jvm_lib, sizeof(jvm_lib))) {
219                                 fprintf(stderr, "could not find jvm library\n");
220                                 exit(1);
221                         }
222                 }
223
224                 snprintf(cp_param, sizeof(cp_param), "-Djava.class.path=%s", jar_file);
225                 args[0] = cp_param;
226                 if(!start_vm(&env, sizeof(args) / sizeof(args[0]), args)) {
227                         fprintf(stderr, "Couldn't initialize java VM\n");
228                         abort();
229                 }
230                 jvm_inited = 1;
231                 old_int_handler  = signal(SIGINT,  sig_jvm_destroy_at_exit);
232                 old_abrt_handler = signal(SIGABRT, sig_jvm_destroy_at_exit);
233                 atexit(jvm_destroy_at_exit);
234         }
235
236         return &env;
237 }
238
239
240 static void check(jni_env_t *env, const char *file, int line)
241 {
242         JNIEnv *jni = env->jni;
243         jboolean exc = (*jni)->ExceptionCheck(jni);
244         if(exc) {
245                 fprintf(stderr, "%s:%d: ", file, line);
246                 (*jni)->ExceptionDescribe(jni);
247                 (*jni)->ExceptionClear(jni);
248                 stop_vm(env);
249                 abort();
250         }
251 }
252
253 #define CHECK(env) check(env, __FILE__, __LINE__)
254
255 enum {
256         mth_add_int_edge,
257         mth_add_aff_edge,
258         mth_set_color,
259         //mth_set_debug,
260         mth_get_color,
261         mth_forbid_color,
262         mth_coalesce,
263         mth_dump,
264         mth_finish,
265         mth_last
266 };
267
268 struct _mth_info_t {
269         const char *name;
270         const char *sig;
271 };
272
273 static const struct _mth_info_t mthis[mth_last] = {
274         { "addIntEdge",  "(II)V"                   }, /* public void addIntEdge(int, int); */
275         { "addAffEdge",  "(III)V"                  }, /* public void addAffEdge(int, int, int); */
276         { "setColor",    "(II)V"                   }, /* public void setColor(int, int); */
277         //{ "setDebug",    "(ILjava/lang/String;)V"  }, /* public void setDebug(int, String); */
278         { "getColor",    "(I)I"                    }, /* public int getColor(int); */
279         { "forbidColor", "(II)V"                   }, /* public void forbidColor(int, int); */
280         { "coalesce",    "()V"                     }, /* public void coalesce(); */
281         { "dump",        "(Ljava/lang/String;)V"   }, /* public void dump(String); */
282         { "finish",      "()V"                     }  /* public void finish(); */
283 };
284
285 /* public static coalescing.Extern createExtern(java.lang.String, int, int, int); */
286 static const struct _mth_info_t mthi_factory = {
287         "createExtern", "(Ljava/lang/String;III)Lcoalescing/Extern;"
288 };
289
290 struct _be_java_coal_t {
291         jni_env_t *env;
292         jclass    cls;
293         jobject   obj;
294
295         jmethodID mth_ids[mth_last];
296 };
297
298 static void jc_call_void(be_java_coal_t *c, int mth_index, ...)
299 {
300         JNIEnv *jni   = c->env->jni;
301         jmethodID mid = c->mth_ids[mth_index];
302
303         va_list args;
304
305         va_start(args, mth_index);
306         (*jni)->CallVoidMethodV(jni, c->obj, mid, args);
307         CHECK(c->env);
308         va_end(args);
309 }
310
311 static int jc_call_int(be_java_coal_t *c, int mth_index, ...)
312 {
313         JNIEnv *jni   = c->env->jni;
314         jmethodID mid = c->mth_ids[mth_index];
315
316         int res;
317         va_list args;
318
319         va_start(args, mth_index);
320         res = (*jni)->CallIntMethodV(jni, c->obj, mid, args);
321         CHECK(c->env);
322         va_end(args);
323
324         return res;
325 }
326
327 be_java_coal_t *be_java_coal_init(const char *graph_name, int n_nodes, int n_regs, int dbg_level)
328 {
329         jni_env_t *env = get_jvm();
330         JNIEnv *jni = env->jni;
331         jmethodID fact;
332         jclass cls;
333         jstring str;
334         int i;
335
336         be_java_coal_t *c = XMALLOCZ(be_java_coal_t);
337         c->env = env;
338
339         /* Find the class we are are looking for. */
340         cls = (*jni)->FindClass(jni, cls_name);
341         CHECK(env);
342
343         /* Get the static factory method. */
344         fact = (*jni)->GetStaticMethodID(jni, cls, mthi_factory.name, mthi_factory.sig);
345         CHECK(env);
346
347         /* Call the factory. */
348         str = (*jni)->NewStringUTF(jni, graph_name);
349         CHECK(env);
350         c->obj = (*jni)->CallStaticObjectMethod(jni, cls, fact, str, n_nodes, n_regs, dbg_level);
351         CHECK(env);
352         c->cls = (*jni)->GetObjectClass(jni, c->obj);
353
354         /* Reference the created object. */
355         c->obj = (*jni)->NewGlobalRef(jni, c->obj);
356         CHECK(env);
357
358         /* Lookup the member methods of the object. */
359         for(i = 0; i < mth_last; ++i) {
360                 c->mth_ids[i] = (*jni)->GetMethodID(jni, c->cls, mthis[i].name, mthis[i].sig);
361                 CHECK(env);
362         }
363
364         return c;
365 }
366
367 void be_java_coal_destroy(be_java_coal_t *c) {
368         JNIEnv *jni = c->env->jni;
369         jc_call_void(c, mth_finish);
370         (*jni)->DeleteGlobalRef(jni, c->obj);
371         free(c);
372 }
373
374 void be_java_coal_add_int_edge(be_java_coal_t *c, int n, int m)
375 {
376         jc_call_void(c, mth_add_int_edge, (jint) n, (jint) m);
377 }
378
379 void be_java_coal_add_aff_edge(be_java_coal_t *c, int n, int m, int weight)
380 {
381         jc_call_void(c, mth_add_aff_edge, (jint) n, (jint) m, (jint) weight);
382 }
383
384 void be_java_coal_set_color(be_java_coal_t *c, int n, int col)
385 {
386         jc_call_void(c, mth_set_color, (jint) n, (jint) col);
387 }
388
389 void be_java_coal_set_debug(be_java_coal_t *c, int n, const char *dbg)
390 {
391         (void) c;
392         (void) n;
393         (void) dbg;
394 #if 0
395         JNIEnv *jni   = c->env->jni;
396         jmethodID mid = c->mth_ids[mth_set_debug];
397         jstring str;
398
399         str = (*jni)->NewStringUTF(jni, dbg);
400         CHECK(c->env);
401         (*jni)->CallVoidMethod(jni, c->obj, mid, (jint) n, str);
402         CHECK(c->env);
403 #endif /* if 0 */
404 }
405
406 void be_java_coal_forbid_color(be_java_coal_t *c, int n, int col)
407 {
408         jc_call_void(c, mth_forbid_color, (jint) n, (jint) col);
409 }
410
411 void be_java_coal_coalesce(be_java_coal_t *c)
412 {
413         jc_call_void(c, mth_coalesce);
414 }
415
416 void be_java_coal_dump(be_java_coal_t *c, const char *fn)
417 {
418         JNIEnv *jni   = c->env->jni;
419         jmethodID mid = c->mth_ids[mth_dump];
420         jstring str;
421
422         str = (*jni)->NewStringUTF(jni, fn);
423         CHECK(c->env);
424         (*jni)->CallVoidMethod(jni, c->obj, mid, str);
425         CHECK(c->env);
426 }
427
428 int be_java_coal_get_color(be_java_coal_t *c, int n)
429 {
430         return jc_call_int(c, mth_get_color, (jint) n);
431 }
432
433 void be_java_coal_start_jvm(void)
434 {
435         get_jvm();
436 }
437
438 #else /* ! WITH_JVM */
439
440 void be_java_coal_start_jvm(void)
441 {
442 }
443
444 #endif /* WITH_JVM */