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