nitg: use GC_MALLOC_ATOMIC for calloc_string
[nit.git] / src / separate_erasure_compiler.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 # Separate compilation of a Nit program with generic type erasure
16 module separate_erasure_compiler
17
18
19 import separate_compiler
20
21 redef class ToolContext
22 # --erasure
23 var opt_erasure: OptionBool = new OptionBool("Erase generic types", "--erasure")
24
25 # --no-check-erasure-cast
26 var opt_no_check_erasure_cast: OptionBool = new OptionBool("Disable implicit casts on unsafe return with erasure-typing policy (dangerous)", "--no-check-erasure-cast")
27
28 redef init
29 do
30 super
31 self.option_context.add_option(self.opt_erasure, self.opt_no_check_erasure_cast)
32 end
33 end
34
35 redef class ModelBuilder
36 fun run_separate_erasure_compiler(mainmodule: MModule, runtime_type_analysis: RapidTypeAnalysis)
37 do
38 var time0 = get_time
39 self.toolcontext.info("*** COMPILING TO C ***", 1)
40
41 var compiler = new SeparateErasureCompiler(mainmodule, runtime_type_analysis, self)
42 compiler.compile_header
43
44 # compile class structures
45 for m in mainmodule.in_importation.greaters do
46 for mclass in m.intro_mclasses do
47 compiler.compile_class_to_c(mclass)
48 end
49 end
50
51 # The main function of the C
52 compiler.compile_main_function
53
54 # compile methods
55 for m in mainmodule.in_importation.greaters do
56 compiler.compile_module_to_c(m)
57 end
58
59 write_and_make(compiler)
60 end
61 end
62
63 class SeparateErasureCompiler
64 super SeparateCompiler
65
66 private var class_ids: HashMap[MClass, Int] = new HashMap[MClass, Int]
67 private var class_colors: Map[MClass, Int]
68 private var class_tables: Map[MClass, Array[nullable MClass]]
69
70 init(mainmodule: MModule, runtime_type_analysis: RapidTypeAnalysis, mmbuilder: ModelBuilder) do
71 var mclasses = new HashSet[MClass]
72 mclasses.add_all(mmbuilder.model.mclasses)
73
74 # classes coloration
75 if modelbuilder.toolcontext.opt_phmod_typing.value then
76 # set type unique id
77 for mclass in mclasses do
78 self.class_ids[mclass] = self.class_ids.length + 1
79 end
80
81 var class_coloring = new ClassModPerfectHashing(mainmodule)
82 self.class_colors = class_coloring.compute_masks(mclasses, class_ids)
83 self.class_tables = class_coloring.hash_type_tables(mclasses, class_ids, class_colors)
84
85 self.header.add_decl("#define HASH(mask, id) ((mask)%(id))")
86 else if modelbuilder.toolcontext.opt_phand_typing.value then
87 # set type unique id
88 for mclass in mclasses do
89 self.class_ids[mclass] = self.class_ids.length + 1
90 end
91
92 var class_coloring = new ClassAndPerfectHashing(mainmodule)
93 self.class_colors = class_coloring.compute_masks(mclasses, class_ids)
94 self.class_tables = class_coloring.hash_type_tables(mclasses, class_ids, class_colors)
95
96 self.header.add_decl("#define HASH(mask, id) ((mask)&(id))")
97 else
98 var class_coloring
99 if modelbuilder.toolcontext.opt_bm_typing.value then
100 class_coloring = new NaiveClassColoring(mainmodule)
101 else
102 class_coloring = new ClassColoring(mainmodule)
103 end
104 # set type unique id
105 for mclass in mclasses do
106 self.class_ids[mclass] = self.class_ids.length + 1
107 end
108 self.class_colors = class_coloring.colorize(modelbuilder.model.mclasses)
109 self.class_tables = class_coloring.build_type_tables(modelbuilder.model.mclasses, class_colors)
110 end
111 end
112
113 redef fun compile_header_structs do
114 self.header.add_decl("typedef void(*nitmethod_t)(void); /* general C type representing a Nit method. */")
115 self.compile_header_attribute_structs
116 self.header.add_decl("struct class \{ int id; const char *name; int box_kind; int color; struct vts_table *vts_table; struct type_table *type_table; nitmethod_t vft[1]; \}; /* general C type representing a Nit class. */")
117 self.header.add_decl("struct type_table \{ int size; int table[1]; \}; /* colorized type table. */")
118 self.header.add_decl("struct vts_entry \{ short int is_nullable; struct class *class; \}; /* link (nullable or not) between the vts and is bound. */")
119
120 if modelbuilder.toolcontext.opt_phmod_typing.value or modelbuilder.toolcontext.opt_phand_typing.value then
121 self.header.add_decl("struct vts_table \{ int mask; struct vts_entry vts[1]; \}; /* vts list of a C type representation. */")
122 else
123 self.header.add_decl("struct vts_table \{ struct vts_entry vts[1]; \}; /* vts list of a C type representation. */")
124 end
125
126 self.header.add_decl("typedef struct val \{ struct class *class; nitattribute_t attrs[1]; \} val; /* general C type representing a Nit instance. */")
127 end
128
129 redef fun compile_class_to_c(mclass: MClass)
130 do
131 var mtype = mclass.intro.bound_mtype
132 var c_name = mclass.c_name
133
134 var vft = self.method_tables[mclass]
135 var attrs = self.attr_tables[mclass]
136 var class_table = self.class_tables[mclass]
137 var v = self.new_visitor
138
139 v.add_decl("/* runtime class {c_name} */")
140 var idnum = classids.length
141 var idname = "ID_" + c_name
142 self.classids[mtype] = idname
143 #self.header.add_decl("#define {idname} {idnum} /* {c_name} */")
144
145 self.header.add_decl("extern const struct class_{c_name} class_{c_name};")
146 self.header.add_decl("struct class_{c_name} \{")
147 self.header.add_decl("int id;")
148 self.header.add_decl("const char *name;")
149 self.header.add_decl("int box_kind;")
150 self.header.add_decl("int color;")
151 self.header.add_decl("const struct vts_table *vts_table;")
152 self.header.add_decl("struct type_table *type_table;")
153 self.header.add_decl("nitmethod_t vft[{vft.length}];")
154 self.header.add_decl("\};")
155
156 # Build class vft
157 v.add_decl("const struct class_{c_name} class_{c_name} = \{")
158 v.add_decl("{self.class_ids[mclass]},")
159 v.add_decl("\"{mclass.name}\", /* class_name_string */")
160 v.add_decl("{self.box_kind_of(mclass)}, /* box_kind */")
161 v.add_decl("{self.class_colors[mclass]},")
162 if build_class_vts_table(mclass) then
163 v.add_decl("(const struct vts_table*) &vts_table_{c_name},")
164 else
165 v.add_decl("NULL,")
166 end
167 v.add_decl("(struct type_table*) &type_table_{c_name},")
168 v.add_decl("\{")
169 for i in [0 .. vft.length[ do
170 var mpropdef = vft[i]
171 if mpropdef == null then
172 v.add_decl("NULL, /* empty */")
173 else
174 if true or mpropdef.mclassdef.bound_mtype.ctype != "val*" then
175 v.add_decl("(nitmethod_t)VIRTUAL_{mpropdef.c_name}, /* pointer to {mclass.intro_mmodule}:{mclass}:{mpropdef} */")
176 else
177 v.add_decl("(nitmethod_t){mpropdef.c_name}, /* pointer to {mclass.intro_mmodule}:{mclass}:{mpropdef} */")
178 end
179 end
180 end
181 v.add_decl("\}")
182 v.add_decl("\};")
183
184 # Build class type table
185 self.header.add_decl("extern const struct type_table_{c_name} type_table_{c_name};")
186 self.header.add_decl("struct type_table_{c_name} \{")
187 self.header.add_decl("int size;")
188 self.header.add_decl("int table[{class_table.length}];")
189 self.header.add_decl("\};")
190
191 v.add_decl("const struct type_table_{c_name} type_table_{c_name} = \{")
192 v.add_decl("{class_table.length},")
193 v.add_decl("\{")
194 for msuper in class_table do
195 if msuper == null then
196 v.add_decl("-1, /* empty */")
197 else
198 v.add_decl("{self.class_ids[msuper]}, /* {msuper} */")
199 end
200 end
201 v.add_decl("\}")
202 v.add_decl("\};")
203
204 #Build instance struct
205 if mtype.ctype != "val*" then
206 self.header.add_decl("struct instance_{c_name} \{")
207 self.header.add_decl("const struct class *class;")
208 self.header.add_decl("{mtype.ctype} value;")
209 self.header.add_decl("\};")
210
211 self.header.add_decl("val* BOX_{c_name}({mtype.ctype});")
212 v.add_decl("/* allocate {mtype} */")
213 v.add_decl("val* BOX_{mtype.c_name}({mtype.ctype} value) \{")
214 v.add("struct instance_{c_name}*res = GC_MALLOC(sizeof(struct instance_{c_name}));")
215 v.add("res->class = (struct class*) &class_{c_name};")
216 v.add("res->value = value;")
217 v.add("return (val*)res;")
218 v.add("\}")
219 return
220 end
221
222 var is_native_array = mclass.name == "NativeArray"
223
224 var sig
225 if is_native_array then
226 sig = "int length"
227 else
228 sig = ""
229 end
230
231 #Build instance struct
232 #extern const struct instance_array__NativeArray instance_array__NativeArray;
233 self.header.add_decl("struct instance_{c_name} \{")
234 self.header.add_decl("const struct class *class;")
235 self.header.add_decl("nitattribute_t attrs[{attrs.length}];")
236 if is_native_array then
237 # NativeArrays are just a instance header followed by an array of values
238 self.header.add_decl("val* values[0];")
239 end
240 self.header.add_decl("\};")
241
242
243 self.header.add_decl("{mtype.ctype} NEW_{c_name}({sig});")
244 v.add_decl("/* allocate {mtype} */")
245 v.add_decl("{mtype.ctype} NEW_{c_name}({sig}) \{")
246 var res = v.new_named_var(mtype, "self")
247 res.is_exact = true
248 if is_native_array then
249 var mtype_elt = mtype.arguments.first
250 v.add("{res} = GC_MALLOC(sizeof(struct instance_{c_name}) + length*sizeof({mtype_elt.ctype}));")
251 else
252 v.add("{res} = GC_MALLOC(sizeof(struct instance_{c_name}));")
253 end
254 v.add("{res}->class = (struct class*) &class_{c_name};")
255
256 self.generate_init_attr(v, res, mtype)
257 v.add("return {res};")
258 v.add("\}")
259
260 generate_check_init_instance(mtype)
261 end
262
263 private fun build_class_vts_table(mclass: MClass): Bool do
264 if self.vt_tables[mclass].is_empty then return false
265
266 self.header.add_decl("extern const struct vts_table_{mclass.c_name} vts_table_{mclass.c_name};")
267 self.header.add_decl("struct vts_table_{mclass.c_name} \{")
268 if modelbuilder.toolcontext.opt_phmod_typing.value or modelbuilder.toolcontext.opt_phand_typing.value then
269 self.header.add_decl("int mask;")
270 end
271 self.header.add_decl("struct vts_entry vts[{self.vt_tables[mclass].length}];")
272 self.header.add_decl("\};")
273
274 var v = new_visitor
275 v.add_decl("const struct vts_table_{mclass.c_name} vts_table_{mclass.c_name} = \{")
276 if modelbuilder.toolcontext.opt_phmod_typing.value or modelbuilder.toolcontext.opt_phand_typing.value then
277 v.add_decl("{vt_masks[mclass]},")
278 end
279 v.add_decl("\{")
280
281 for vt in self.vt_tables[mclass] do
282 if vt == null then
283 v.add_decl("\{-1, NULL\}, /* empty */")
284 else
285 var is_null = 0
286 var bound = retrieve_vt_bound(mclass.intro.bound_mtype, vt.bound)
287 while bound isa MNullableType do
288 bound = retrieve_vt_bound(mclass.intro.bound_mtype, bound.mtype)
289 is_null = 1
290 end
291 v.add_decl("\{{is_null}, (struct class*)&class_{bound.as(MClassType).mclass.c_name}\}, /* {vt} */")
292 end
293 end
294 v.add_decl("\},")
295 v.add_decl("\};")
296 return true
297 end
298
299 private fun retrieve_vt_bound(anchor: MClassType, mtype: nullable MType): MType do
300 if mtype == null then
301 print "NOT YET IMPLEMENTED: retrieve_vt_bound on null"
302 abort
303 end
304 if mtype isa MVirtualType then
305 return mtype.anchor_to(mainmodule, anchor)
306 else if mtype isa MParameterType then
307 return mtype.anchor_to(mainmodule, anchor)
308 else
309 return mtype
310 end
311 end
312
313 redef fun new_visitor do return new SeparateErasureCompilerVisitor(self)
314 end
315
316 class SeparateErasureCompilerVisitor
317 super SeparateCompilerVisitor
318
319 redef fun compile_callsite(callsite, arguments)
320 do
321 var res = super
322 if callsite.erasure_cast and not self.compiler.as(SeparateErasureCompiler).modelbuilder.toolcontext.opt_no_check_erasure_cast.value then
323 assert res != null
324 var mtype = callsite.msignature.return_mtype
325 assert mtype != null
326 self.add("/* Erasure cast for return {res} isa {mtype} */")
327 var cond = self.type_test(res, mtype)
328 self.add("if (!{cond}) \{")
329 #var x = self.class_name_string(res)
330 #var y = self.class_name_string(arguments.first)
331 #self.add("fprintf(stderr, \"Erasure cast: expected {mtype} (self is %s), got %s for {res}\\n\", {y}, {x});")
332 self.add_abort("Cast failed")
333 self.add("\}")
334 end
335 return res
336 end
337
338 redef fun init_instance(mtype)
339 do
340 return self.new_expr("NEW_{mtype.mclass.c_name}()", mtype)
341 end
342
343 redef fun type_test(value, mtype)
344 do
345 self.add("/* type test for {value.inspect} isa {mtype} */")
346
347 var res = self.new_var(bool_type)
348
349 var cltype = self.get_name("cltype")
350 self.add_decl("int {cltype};")
351 var idtype = self.get_name("idtype")
352 self.add_decl("int {idtype};")
353 var is_nullable = self.get_name("is_nullable")
354 self.add_decl("short int {is_nullable};")
355 var is_null = self.get_name("is_null")
356 self.add_decl("short int {is_null};")
357
358 var maybe_null = 0
359 if mtype isa MNullableType then
360 mtype = mtype.mtype
361 maybe_null = 1
362 self.add("{is_nullable} = 1;")
363 end
364 if mtype isa MParameterType then
365 # Here we get the bound of the the formal type (eh, erasure...)
366 mtype = mtype.resolve_for(self.frame.mpropdef.mclassdef.bound_mtype, self.frame.mpropdef.mclassdef.bound_mtype, self.frame.mpropdef.mclassdef.mmodule, false)
367 if mtype isa MNullableType then
368 mtype = mtype.mtype
369 maybe_null = 1
370 self.add("{is_nullable} = 1;")
371 end
372 end
373 if mtype isa MVirtualType then
374 # FIXME virtual types should not be erased but got from the class table of the current receiver (self.frame.arguments.first)
375 #mtype = mtype.resolve_for(self.frame.mpropdef.mclassdef.bound_mtype, self.frame.mpropdef.mclassdef.bound_mtype, self.frame.mpropdef.mclassdef.mmodule, true)
376 #if mtype isa MNullableType then
377 # mtype = mtype.mtype
378 # maybe_null = true
379 #end
380 end
381
382 if value.mcasttype.is_subtype(self.frame.mpropdef.mclassdef.mmodule, self.frame.mpropdef.mclassdef.bound_mtype, mtype) then
383 self.add("{res} = 1; /* easy {value.inspect} isa {mtype}*/")
384 return res
385 end
386
387 var class_ptr
388 var type_table
389 if value.mtype.ctype == "val*" then
390 class_ptr = "{value}->class->"
391 self.add("{is_null} = {value} == NULL;")
392 else
393 var mclass = value.mtype.as(MClassType).mclass
394 class_ptr = "class_{mclass.c_name}."
395 self.add("{is_null} = 0;")
396 end
397
398 if mtype isa MClassType then
399 self.add("{cltype} = class_{mtype.mclass.c_name}.color;")
400 self.add("{idtype} = class_{mtype.mclass.c_name}.id;")
401 if maybe_null == 0 then
402 self.add("{is_nullable} = 0;")
403 end
404 else if mtype isa MVirtualType then
405 var recv = self.frame.arguments.first
406 var recv_ptr
407 if recv.mtype.ctype == "val*" then
408 recv_ptr = "{recv}->class->"
409 else
410 var mclass = recv.mtype.as(MClassType).mclass
411 recv_ptr = "class_{mclass.c_name}."
412 end
413 var entry = self.get_name("entry")
414 self.add("struct vts_entry {entry};")
415 if compiler.modelbuilder.toolcontext.opt_phmod_typing.value or compiler.modelbuilder.toolcontext.opt_phand_typing.value then
416 self.add("{entry} = {recv_ptr}vts_table->vts[HASH({recv_ptr}vts_table->mask, {mtype.mproperty.const_color})];")
417 else
418 self.add("{entry} = {recv_ptr}vts_table->vts[{mtype.mproperty.const_color}];")
419 end
420 self.add("{cltype} = {entry}.class->color;")
421 self.add("{idtype} = {entry}.class->id;")
422 if maybe_null == 0 then
423 self.add("{is_nullable} = {entry}.is_nullable;")
424 end
425 else
426 self.debug("type_test({value.inspect}, {mtype})")
427 abort
428 end
429
430 # check color is in table
431 self.add("if({is_null}) \{")
432 self.add("{res} = {is_nullable};")
433 self.add("\} else \{")
434 if compiler.modelbuilder.toolcontext.opt_phmod_typing.value or compiler.modelbuilder.toolcontext.opt_phand_typing.value then
435 self.add("{cltype} = HASH({class_ptr}color, {idtype});")
436 end
437 self.add("if({cltype} >= {class_ptr}type_table->size) \{")
438 self.add("{res} = 0;")
439 self.add("\} else \{")
440 self.add("{res} = {class_ptr}type_table->table[{cltype}] == {idtype};")
441 self.add("\}")
442 self.add("\}")
443
444 return res
445 end
446
447 redef fun class_name_string(value)
448 do
449 var res = self.get_name("var_class_name")
450 self.add_decl("const char* {res};")
451 if value.mtype.ctype == "val*" then
452 self.add "{res} = {value} == NULL ? \"null\" : {value}->class->name;"
453 else
454 self.add "{res} = class_{value.mtype.c_name}.name;"
455 end
456 return res
457 end
458
459 redef fun array_instance(array, elttype)
460 do
461 var nclass = self.get_class("NativeArray")
462 elttype = self.anchor(elttype)
463 var arraytype = self.get_class("Array").get_mtype([elttype])
464 var res = self.init_instance(arraytype)
465 self.add("\{ /* {res} = array_instance Array[{elttype}] */")
466 var nat = self.new_var(self.get_class("NativeArray").get_mtype([elttype]))
467 nat.is_exact = true
468 self.add("{nat} = NEW_{nclass.c_name}({array.length});")
469 for i in [0..array.length[ do
470 var r = self.autobox(array[i], self.object_type)
471 self.add("((struct instance_{nclass.c_name}*){nat})->values[{i}] = (val*) {r};")
472 end
473 var length = self.int_instance(array.length)
474 self.send(self.get_property("with_native", arraytype), [res, nat, length])
475 self.check_init_instance(res, arraytype)
476 self.add("\}")
477 return res
478 end
479
480 redef fun calloc_array(ret_type, arguments)
481 do
482 var ret = ret_type.as(MClassType)
483 self.ret(self.new_expr("NEW_{ret.mclass.c_name}({arguments[1]})", ret_type))
484 end
485 end