compilers: missing argument unboxing with new nativearray
[nit.git] / src / compiler / global_compiler.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2012 Jean Privat <jean@pryen.org>
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 # Global compilation of a Nit program
18 #
19 # Techniques used are:
20 # * heterogeneous generics
21 # * customization
22 # * switch dispatch
23 # * inlining
24 module global_compiler
25
26 import abstract_compiler
27 import rapid_type_analysis
28
29 redef class ToolContext
30 # option --global
31 var opt_global = new OptionBool("Use global compilation", "--global")
32
33 var global_compiler_phase = new GlobalCompilerPhase(self, null)
34
35 redef init do
36 super
37 option_context.add_option(opt_global)
38 end
39 end
40
41 class GlobalCompilerPhase
42 super Phase
43 redef fun process_mainmodule(mainmodule, given_mmodules) do
44 if not toolcontext.opt_global.value then return
45
46 var modelbuilder = toolcontext.modelbuilder
47 var analysis = modelbuilder.do_rapid_type_analysis(mainmodule)
48 modelbuilder.run_global_compiler(mainmodule, analysis)
49 end
50 end
51
52 redef class ModelBuilder
53 # Entry point to performs a global compilation on the AST of a complete program.
54 # `mainmodule` is the main module of the program
55 # `runtime_type_analysis` is a already computer type analysis.
56 fun run_global_compiler(mainmodule: MModule, runtime_type_analysis: RapidTypeAnalysis)
57 do
58 var time0 = get_time
59 self.toolcontext.info("*** GENERATING C ***", 1)
60
61 var compiler = new GlobalCompiler(mainmodule, self, runtime_type_analysis)
62 compiler.do_compilation
63 compiler.display_stats
64
65 var time1 = get_time
66 self.toolcontext.info("*** END GENERATING C: {time1-time0} ***", 2)
67 write_and_make(compiler)
68 end
69 end
70
71 # Compiler that use global compilation and perform hard optimisations like:
72 # * customization
73 # * switch dispatch
74 # * inlining
75 class GlobalCompiler
76 super AbstractCompiler
77
78 redef type VISITOR: GlobalCompilerVisitor
79
80 # The result of the RTA (used to know live types and methods)
81 var runtime_type_analysis: RapidTypeAnalysis
82
83 init
84 do
85 var file = new_file("{mainmodule.c_name}.nitgg")
86 self.header = new CodeWriter(file)
87 self.live_primitive_types = new Array[MClassType]
88 for t in runtime_type_analysis.live_types do
89 if t.is_c_primitive or t.mclass.name == "Pointer" then
90 self.live_primitive_types.add(t)
91 end
92 end
93 end
94
95 redef fun do_compilation
96 do
97 var compiler = self
98
99 compiler.compile_header
100
101 if mainmodule.model.get_mclasses_by_name("Pointer") != null then
102 runtime_type_analysis.live_types.add(mainmodule.pointer_type)
103 end
104 for t in runtime_type_analysis.live_types do
105 compiler.declare_runtimeclass(t)
106 end
107
108 compiler.compile_class_names
109
110 # Init instance code (allocate and init-arguments)
111 for t in runtime_type_analysis.live_types do
112 if not t.is_c_primitive then
113 compiler.generate_init_instance(t)
114 if t.mclass.kind == extern_kind then
115 compiler.generate_box_instance(t)
116 end
117 else
118 compiler.generate_box_instance(t)
119 end
120 end
121
122 # The main function of the C
123 compiler.compile_nitni_global_ref_functions
124 compiler.compile_main_function
125
126 # Compile until all runtime_functions are visited
127 while not compiler.todos.is_empty do
128 var m = compiler.todos.shift
129 modelbuilder.toolcontext.info("Compile {m} ({compiler.seen.length-compiler.todos.length}/{compiler.seen.length})", 3)
130 m.compile_to_c(compiler)
131 end
132 modelbuilder.toolcontext.info("Total methods to compile to C: {compiler.seen.length}", 2)
133
134 end
135
136 # Compile class names (for the class_name and output_class_name methods)
137 protected fun compile_class_names do
138 var v = new_visitor
139 self.header.add_decl("extern const char *class_names[];")
140 v.add("const char *class_names[] = \{")
141 for t in self.runtime_type_analysis.live_types do
142 v.add("\"{t}\", /* {self.classid(t)} */")
143 end
144 v.add("\};")
145 end
146
147 # Return the C symbol associated to a live type runtime
148 # REQUIRE: self.runtime_type_analysis.live_types.has(mtype)
149 fun classid(mtype: MClassType): String
150 do
151 if self.classids.has_key(mtype) then
152 return self.classids[mtype]
153 end
154 print "No classid for {mtype}"
155 abort
156 end
157
158 # Cache for classid
159 protected var classids: HashMap[MClassType, String] = new HashMap[MClassType, String]
160
161 # Declaration of structures the live Nit types
162 # Each live type is generated as an independent C `struct` type.
163 # They only share a common first field `classid` used to implement the polymorphism.
164 # Usualy, all C variables that refers to a Nit object are typed on the abstract struct `val` that contains only the `classid` field.
165 redef fun compile_header_structs do
166 self.header.add_decl("typedef struct \{int classid;\} val; /* general C type representing a Nit instance. */")
167 end
168
169 # Subset of runtime_type_analysis.live_types that contains only primitive types
170 # Used to implement the equal test
171 var live_primitive_types: Array[MClassType] is noinit
172
173 # Add a new todo task
174 fun todo(m: AbstractRuntimeFunction)
175 do
176 if seen.has(m) then return
177 todos.add(m)
178 seen.add(m)
179 end
180
181 # runtime_functions that need to be compiled
182 private var todos: List[AbstractRuntimeFunction] = new List[AbstractRuntimeFunction]
183
184 # runtime_functions already seen (todo or done)
185 private var seen: HashSet[AbstractRuntimeFunction] = new HashSet[AbstractRuntimeFunction]
186
187 # Declare C structures and identifiers for a runtime class
188 fun declare_runtimeclass(mtype: MClassType)
189 do
190 var v = self.header
191 assert self.runtime_type_analysis.live_types.has(mtype)
192 v.add_decl("/* runtime class {mtype} */")
193 var idnum = classids.length
194 var idname = "ID_" + mtype.c_name
195 self.classids[mtype] = idname
196 v.add_decl("#define {idname} {idnum} /* {mtype} */")
197
198 v.add_decl("struct {mtype.c_name} \{")
199 v.add_decl("int classid; /* must be {idname} */")
200
201 if mtype.mclass.name == "NativeArray" then
202 # NativeArrays are just a instance header followed by an array of values
203 v.add_decl("int length;")
204 v.add_decl("{mtype.arguments.first.ctype} values[1];")
205 end
206
207 if mtype.ctype_extern != "val*" then
208 # Is the Nit type is native then the struct is a box with two fields:
209 # * the `classid` to be polymorph
210 # * the `value` that contains the native value.
211 v.add_decl("{mtype.ctype_extern} value;")
212 end
213
214 # Collect all attributes and associate them a field in the structure.
215 # Note: we do not try to optimize the order and helps CC to optimize the client code.
216 for cd in mtype.collect_mclassdefs(self.mainmodule) do
217 for p in cd.intro_mproperties do
218 if not p isa MAttribute then continue
219 var t = p.intro.static_mtype.as(not null)
220 t = t.anchor_to(self.mainmodule, mtype)
221 v.add_decl("{t.ctype} {p.intro.c_name}; /* {p}: {t} */")
222 end
223 end
224 v.add_decl("\};")
225 end
226
227 # Generate the init-instance of a live type (allocate + init-instance)
228 fun generate_init_instance(mtype: MClassType)
229 do
230 assert self.runtime_type_analysis.live_types.has(mtype)
231 assert not mtype.is_c_primitive
232 var v = self.new_visitor
233
234 var is_native_array = mtype.mclass.name == "NativeArray"
235
236 var sig
237 if is_native_array then
238 sig = "int length"
239 else
240 sig = "void"
241 end
242
243 self.header.add_decl("{mtype.ctype} NEW_{mtype.c_name}({sig});")
244 v.add_decl("/* allocate {mtype} */")
245 v.add_decl("{mtype.ctype} NEW_{mtype.c_name}({sig}) \{")
246 var res = v.new_var(mtype)
247 res.is_exact = true
248 if is_native_array then
249 var mtype_elt = mtype.arguments.first
250 v.add("{res} = nit_alloc(sizeof(struct {mtype.c_name}) + length*sizeof({mtype_elt.ctype}));")
251 v.add("((struct {mtype.c_name}*){res})->length = length;")
252 else
253 v.add("{res} = nit_alloc(sizeof(struct {mtype.c_name}));")
254 end
255 v.add("{res}->classid = {self.classid(mtype)};")
256
257 self.generate_init_attr(v, res, mtype)
258 v.set_finalizer res
259 v.add("return {res};")
260 v.add("\}")
261 end
262
263 fun generate_box_instance(mtype: MClassType)
264 do
265 assert self.runtime_type_analysis.live_types.has(mtype)
266 var v = self.new_visitor
267
268 self.header.add_decl("val* BOX_{mtype.c_name}({mtype.ctype});")
269 v.add_decl("/* allocate {mtype} */")
270 v.add_decl("val* BOX_{mtype.c_name}({mtype.ctype} value) \{")
271 v.add("struct {mtype.c_name}*res = nit_alloc(sizeof(struct {mtype.c_name}));")
272 v.add("res->classid = {self.classid(mtype)};")
273 v.add("res->value = value;")
274 v.add("return (val*)res;")
275 v.add("\}")
276 end
277
278 redef fun new_visitor do return new GlobalCompilerVisitor(self)
279
280 private var collect_types_cache: HashMap[MType, Array[MClassType]] = new HashMap[MType, Array[MClassType]]
281
282 redef fun compile_nitni_structs
283 do
284 self.header.add_decl """
285 struct nitni_instance \{
286 struct nitni_instance *next,
287 *prev; /* adjacent global references in global list */
288 int count; /* number of time this global reference has been marked */
289 val *value;
290 \};"""
291 super
292 end
293 end
294
295 # A visitor on the AST of property definition that generate the C code.
296 # Because of inlining, a visitor can visit more than one property.
297 class GlobalCompilerVisitor
298 super AbstractCompilerVisitor
299
300 redef type COMPILER: GlobalCompiler
301
302 redef fun autobox(value, mtype)
303 do
304 if value.mtype == mtype then
305 return value
306 else if not value.mtype.is_c_primitive and not mtype.is_c_primitive then
307 return value
308 else if not value.mtype.is_c_primitive then
309 return self.new_expr("((struct {mtype.c_name}*){value})->value; /* autounbox from {value.mtype} to {mtype} */", mtype)
310 else if not mtype.is_c_primitive then
311 var valtype = value.mtype.as(MClassType)
312 var res = self.new_var(mtype)
313 if not compiler.runtime_type_analysis.live_types.has(valtype) then
314 self.add("/*no autobox from {value.mtype} to {mtype}: {value.mtype} is not live! */")
315 self.add("PRINT_ERROR(\"Dead code executed!\\n\"); fatal_exit(1);")
316 return res
317 end
318 self.add("{res} = BOX_{valtype.c_name}({value}); /* autobox from {value.mtype} to {mtype} */")
319 return res
320 else if value.mtype.ctype == "void*" and mtype.ctype == "void*" then
321 return value
322 else
323 # Bad things will appen!
324 var res = self.new_var(mtype)
325 self.add("/* {res} left unintialized (cannot convert {value.mtype} to {mtype}) */")
326 self.add("PRINT_ERROR(\"Cast error: Cannot cast %s to %s.\\n\", \"{value.mtype}\", \"{mtype}\"); fatal_exit(1);")
327 return res
328 end
329 end
330
331 redef fun unbox_extern(value, mtype)
332 do
333 if mtype isa MClassType and mtype.mclass.kind == extern_kind and
334 mtype.mclass.name != "NativeString" then
335 var res = self.new_var_extern(mtype)
336 self.add "{res} = ((struct {mtype.c_name}*){value})->value; /* unboxing {value.mtype} */"
337 return res
338 else
339 return value
340 end
341 end
342
343 redef fun box_extern(value, mtype)
344 do
345 if not mtype isa MClassType or mtype.mclass.kind != extern_kind or
346 mtype.mclass.name == "NativeString" then return value
347
348 var valtype = value.mtype.as(MClassType)
349 var res = self.new_var(mtype)
350 if not compiler.runtime_type_analysis.live_types.has(value.mtype.as(MClassType)) then
351 self.add("/*no boxing of {value.mtype}: {value.mtype} is not live! */")
352 self.add("PRINT_ERROR(\"Dead code executed!\\n\"); fatal_exit(1);")
353 return res
354 end
355 self.add("{res} = BOX_{valtype.c_name}({value}); /* boxing {value.mtype} */")
356 return res
357 end
358
359 # The runtime types that are acceptable for a given receiver.
360 fun collect_types(recv: RuntimeVariable): Array[MClassType]
361 do
362 var mtype = recv.mcasttype
363 if recv.is_exact then
364 assert mtype isa MClassType
365 assert self.compiler.runtime_type_analysis.live_types.has(mtype)
366 var types = [mtype]
367 return types
368 end
369 var cache = self.compiler.collect_types_cache
370 if cache.has_key(mtype) then
371 return cache[mtype]
372 end
373 var types = new Array[MClassType]
374 var mainmodule = self.compiler.mainmodule
375 for t in self.compiler.runtime_type_analysis.live_types do
376 if not t.is_subtype(mainmodule, null, mtype) then continue
377 types.add(t)
378 end
379 cache[mtype] = types
380 return types
381 end
382
383 redef fun native_array_def(pname, ret_type, arguments)
384 do
385 var elttype = arguments.first.mtype
386 var recv = "((struct {arguments[0].mcasttype.c_name}*){arguments[0]})->values"
387 if pname == "[]" then
388 self.ret(self.new_expr("{recv}[{arguments[1]}]", ret_type.as(not null)))
389 return
390 else if pname == "[]=" then
391 self.add("{recv}[{arguments[1]}]={arguments[2]};")
392 return
393 else if pname == "length" then
394 self.ret(self.new_expr("((struct {arguments[0].mcasttype.c_name}*){arguments[0]})->length", ret_type.as(not null)))
395 return
396 else if pname == "copy_to" then
397 var recv1 = "((struct {arguments[1].mcasttype.c_name}*){arguments[1]})->values"
398 self.add("memmove({recv1},{recv},{arguments[2]}*sizeof({elttype.ctype}));")
399 return
400 end
401 end
402
403 redef fun native_array_instance(elttype: MType, length: RuntimeVariable): RuntimeVariable
404 do
405 var ret_type = mmodule.native_array_type(elttype)
406 ret_type = anchor(ret_type).as(MClassType)
407 length = autobox(length, compiler.mainmodule.int_type)
408 return self.new_expr("NEW_{ret_type.c_name}({length})", ret_type)
409 end
410
411 redef fun native_array_get(nat, i)
412 do
413 var recv = "((struct {nat.mcasttype.c_name}*){nat})->values"
414 var ret_type = nat.mcasttype.as(MClassType).arguments.first
415 return self.new_expr("{recv}[{i}]", ret_type)
416 end
417
418 redef fun native_array_set(nat, i, val)
419 do
420 var recv = "((struct {nat.mcasttype.c_name}*){nat})->values"
421 self.add("{recv}[{i}]={val};")
422 end
423
424 redef fun calloc_array(ret_type, arguments)
425 do
426 self.ret(self.new_expr("NEW_{ret_type.c_name}({arguments[1]})", ret_type))
427 end
428
429 redef fun send(m, args)
430 do
431 var types = self.collect_types(args.first)
432
433 var res: nullable RuntimeVariable
434 var ret = m.intro.msignature.return_mtype
435 if ret == null then
436 res = null
437 else
438 ret = self.resolve_for(ret, args.first)
439 res = self.new_var(ret)
440 end
441
442 self.add("/* send {m} on {args.first.inspect} */")
443 if args.first.mtype.is_c_primitive then
444 var mclasstype = args.first.mtype.as(MClassType)
445 if not self.compiler.runtime_type_analysis.live_types.has(mclasstype) then
446 self.add("/* skip, no method {m} */")
447 return res
448 end
449 var propdef = m.lookup_first_definition(self.compiler.mainmodule, mclasstype)
450 var res2 = self.call(propdef, mclasstype, args)
451 if res != null then self.assign(res, res2.as(not null))
452 return res
453 end
454 var consider_null = not self.compiler.modelbuilder.toolcontext.opt_no_check_null.value or m.name == "==" or m.name == "!="
455 if args.first.mcasttype isa MNullableType or args.first.mcasttype isa MNullType and consider_null then
456 # The reciever is potentially null, so we have to 3 cases: ==, != or NullPointerException
457 self.add("if ({args.first} == NULL) \{ /* Special null case */")
458 if m.name == "==" or m.name == "is_same_instance" then
459 assert res != null
460 if args[1].mcasttype isa MNullableType then
461 self.add("{res} = ({args[1]} == NULL);")
462 else if args[1].mcasttype isa MNullType then
463 self.add("{res} = 1; /* is null */")
464 else
465 self.add("{res} = 0; /* {args[1].inspect} cannot be null */")
466 end
467 else if m.name == "!=" then
468 assert res != null
469 if args[1].mcasttype isa MNullableType then
470 self.add("{res} = ({args[1]} != NULL);")
471 else if args[1].mcasttype isa MNullType then
472 self.add("{res} = 0; /* is null */")
473 else
474 self.add("{res} = 1; /* {args[1].inspect} cannot be null */")
475 end
476 else
477 self.add_abort("Receiver is null")
478 end
479 self.add "\} else"
480 end
481 if types.is_empty then
482 self.add("\{")
483 self.add("/*BUG: no live types for {args.first.inspect} . {m}*/")
484 self.bugtype(args.first)
485 self.add("\}")
486 return res
487 end
488
489 self.add("switch({args.first}->classid) \{")
490 var last = types.last
491 var defaultpropdef: nullable MMethodDef = null
492 for t in types do
493 var propdef = m.lookup_first_definition(self.compiler.mainmodule, t)
494 if propdef.mclassdef.mclass.name == "Object" and not t.is_c_primitive then
495 defaultpropdef = propdef
496 continue
497 end
498 if not self.compiler.hardening and t == last and defaultpropdef == null then
499 self.add("default: /* test {t} */")
500 else
501 self.add("case {self.compiler.classid(t)}: /* test {t} */")
502 end
503 var res2 = self.call(propdef, t, args)
504 if res != null then self.assign(res, res2.as(not null))
505 self.add "break;"
506 end
507 if defaultpropdef != null then
508 self.add("default: /* default is Object */")
509 var res2 = self.call(defaultpropdef, defaultpropdef.mclassdef.bound_mtype, args)
510 if res != null then self.assign(res, res2.as(not null))
511 else if self.compiler.hardening then
512 self.add("default: /* bug */")
513 self.bugtype(args.first)
514 end
515 self.add("\}")
516 return res
517 end
518
519 fun check_valid_reciever(recvtype: MClassType)
520 do
521 if self.compiler.runtime_type_analysis.live_types.has(recvtype) or recvtype.mclass.name == "Object" then return
522 print "{recvtype} is not a live type"
523 abort
524 end
525
526 # Subpart of old call function
527 #
528 # Checks if the type of the receiver is valid and corrects it if necessary
529 private fun get_recvtype(m: MMethodDef, recvtype: MClassType, args: Array[RuntimeVariable]): MClassType
530 do
531 check_valid_reciever(recvtype)
532 return recvtype
533 end
534
535 redef fun call(m, recvtype, args)
536 do
537 var recv_type = get_recvtype(m, recvtype, args)
538 var recv = self.autoadapt(self.autobox(args.first, recvtype), recvtype)
539 if m.is_extern then recv = unbox_extern(recv, recv_type)
540
541 args = args.to_a
542 args.first = recv
543
544 assert args.length == m.msignature.arity + 1 else debug("Invalid arity for {m}. {args.length} arguments given.")
545
546 var rm = new CustomizedRuntimeFunction(m, recvtype)
547 return rm.call(self, args)
548 end
549
550 redef fun supercall(m: MMethodDef, recvtype: MClassType, args: Array[RuntimeVariable]): nullable RuntimeVariable
551 do
552 var types = self.collect_types(args.first)
553
554 var res: nullable RuntimeVariable
555 var ret = m.mproperty.intro.msignature.return_mtype
556 if ret == null then
557 res = null
558 else
559 ret = self.resolve_for(ret, args.first)
560 res = self.new_var(ret)
561 end
562
563 self.add("/* super {m} on {args.first.inspect} */")
564 if args.first.mtype.is_c_primitive then
565 var mclasstype = args.first.mtype.as(MClassType)
566 if not self.compiler.runtime_type_analysis.live_types.has(mclasstype) then
567 self.add("/* skip, no method {m} */")
568 return res
569 end
570 var propdef = m.lookup_next_definition(self.compiler.mainmodule, mclasstype)
571 var res2 = self.call(propdef, mclasstype, args)
572 if res != null then self.assign(res, res2.as(not null))
573 return res
574 end
575
576 if types.is_empty then
577 self.add("\{")
578 self.add("/*BUG: no live types for {args.first.inspect} . {m}*/")
579 self.bugtype(args.first)
580 self.add("\}")
581 return res
582 end
583
584 self.add("switch({args.first}->classid) \{")
585 var last = types.last
586 for t in types do
587 var propdef = m.lookup_next_definition(self.compiler.mainmodule, t)
588 if not self.compiler.hardening and t == last then
589 self.add("default: /* test {t} */")
590 else
591 self.add("case {self.compiler.classid(t)}: /* test {t} */")
592 end
593 var res2 = self.call(propdef, t, args)
594 if res != null then self.assign(res, res2.as(not null))
595 self.add "break;"
596 end
597 if self.compiler.hardening then
598 self.add("default: /* bug */")
599 self.bugtype(args.first)
600 end
601 self.add("\}")
602 return res
603 end
604
605 redef fun adapt_signature(m, args)
606 do
607 var recv = args.first
608 for i in [0..m.msignature.arity[ do
609 var t = m.msignature.mparameters[i].mtype
610 if i == m.msignature.vararg_rank then
611 t = args[i+1].mtype
612 end
613 t = self.resolve_for(t, recv)
614 args[i+1] = self.autobox(args[i+1], t)
615 end
616 end
617
618 redef fun unbox_signature_extern(m, args)
619 do
620 var recv = args.first
621 for i in [0..m.msignature.arity[ do
622 var t = m.msignature.mparameters[i].mtype
623 if i == m.msignature.vararg_rank then
624 t = args[i+1].mtype
625 end
626 t = self.resolve_for(t, recv)
627 if m.is_extern then args[i+1] = self.unbox_extern(args[i+1], t)
628 end
629 end
630
631 # FIXME: this is currently buggy since recv is not exact
632 redef fun vararg_instance(mpropdef, recv, varargs, elttype)
633 do
634 elttype = self.resolve_for(elttype, recv)
635 return self.array_instance(varargs, elttype)
636 end
637
638 fun bugtype(recv: RuntimeVariable)
639 do
640 if recv.mtype.is_c_primitive then return
641 self.add("PRINT_ERROR(\"BTD BUG: Dynamic type is %s, static type is %s\\n\", class_names[{recv}->classid], \"{recv.mcasttype}\");")
642 self.add("fatal_exit(1);")
643 end
644
645 redef fun isset_attribute(a, recv)
646 do
647 check_recv_notnull(recv)
648
649 var types = self.collect_types(recv)
650 var res = self.new_var(bool_type)
651
652 if types.is_empty then
653 self.add("/*BUG: no live types for {recv.inspect} . {a}*/")
654 self.bugtype(recv)
655 return res
656 end
657 self.add("/* isset {a} on {recv.inspect} */")
658 self.add("switch({recv}->classid) \{")
659 var last = types.last
660 for t in types do
661 if not self.compiler.hardening and t == last then
662 self.add("default: /*{self.compiler.classid(t)}*/")
663 else
664 self.add("case {self.compiler.classid(t)}:")
665 end
666 var recv2 = self.autoadapt(recv, t)
667 var ta = a.intro.static_mtype.as(not null)
668 ta = self.resolve_for(ta, recv2)
669 var attr = self.new_expr("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta)
670 if not ta isa MNullableType then
671 if not ta.is_c_primitive then
672 self.add("{res} = ({attr} != NULL);")
673 else
674 self.add("{res} = 1; /*NOTYET isset on primitive attributes*/")
675 end
676 end
677 self.add("break;")
678 end
679 if self.compiler.hardening then
680 self.add("default: /* Bug */")
681 self.bugtype(recv)
682 end
683 self.add("\}")
684
685 return res
686 end
687
688 redef fun read_attribute(a, recv)
689 do
690 check_recv_notnull(recv)
691
692 var types = self.collect_types(recv)
693
694 var ret = a.intro.static_mtype.as(not null)
695 ret = self.resolve_for(ret, recv)
696 var res = self.new_var(ret)
697
698 if types.is_empty then
699 self.add("/*BUG: no live types for {recv.inspect} . {a}*/")
700 self.bugtype(recv)
701 return res
702 end
703 self.add("/* read {a} on {recv.inspect} */")
704 self.add("switch({recv}->classid) \{")
705 var last = types.last
706 for t in types do
707 if not self.compiler.hardening and t == last then
708 self.add("default: /*{self.compiler.classid(t)}*/")
709 else
710 self.add("case {self.compiler.classid(t)}:")
711 end
712 var recv2 = self.autoadapt(recv, t)
713 var ta = a.intro.static_mtype.as(not null)
714 ta = self.resolve_for(ta, recv2)
715 var res2 = self.new_expr("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta)
716 if not ta isa MNullableType and not self.compiler.modelbuilder.toolcontext.opt_no_check_attr_isset.value then
717 if not ta.is_c_primitive then
718 self.add("if ({res2} == NULL) \{")
719 self.add_abort("Uninitialized attribute {a.name}")
720 self.add("\}")
721 else
722 self.add("/*NOTYET isset on primitive attributes*/")
723 end
724 end
725 self.assign(res, res2)
726 self.add("break;")
727 end
728 if self.compiler.hardening then
729 self.add("default: /* Bug */")
730 self.bugtype(recv)
731 end
732 self.add("\}")
733
734 return res
735 end
736
737 redef fun write_attribute(a, recv, value)
738 do
739 check_recv_notnull(recv)
740
741 var types = self.collect_types(recv)
742
743 if types.is_empty then
744 self.add("/*BUG: no live types for {recv.inspect} . {a}*/")
745 self.bugtype(recv)
746 return
747 end
748 self.add("/* write {a} on {recv.inspect} */")
749 self.add("switch({recv}->classid) \{")
750 var last = types.last
751 for t in types do
752 if not self.compiler.hardening and t == last then
753 self.add("default: /*{self.compiler.classid(t)}*/")
754 else
755 self.add("case {self.compiler.classid(t)}:")
756 end
757 var recv2 = self.autoadapt(recv, t)
758 var ta = a.intro.static_mtype.as(not null)
759 ta = self.resolve_for(ta, recv2)
760 self.add("((struct {t.c_name}*){recv})->{a.intro.c_name} = {self.autobox(value, ta)};")
761 self.add("break;")
762 end
763 if self.compiler.hardening then
764 self.add("default: /* Bug*/")
765 self.bugtype(recv)
766 end
767 self.add("\}")
768 end
769
770 redef fun init_instance(mtype)
771 do
772 mtype = self.anchor(mtype).as(MClassType)
773 if not self.compiler.runtime_type_analysis.live_types.has(mtype) then
774 debug "problem: {mtype} was detected dead"
775 end
776 var res = self.new_expr("NEW_{mtype.c_name}()", mtype)
777 res.is_exact = true
778 return res
779 end
780
781 redef fun type_test(value, mtype, tag)
782 do
783 mtype = self.anchor(mtype)
784 if not self.compiler.runtime_type_analysis.live_cast_types.has(mtype) then
785 debug "problem: {mtype} was detected cast-dead"
786 abort
787 end
788
789 var types = self.collect_types(value)
790 var res = self.new_var(bool_type)
791
792 self.add("/* isa {mtype} on {value.inspect} */")
793 if value.mtype.is_c_primitive then
794 if value.mtype.is_subtype(self.compiler.mainmodule, null, mtype) then
795 self.add("{res} = 1;")
796 else
797 self.add("{res} = 0;")
798 end
799 return res
800 end
801 if value.mcasttype isa MNullableType or value.mcasttype isa MNullType then
802 self.add("if ({value} == NULL) \{")
803 if mtype isa MNullableType then
804 self.add("{res} = 1; /* isa {mtype} */")
805 else
806 self.add("{res} = 0; /* not isa {mtype} */")
807 end
808 self.add("\} else ")
809 end
810 self.add("switch({value}->classid) \{")
811 for t in types do
812 if t.is_subtype(self.compiler.mainmodule, null, mtype) then
813 self.add("case {self.compiler.classid(t)}: /* {t} */")
814 end
815 end
816 self.add("{res} = 1;")
817 self.add("break;")
818 self.add("default:")
819 self.add("{res} = 0;")
820 self.add("\}")
821
822 return res
823 end
824
825 redef fun is_same_type_test(value1, value2)
826 do
827 var res = self.new_var(bool_type)
828 if not value2.mtype.is_c_primitive then
829 if not value1.mtype.is_c_primitive then
830 self.add "{res} = {value1}->classid == {value2}->classid;"
831 else
832 self.add "{res} = {self.compiler.classid(value1.mtype.as(MClassType))} == {value2}->classid;"
833 end
834 else
835 if not value1.mtype.is_c_primitive then
836 self.add "{res} = {value1}->classid == {self.compiler.classid(value2.mtype.as(MClassType))};"
837 else if value1.mcasttype == value2.mcasttype then
838 self.add "{res} = 1;"
839 else
840 self.add "{res} = 0;"
841 end
842 end
843 return res
844 end
845
846 redef fun class_name_string(value)
847 do
848 var res = self.get_name("var_class_name")
849 self.add_decl("const char* {res};")
850 if not value.mtype.is_c_primitive then
851 self.add "{res} = class_names[{value}->classid];"
852 else
853 self.add "{res} = class_names[{self.compiler.classid(value.mtype.as(MClassType))}];"
854 end
855 return res
856 end
857
858 redef fun equal_test(value1, value2)
859 do
860 var res = self.new_var(bool_type)
861 if value2.mtype.is_c_primitive and not value1.mtype.is_c_primitive then
862 var tmp = value1
863 value1 = value2
864 value2 = tmp
865 end
866 if value1.mtype.is_c_primitive then
867 if value2.mtype == value1.mtype then
868 self.add("{res} = {value1} == {value2};")
869 else if value2.mtype.is_c_primitive then
870 self.add("{res} = 0; /* incompatible types {value1.mtype} vs. {value2.mtype}*/")
871 else
872 var mtype1 = value1.mtype.as(MClassType)
873 self.add("{res} = ({value2} != NULL) && ({value2}->classid == {self.compiler.classid(mtype1)});")
874 self.add("if ({res}) \{")
875 self.add("{res} = ({self.autobox(value2, value1.mtype)} == {value1});")
876 self.add("\}")
877 end
878 else
879 var s = new Array[String]
880 for t in self.compiler.live_primitive_types do
881 if not t.is_subtype(self.compiler.mainmodule, null, value1.mcasttype) then continue
882 if not t.is_subtype(self.compiler.mainmodule, null, value2.mcasttype) then continue
883 s.add "({value1}->classid == {self.compiler.classid(t)} && ((struct {t.c_name}*){value1})->value == ((struct {t.c_name}*){value2})->value)"
884 end
885
886 if self.compiler.mainmodule.model.get_mclasses_by_name("Pointer") != null then
887 var pointer_type = self.compiler.mainmodule.pointer_type
888 if value1.mcasttype.is_subtype(self.compiler.mainmodule, null, pointer_type) or
889 value2.mcasttype.is_subtype(self.compiler.mainmodule, null, pointer_type) then
890 s.add "(((struct {pointer_type.c_name}*){value1})->value == ((struct {pointer_type.c_name}*){value2})->value)"
891 end
892 end
893
894 if s.is_empty then
895 self.add("{res} = {value1} == {value2};")
896 else
897 self.add("{res} = {value1} == {value2} || ({value1} != NULL && {value2} != NULL && {value1}->classid == {value2}->classid && ({s.join(" || ")}));")
898 end
899 end
900 return res
901 end
902
903 redef fun array_instance(array, elttype)
904 do
905 elttype = self.anchor(elttype)
906 var arraytype = mmodule.array_type(elttype)
907 var res = self.init_instance(arraytype)
908 self.add("\{ /* {res} = array_instance Array[{elttype}] */")
909 var nat = self.new_var(mmodule.native_array_type(elttype))
910 nat.is_exact = true
911 self.add("{nat} = NEW_{nat.mtype.c_name}({array.length});")
912 for i in [0..array.length[ do
913 var r = self.autobox(array[i], elttype)
914 self.add("((struct {nat.mtype.c_name}*) {nat})->values[{i}] = {r};")
915 end
916 var length = self.int_instance(array.length)
917 self.send(self.get_property("with_native", arraytype), [res, nat, length])
918 self.add("\}")
919 return res
920 end
921 end
922
923 # A runtime function customized on a specific monomrph receiver type
924 private class CustomizedRuntimeFunction
925 super AbstractRuntimeFunction
926
927 redef type COMPILER: GlobalCompiler
928 redef type VISITOR: GlobalCompilerVisitor
929
930 # The considered reciever
931 # (usually is a live type but no strong guarantee)
932 var recv: MClassType
933
934 redef fun build_c_name
935 do
936 var res = self.c_name_cache
937 if res != null then return res
938 if self.mmethoddef.mclassdef.bound_mtype == self.recv then
939 res = self.mmethoddef.c_name
940 else
941 res = "{mmethoddef.c_name}__{recv.c_name}"
942 end
943 self.c_name_cache = res
944 return res
945 end
946
947 # used in the compiler worklist
948 redef fun ==(o)
949 do
950 if not o isa CustomizedRuntimeFunction then return false
951 if self.mmethoddef != o.mmethoddef then return false
952 if self.recv != o.recv then return false
953 return true
954 end
955
956 # used in the compiler work-list
957 redef fun hash do return self.mmethoddef.hash + self.recv.hash
958
959 redef fun to_s
960 do
961 if self.mmethoddef.mclassdef.bound_mtype == self.recv then
962 return self.mmethoddef.to_s
963 else
964 return "{self.mmethoddef}@{self.recv}"
965 end
966 end
967
968 # compile the code customized for the reciever
969 redef fun compile_to_c(compiler)
970 do
971 var recv = self.recv
972 var mmethoddef = self.mmethoddef
973 if not recv.is_subtype(compiler.mainmodule, null, mmethoddef.mclassdef.bound_mtype) then
974 print("problem: why do we compile {self} for {recv}?")
975 abort
976 end
977
978 var v = compiler.new_visitor
979 var selfvar = new RuntimeVariable("self", recv, recv)
980 if compiler.runtime_type_analysis.live_types.has(recv) then
981 selfvar.is_exact = true
982 end
983 var arguments = new Array[RuntimeVariable]
984 var frame = new StaticFrame(v, mmethoddef, recv, arguments)
985 v.frame = frame
986
987 var sig = new FlatBuffer
988 var comment = new FlatBuffer
989 var ret = mmethoddef.msignature.return_mtype
990 if ret != null then
991 ret = v.resolve_for(ret, selfvar)
992 sig.append("{ret.ctype} ")
993 else
994 sig.append("void ")
995 end
996 sig.append(self.c_name)
997 sig.append("({recv.ctype} {selfvar}")
998 comment.append("(self: {recv}")
999 arguments.add(selfvar)
1000 for i in [0..mmethoddef.msignature.arity[ do
1001 var mtype = mmethoddef.msignature.mparameters[i].mtype
1002 if i == mmethoddef.msignature.vararg_rank then
1003 mtype = v.mmodule.array_type(mtype)
1004 end
1005 mtype = v.resolve_for(mtype, selfvar)
1006 comment.append(", {mtype}")
1007 sig.append(", {mtype.ctype} p{i}")
1008 var argvar = new RuntimeVariable("p{i}", mtype, mtype)
1009 arguments.add(argvar)
1010 end
1011 sig.append(")")
1012 comment.append(")")
1013 if ret != null then
1014 comment.append(": {ret}")
1015 end
1016 compiler.header.add_decl("{sig};")
1017
1018 v.add_decl("/* method {self} for {comment} */")
1019 v.add_decl("{sig} \{")
1020 #v.add("printf(\"method {self} for {comment}\\n\");")
1021 if ret != null then
1022 frame.returnvar = v.new_var(ret)
1023 end
1024 frame.returnlabel = v.get_name("RET_LABEL")
1025
1026 mmethoddef.compile_inside_to_c(v, arguments)
1027
1028 v.add("{frame.returnlabel.as(not null)}:;")
1029 if ret != null then
1030 v.add("return {frame.returnvar.as(not null)};")
1031 end
1032 v.add("\}")
1033 if not self.c_name.has_substring("VIRTUAL", 0) then compiler.names[self.c_name] = "{mmethoddef.mclassdef.mmodule.name}::{mmethoddef.mclassdef.mclass.name}::{mmethoddef.mproperty.name} ({mmethoddef.location.file.filename}:{mmethoddef.location.line_start})"
1034 end
1035
1036 redef fun call(v: VISITOR, arguments: Array[RuntimeVariable]): nullable RuntimeVariable
1037 do
1038 var ret = self.mmethoddef.msignature.return_mtype
1039 if ret != null then
1040 ret = v.resolve_for(ret, arguments.first)
1041 end
1042 if self.mmethoddef.can_inline(v) then
1043 var frame = new StaticFrame(v, self.mmethoddef, self.recv, arguments)
1044 frame.returnlabel = v.get_name("RET_LABEL")
1045 if ret != null then
1046 frame.returnvar = v.new_var(ret)
1047 end
1048 var old_frame = v.frame
1049 v.frame = frame
1050 v.add("\{ /* Inline {self} ({arguments.join(",")}) */")
1051 self.mmethoddef.compile_inside_to_c(v, arguments)
1052 v.add("{frame.returnlabel.as(not null)}:(void)0;")
1053 v.add("\}")
1054 v.frame = old_frame
1055 return frame.returnvar
1056 end
1057 v.adapt_signature(self.mmethoddef, arguments)
1058 v.compiler.todo(self)
1059 if ret == null then
1060 v.add("{self.c_name}({arguments.join(",")});")
1061 return null
1062 else
1063 var res = v.new_var(ret)
1064 v.add("{res} = {self.c_name}({arguments.join(",")});")
1065 return res
1066 end
1067 end
1068 end