rta: use callsites to do the analysis
[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
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 end
246
247 # A visitor on the AST of property definition that generate the C code.
248 # Because of inlining, a visitor can visit more than one property.
249 class GlobalCompilerVisitor
250 super AbstractCompilerVisitor
251
252 redef type COMPILER: GlobalCompiler
253
254 redef fun autobox(value, mtype)
255 do
256 if value.mtype == mtype then
257 return value
258 else if value.mtype.ctype == "val*" and mtype.ctype == "val*" then
259 return value
260 else if value.mtype.ctype == "val*" then
261 return self.new_expr("((struct {mtype.c_name}*){value})->value; /* autounbox from {value.mtype} to {mtype} */", mtype)
262 else if mtype.ctype == "val*" then
263 var valtype = value.mtype.as(MClassType)
264 var res = self.new_var(mtype)
265 if not compiler.runtime_type_analysis.live_types.has(valtype) then
266 self.add("/*no autobox from {value.mtype} to {mtype}: {value.mtype} is not live! */")
267 self.add("printf(\"Dead code executed!\\n\"); show_backtrace(1);")
268 return res
269 end
270 self.add("{res} = BOX_{valtype.c_name}({value}); /* autobox from {value.mtype} to {mtype} */")
271 return res
272 else
273 # Bad things will appen!
274 var res = self.new_var(mtype)
275 self.add("/* {res} left unintialized (cannot convert {value.mtype} to {mtype}) */")
276 self.add("printf(\"Cast error: Cannot cast %s to %s.\\n\", \"{value.mtype}\", \"{mtype}\"); show_backtrace(1);")
277 return res
278 end
279 end
280
281 # The runtime types that are acceptable for a given receiver.
282 fun collect_types(recv: RuntimeVariable): Array[MClassType]
283 do
284 var mtype = recv.mcasttype
285 if recv.is_exact then
286 assert mtype isa MClassType
287 assert self.compiler.runtime_type_analysis.live_types.has(mtype)
288 var types = [mtype]
289 return types
290 end
291 var cache = self.compiler.collect_types_cache
292 if cache.has_key(mtype) then
293 return cache[mtype]
294 end
295 var types = new Array[MClassType]
296 var mainmodule = self.compiler.mainmodule
297 for t in self.compiler.runtime_type_analysis.live_types do
298 if not t.is_subtype(mainmodule, null, mtype) then continue
299 types.add(t)
300 end
301 cache[mtype] = types
302 return types
303 end
304
305 redef fun native_array_def(pname, ret_type, arguments)
306 do
307 var elttype = arguments.first.mtype
308 var recv = "((struct {arguments[0].mcasttype.c_name}*){arguments[0]})->values"
309 if pname == "[]" then
310 self.ret(self.new_expr("{recv}[{arguments[1]}]", ret_type.as(not null)))
311 return
312 else if pname == "[]=" then
313 self.add("{recv}[{arguments[1]}]={arguments[2]};")
314 return
315 else if pname == "copy_to" then
316 var recv1 = "((struct {arguments[1].mcasttype.c_name}*){arguments[1]})->values"
317 self.add("memcpy({recv1},{recv},{arguments[2]}*sizeof({elttype.ctype}));")
318 return
319 end
320 end
321
322 redef fun calloc_array(ret_type, arguments)
323 do
324 self.ret(self.new_expr("NEW_{ret_type.c_name}({arguments[1]})", ret_type))
325 end
326
327 redef fun send(m, args)
328 do
329 var types = self.collect_types(args.first)
330
331 var res: nullable RuntimeVariable
332 var ret = m.intro.msignature.return_mtype
333 if m.is_new then
334 ret = args.first.mtype
335 res = self.new_var(ret)
336 else if ret == null then
337 res = null
338 else
339 ret = self.resolve_for(ret, args.first)
340 res = self.new_var(ret)
341 end
342
343 self.add("/* send {m} on {args.first.inspect} */")
344 if args.first.mtype.ctype != "val*" then
345 var mclasstype = args.first.mtype.as(MClassType)
346 if not self.compiler.runtime_type_analysis.live_types.has(mclasstype) then
347 self.add("/* skip, no method {m} */")
348 return res
349 end
350 var propdef = m.lookup_first_definition(self.compiler.mainmodule, mclasstype)
351 var res2 = self.call(propdef, mclasstype, args)
352 if res != null then self.assign(res, res2.as(not null))
353 return res
354 end
355 var consider_null = not self.compiler.modelbuilder.toolcontext.opt_no_check_other.value or m.name == "==" or m.name == "!="
356 if args.first.mcasttype isa MNullableType or args.first.mcasttype isa MNullType and consider_null then
357 # The reciever is potentially null, so we have to 3 cases: ==, != or NullPointerException
358 self.add("if ({args.first} == NULL) \{ /* Special null case */")
359 if m.name == "==" then
360 assert res != null
361 if args[1].mcasttype isa MNullableType then
362 self.add("{res} = ({args[1]} == NULL);")
363 else if args[1].mcasttype isa MNullType then
364 self.add("{res} = 1; /* is null */")
365 else
366 self.add("{res} = 0; /* {args[1].inspect} cannot be null */")
367 end
368 else if m.name == "!=" then
369 assert res != null
370 if args[1].mcasttype isa MNullableType then
371 self.add("{res} = ({args[1]} != NULL);")
372 else if args[1].mcasttype isa MNullType then
373 self.add("{res} = 0; /* is null */")
374 else
375 self.add("{res} = 1; /* {args[1].inspect} cannot be null */")
376 end
377 else
378 self.add_abort("Reciever is null")
379 end
380 self.add "\} else"
381 end
382 if types.is_empty then
383 self.add("\{")
384 self.add("/*BUG: no live types for {args.first.inspect} . {m}*/")
385 self.bugtype(args.first)
386 self.add("\}")
387 return res
388 end
389
390 self.add("switch({args.first}->classid) \{")
391 var last = types.last
392 var defaultpropdef: nullable MMethodDef = null
393 for t in types do
394 var propdef = m.lookup_first_definition(self.compiler.mainmodule, t)
395 if propdef.mclassdef.mclass.name == "Object" and t.ctype == "val*" then
396 defaultpropdef = propdef
397 continue
398 end
399 if not self.compiler.hardening and t == last and defaultpropdef == null then
400 self.add("default: /* test {t} */")
401 else
402 self.add("case {self.compiler.classid(t)}: /* test {t} */")
403 end
404 var res2 = self.call(propdef, t, args)
405 if res != null then self.assign(res, res2.as(not null))
406 self.add "break;"
407 end
408 if defaultpropdef != null then
409 self.add("default: /* default is Object */")
410 var res2 = self.call(defaultpropdef, defaultpropdef.mclassdef.bound_mtype, args)
411 if res != null then self.assign(res, res2.as(not null))
412 else if self.compiler.hardening then
413 self.add("default: /* bug */")
414 self.bugtype(args.first)
415 end
416 self.add("\}")
417 return res
418 end
419
420 fun check_valid_reciever(recvtype: MClassType)
421 do
422 if self.compiler.runtime_type_analysis.live_types.has(recvtype) or recvtype.mclass.name == "Object" then return
423 print "{recvtype} is not a live type"
424 abort
425 end
426
427 # Subpart of old call function
428 #
429 # Checks if the type of the receiver is valid and corrects it if necessary
430 private fun get_recvtype(m: MMethodDef, recvtype: MClassType, args: Array[RuntimeVariable]): MClassType
431 do
432 check_valid_reciever(recvtype)
433 #debug("call {m} on {recvtype} on {args.first}:{args.first.mtype}")
434 if m.mclassdef.mclass.name == "Object" and recvtype.ctype == "val*" then
435 recvtype = m.mclassdef.bound_mtype
436 end
437 return recvtype
438 end
439
440 # Subpart of old call function
441 # Gets the receiver boxed and casted if necessary
442 private fun get_recv(recvtype: MClassType, args: Array[RuntimeVariable]): RuntimeVariable
443 do
444 return self.autoadapt(self.autobox(args.first, recvtype), recvtype)
445 end
446
447 # Finalizes a call to a method ´m´ on type ´recvtype´ with arguments ´args´
448 private fun finalize_call(m: MMethodDef, recvtype: MClassType, args: Array[RuntimeVariable]): nullable RuntimeVariable
449 do
450 if args.length != m.msignature.arity + 1 then # because of self
451 add("printf(\"NOT YET IMPLEMENTED: Invalid arity for {m}. {args.length} arguments given.\\n\"); show_backtrace(1);")
452 debug("NOT YET IMPLEMENTED: Invalid arity for {m}. {args.length} arguments given.")
453 return null
454 end
455
456 var rm = new CustomizedRuntimeFunction(m, recvtype)
457 return rm.call(self, args)
458 end
459
460 redef fun call(m, recvtype, args)
461 do
462 var recv_type = get_recvtype(m, recvtype, args)
463 var recv = get_recv(recv_type, args)
464 var new_args = args.to_a
465 self.varargize(m, m.msignature.as(not null), new_args)
466 new_args.first = recv
467 return finalize_call(m, recv_type, new_args)
468 end
469
470 # Does a call without encapsulating varargs into an array
471 # Avoids multiple encapsulation when calling a super in a variadic function
472 fun call_without_varargize(m: MMethodDef, recvtype: MClassType, args: Array[RuntimeVariable]): nullable RuntimeVariable
473 do
474 var recv_type = get_recvtype(m, recvtype, args)
475 var recv = get_recv(recv_type, args)
476 var new_args = args.to_a
477 new_args.first = recv
478 return finalize_call(m, recv_type, new_args)
479 end
480
481 redef fun supercall(m: MMethodDef, recvtype: MClassType, args: Array[RuntimeVariable]): nullable RuntimeVariable
482 do
483 var types = self.collect_types(args.first)
484
485 var res: nullable RuntimeVariable
486 var ret = m.mproperty.intro.msignature.return_mtype
487 if ret == null then
488 res = null
489 else
490 ret = self.resolve_for(ret, args.first)
491 res = self.new_var(ret)
492 end
493
494 self.add("/* super {m} on {args.first.inspect} */")
495 if args.first.mtype.ctype != "val*" then
496 var mclasstype = args.first.mtype.as(MClassType)
497 if not self.compiler.runtime_type_analysis.live_types.has(mclasstype) then
498 self.add("/* skip, no method {m} */")
499 return res
500 end
501 var propdef = m.lookup_next_definition(self.compiler.mainmodule, mclasstype)
502 var res2 = self.call_without_varargize(propdef, mclasstype, args)
503 if res != null then self.assign(res, res2.as(not null))
504 return res
505 end
506
507 if types.is_empty then
508 self.add("\{")
509 self.add("/*BUG: no live types for {args.first.inspect} . {m}*/")
510 self.bugtype(args.first)
511 self.add("\}")
512 return res
513 end
514
515 self.add("switch({args.first}->classid) \{")
516 var last = types.last
517 for t in types do
518 var propdef = m.lookup_next_definition(self.compiler.mainmodule, t)
519 if not self.compiler.hardening and t == last then
520 self.add("default: /* test {t} */")
521 else
522 self.add("case {self.compiler.classid(t)}: /* test {t} */")
523 end
524 var res2 = self.call_without_varargize(propdef, t, args)
525 if res != null then self.assign(res, res2.as(not null))
526 self.add "break;"
527 end
528 if self.compiler.hardening then
529 self.add("default: /* bug */")
530 self.bugtype(args.first)
531 end
532 self.add("\}")
533 return res
534 end
535
536 redef fun adapt_signature(m, args)
537 do
538 var recv = args.first
539 for i in [0..m.msignature.arity[ do
540 var t = m.msignature.mparameters[i].mtype
541 if i == m.msignature.vararg_rank then
542 t = args[i+1].mtype
543 end
544 t = self.resolve_for(t, recv)
545 args[i+1] = self.autobox(args[i+1], t)
546 end
547 end
548
549 # FIXME: this is currently buggy since recv is not exact
550 redef fun vararg_instance(mpropdef, recv, varargs, elttype)
551 do
552 elttype = self.resolve_for(elttype, recv)
553 return self.array_instance(varargs, elttype)
554 end
555
556 fun bugtype(recv: RuntimeVariable)
557 do
558 if recv.mtype.ctype != "val*" then return
559 self.add("fprintf(stderr, \"BTD BUG: Dynamic type is %s, static type is %s\\n\", class_names[{recv}->classid], \"{recv.mcasttype}\");")
560 self.add("show_backtrace(1);")
561 end
562
563 redef fun isset_attribute(a, recv)
564 do
565 check_recv_notnull(recv)
566
567 var types = self.collect_types(recv)
568 var res = self.new_var(bool_type)
569
570 if types.is_empty then
571 self.add("/*BUG: no live types for {recv.inspect} . {a}*/")
572 self.bugtype(recv)
573 return res
574 end
575 self.add("/* isset {a} on {recv.inspect} */")
576 self.add("switch({recv}->classid) \{")
577 var last = types.last
578 for t in types do
579 if not self.compiler.hardening and t == last then
580 self.add("default: /*{self.compiler.classid(t)}*/")
581 else
582 self.add("case {self.compiler.classid(t)}:")
583 end
584 var recv2 = self.autoadapt(recv, t)
585 var ta = a.intro.static_mtype.as(not null)
586 ta = self.resolve_for(ta, recv2)
587 var attr = self.new_expr("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta)
588 if not ta isa MNullableType then
589 if ta.ctype == "val*" then
590 self.add("{res} = ({attr} != NULL);")
591 else
592 self.add("{res} = 1; /*NOTYET isset on primitive attributes*/")
593 end
594 end
595 self.add("break;")
596 end
597 if self.compiler.hardening then
598 self.add("default: /* Bug */")
599 self.bugtype(recv)
600 end
601 self.add("\}")
602
603 return res
604 end
605
606 redef fun read_attribute(a, recv)
607 do
608 check_recv_notnull(recv)
609
610 var types = self.collect_types(recv)
611
612 var ret = a.intro.static_mtype.as(not null)
613 ret = self.resolve_for(ret, recv)
614 var res = self.new_var(ret)
615
616 if types.is_empty then
617 self.add("/*BUG: no live types for {recv.inspect} . {a}*/")
618 self.bugtype(recv)
619 return res
620 end
621 self.add("/* read {a} on {recv.inspect} */")
622 self.add("switch({recv}->classid) \{")
623 var last = types.last
624 for t in types do
625 if not self.compiler.hardening and t == last then
626 self.add("default: /*{self.compiler.classid(t)}*/")
627 else
628 self.add("case {self.compiler.classid(t)}:")
629 end
630 var recv2 = self.autoadapt(recv, t)
631 var ta = a.intro.static_mtype.as(not null)
632 ta = self.resolve_for(ta, recv2)
633 var res2 = self.new_expr("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta)
634 if not ta isa MNullableType and not self.compiler.modelbuilder.toolcontext.opt_no_check_other.value then
635 if ta.ctype == "val*" then
636 self.add("if ({res2} == NULL) \{")
637 self.add_abort("Uninitialized attribute {a.name}")
638 self.add("\}")
639 else
640 self.add("/*NOTYET isset on primitive attributes*/")
641 end
642 end
643 self.assign(res, res2)
644 self.add("break;")
645 end
646 if self.compiler.hardening then
647 self.add("default: /* Bug */")
648 self.bugtype(recv)
649 end
650 self.add("\}")
651
652 return res
653 end
654
655 redef fun write_attribute(a, recv, value)
656 do
657 check_recv_notnull(recv)
658
659 var types = self.collect_types(recv)
660
661 if types.is_empty then
662 self.add("/*BUG: no live types for {recv.inspect} . {a}*/")
663 self.bugtype(recv)
664 return
665 end
666 self.add("/* write {a} on {recv.inspect} */")
667 self.add("switch({recv}->classid) \{")
668 var last = types.last
669 for t in types do
670 if not self.compiler.hardening and t == last then
671 self.add("default: /*{self.compiler.classid(t)}*/")
672 else
673 self.add("case {self.compiler.classid(t)}:")
674 end
675 var recv2 = self.autoadapt(recv, t)
676 var ta = a.intro.static_mtype.as(not null)
677 ta = self.resolve_for(ta, recv2)
678 self.add("((struct {t.c_name}*){recv})->{a.intro.c_name} = {self.autobox(value, ta)};")
679 self.add("break;")
680 end
681 if self.compiler.hardening then
682 self.add("default: /* Bug*/")
683 self.bugtype(recv)
684 end
685 self.add("\}")
686 end
687
688 redef fun init_instance(mtype)
689 do
690 mtype = self.anchor(mtype).as(MClassType)
691 if not self.compiler.runtime_type_analysis.live_types.has(mtype) then
692 debug "problem: {mtype} was detected dead"
693 end
694 var res = self.new_expr("NEW_{mtype.c_name}()", mtype)
695 res.is_exact = true
696 return res
697 end
698
699 redef fun type_test(value, mtype, tag)
700 do
701 mtype = self.anchor(mtype)
702 var mclasstype = mtype
703 if mtype isa MNullableType then mclasstype = mtype.mtype
704 assert mclasstype isa MClassType
705 if not self.compiler.runtime_type_analysis.live_cast_types.has(mclasstype) 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