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