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