344dcd00236c94d9111c54cffc9b130891003c98
[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
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 propdefs = m.lookup_definitions(self.compiler.mainmodule, mclasstype)
363 if propdefs.length == 0 then
364 self.add("/* skip, no method {m} */")
365 return res
366 end
367 assert propdefs.length == 1
368 var propdef = propdefs.first
369 var res2 = self.call(propdef, mclasstype, args)
370 if res != null then self.assign(res, res2.as(not null))
371 return res
372 end
373 var consider_null = not self.compiler.modelbuilder.toolcontext.opt_no_check_other.value or m.name == "==" or m.name == "!="
374 if args.first.mcasttype isa MNullableType or args.first.mcasttype isa MNullType and consider_null then
375 # The reciever is potentially null, so we have to 3 cases: ==, != or NullPointerException
376 self.add("if ({args.first} == NULL) \{ /* Special null case */")
377 if m.name == "==" then
378 assert res != null
379 if args[1].mcasttype isa MNullableType then
380 self.add("{res} = ({args[1]} == NULL);")
381 else if args[1].mcasttype isa MNullType then
382 self.add("{res} = 1; /* is null */")
383 else
384 self.add("{res} = 0; /* {args[1].inspect} cannot be null */")
385 end
386 else if m.name == "!=" then
387 assert res != null
388 if args[1].mcasttype isa MNullableType then
389 self.add("{res} = ({args[1]} != NULL);")
390 else if args[1].mcasttype isa MNullType then
391 self.add("{res} = 0; /* is null */")
392 else
393 self.add("{res} = 1; /* {args[1].inspect} cannot be null */")
394 end
395 else
396 self.add_abort("Reciever is null")
397 end
398 self.add "\} else"
399 end
400 if types.is_empty then
401 self.add("\{")
402 self.add("/*BUG: no live types for {args.first.inspect} . {m}*/")
403 self.bugtype(args.first)
404 self.add("\}")
405 return res
406 end
407
408 self.add("switch({args.first}->classid) \{")
409 var last = types.last
410 var defaultpropdef: nullable MMethodDef = null
411 for t in types do
412 var propdefs = m.lookup_definitions(self.compiler.mainmodule, t)
413 if propdefs.length == 0 then
414 self.add("/* skip {t}, no method {m} */")
415 continue
416 end
417 if propdefs.length > 1 then
418 self.debug("NOT YET IMPLEMENTED conflict for {t}.{m}: {propdefs.join(" ")}. choose the first")
419 end
420 var propdef = propdefs.first
421 if propdef.mclassdef.mclass.name == "Object" and t.ctype == "val*" then
422 defaultpropdef = propdef
423 continue
424 end
425 if not self.compiler.hardening and t == last and defaultpropdef == null then
426 self.add("default: /* test {t} */")
427 else
428 self.add("case {self.compiler.classid(t)}: /* test {t} */")
429 end
430 var res2 = self.call(propdef, t, args)
431 if res != null then self.assign(res, res2.as(not null))
432 self.add "break;"
433 end
434 if defaultpropdef != null then
435 self.add("default: /* default is Object */")
436 var res2 = self.call(defaultpropdef, defaultpropdef.mclassdef.bound_mtype, args)
437 if res != null then self.assign(res, res2.as(not null))
438 else if self.compiler.hardening then
439 self.add("default: /* bug */")
440 self.bugtype(args.first)
441 end
442 self.add("\}")
443 return res
444 end
445
446 fun check_valid_reciever(recvtype: MClassType)
447 do
448 if self.compiler.runtime_type_analysis.live_types.has(recvtype) or recvtype.mclass.name == "Object" then return
449 print "{recvtype} is not a live type"
450 abort
451 end
452
453 redef fun call(m, recvtype, args)
454 do
455 check_valid_reciever(recvtype)
456 #debug("call {m} on {recvtype} on {args.first}:{args.first.mtype}")
457 if m.mclassdef.mclass.name == "Object" and recvtype.ctype == "val*" then
458 recvtype = m.mclassdef.bound_mtype
459 end
460 var recv = self.autobox(args.first, recvtype)
461 recv = self.autoadapt(recv, recvtype)
462
463 args = args.to_a
464 self.varargize(m, m.msignature.as(not null), args)
465 if args.length != m.msignature.arity + 1 then # because of self
466 add("printf(\"NOT YET IMPLEMENTED: Invalid arity for {m}. {args.length} arguments given.\\n\"); exit(1);")
467 debug("NOT YET IMPLEMENTED: Invalid arity for {m}. {args.length} arguments given.")
468 return null
469 end
470
471 args.first = recv
472 var rm = new CustomizedRuntimeFunction(m, recvtype)
473 return rm.call(self, args)
474 end
475
476 redef fun adapt_signature(m, args)
477 do
478 var recv = args.first
479 for i in [0..m.msignature.arity[ do
480 var t = m.msignature.mparameters[i].mtype
481 if i == m.msignature.vararg_rank then
482 t = args[i+1].mtype
483 end
484 t = self.resolve_for(t, recv)
485 args[i+1] = self.autobox(args[i+1], t)
486 end
487 end
488
489 # FIXME: this is currently buggy since recv is not exact
490 redef fun vararg_instance(mpropdef, recv, varargs, elttype)
491 do
492 elttype = self.resolve_for(elttype, recv)
493 return self.array_instance(varargs, elttype)
494 end
495
496 fun bugtype(recv: RuntimeVariable)
497 do
498 if recv.mtype.ctype != "val*" then return
499 self.add("fprintf(stderr, \"BTD BUG: Dynamic type is %s, static type is %s\\n\", class_names[{recv}->classid], \"{recv.mcasttype}\");")
500 self.add("exit(1);")
501 end
502
503 redef fun isset_attribute(a, recv)
504 do
505 check_recv_notnull(recv)
506
507 var types = self.collect_types(recv)
508 var res = self.new_var(bool_type)
509
510 if types.is_empty then
511 self.add("/*BUG: no live types for {recv.inspect} . {a}*/")
512 self.bugtype(recv)
513 return res
514 end
515 self.add("/* isset {a} on {recv.inspect} */")
516 self.add("switch({recv}->classid) \{")
517 var last = types.last
518 for t in types do
519 if not self.compiler.hardening and t == last then
520 self.add("default: /*{self.compiler.classid(t)}*/")
521 else
522 self.add("case {self.compiler.classid(t)}:")
523 end
524 var recv2 = self.autoadapt(recv, t)
525 var ta = a.intro.static_mtype.as(not null)
526 ta = self.resolve_for(ta, recv2)
527 var attr = self.new_expr("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta)
528 if not ta isa MNullableType then
529 if ta.ctype == "val*" then
530 self.add("{res} = ({attr} != NULL);")
531 else
532 self.add("{res} = 1; /*NOTYET isset on primitive attributes*/")
533 end
534 end
535 self.add("break;")
536 end
537 if self.compiler.hardening then
538 self.add("default: /* Bug */")
539 self.bugtype(recv)
540 end
541 self.add("\}")
542
543 return res
544 end
545
546 redef fun read_attribute(a, recv)
547 do
548 check_recv_notnull(recv)
549
550 var types = self.collect_types(recv)
551
552 var ret = a.intro.static_mtype.as(not null)
553 ret = self.resolve_for(ret, recv)
554 var res = self.new_var(ret)
555
556 if types.is_empty then
557 self.add("/*BUG: no live types for {recv.inspect} . {a}*/")
558 self.bugtype(recv)
559 return res
560 end
561 self.add("/* read {a} on {recv.inspect} */")
562 self.add("switch({recv}->classid) \{")
563 var last = types.last
564 for t in types do
565 if not self.compiler.hardening and t == last then
566 self.add("default: /*{self.compiler.classid(t)}*/")
567 else
568 self.add("case {self.compiler.classid(t)}:")
569 end
570 var recv2 = self.autoadapt(recv, t)
571 var ta = a.intro.static_mtype.as(not null)
572 ta = self.resolve_for(ta, recv2)
573 var res2 = self.new_expr("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta)
574 if not ta isa MNullableType and not self.compiler.modelbuilder.toolcontext.opt_no_check_other.value then
575 if ta.ctype == "val*" then
576 self.add("if ({res2} == NULL) \{")
577 self.add_abort("Uninitialized attribute {a.name}")
578 self.add("\}")
579 else
580 self.add("/*NOTYET isset on primitive attributes*/")
581 end
582 end
583 self.assign(res, res2)
584 self.add("break;")
585 end
586 if self.compiler.hardening then
587 self.add("default: /* Bug */")
588 self.bugtype(recv)
589 end
590 self.add("\}")
591
592 return res
593 end
594
595 redef fun write_attribute(a, recv, value)
596 do
597 check_recv_notnull(recv)
598
599 var types = self.collect_types(recv)
600
601 if types.is_empty then
602 self.add("/*BUG: no live types for {recv.inspect} . {a}*/")
603 self.bugtype(recv)
604 return
605 end
606 self.add("/* write {a} on {recv.inspect} */")
607 self.add("switch({recv}->classid) \{")
608 var last = types.last
609 for t in types do
610 if not self.compiler.hardening and t == last then
611 self.add("default: /*{self.compiler.classid(t)}*/")
612 else
613 self.add("case {self.compiler.classid(t)}:")
614 end
615 var recv2 = self.autoadapt(recv, t)
616 var ta = a.intro.static_mtype.as(not null)
617 ta = self.resolve_for(ta, recv2)
618 self.add("((struct {t.c_name}*){recv})->{a.intro.c_name} = {self.autobox(value, ta)};")
619 self.add("break;")
620 end
621 if self.compiler.hardening then
622 self.add("default: /* Bug*/")
623 self.bugtype(recv)
624 end
625 self.add("\}")
626 end
627
628 redef fun init_instance(mtype)
629 do
630 mtype = self.anchor(mtype).as(MClassType)
631 if not self.compiler.runtime_type_analysis.live_types.has(mtype) then
632 debug "problem: {mtype} was detected dead"
633 end
634 var res = self.new_expr("NEW_{mtype.c_name}()", mtype)
635 res.is_exact = true
636 return res
637 end
638
639 redef fun type_test(value, mtype, tag)
640 do
641 mtype = self.anchor(mtype)
642 var mclasstype = mtype
643 if mtype isa MNullableType then mclasstype = mtype.mtype
644 assert mclasstype isa MClassType
645 if not self.compiler.runtime_type_analysis.live_cast_types.has(mclasstype) then
646 debug "problem: {mtype} was detected cast-dead"
647 abort
648 end
649
650 var types = self.collect_types(value)
651 var res = self.new_var(bool_type)
652
653 self.add("/* isa {mtype} on {value.inspect} */")
654 if value.mtype.ctype != "val*" then
655 if value.mtype.is_subtype(self.compiler.mainmodule, null, mtype) then
656 self.add("{res} = 1;")
657 else
658 self.add("{res} = 0;")
659 end
660 return res
661 end
662 if value.mcasttype isa MNullableType or value.mcasttype isa MNullType then
663 self.add("if ({value} == NULL) \{")
664 if mtype isa MNullableType then
665 self.add("{res} = 1; /* isa {mtype} */")
666 else
667 self.add("{res} = 0; /* not isa {mtype} */")
668 end
669 self.add("\} else ")
670 end
671 self.add("switch({value}->classid) \{")
672 for t in types do
673 if t.is_subtype(self.compiler.mainmodule, null, mtype) then
674 self.add("case {self.compiler.classid(t)}: /* {t} */")
675 end
676 end
677 self.add("{res} = 1;")
678 self.add("break;")
679 self.add("default:")
680 self.add("{res} = 0;")
681 self.add("\}")
682
683 return res
684 end
685
686 redef fun is_same_type_test(value1, value2)
687 do
688 var res = self.new_var(bool_type)
689 if value2.mtype.ctype == "val*" then
690 if value1.mtype.ctype == "val*" then
691 self.add "{res} = {value1}->classid == {value2}->classid;"
692 else
693 self.add "{res} = {self.compiler.classid(value1.mtype.as(MClassType))} == {value2}->classid;"
694 end
695 else
696 if value1.mtype.ctype == "val*" then
697 self.add "{res} = {value1}->classid == {self.compiler.classid(value2.mtype.as(MClassType))};"
698 else if value1.mcasttype == value2.mcasttype then
699 self.add "{res} = 1;"
700 else
701 self.add "{res} = 0;"
702 end
703 end
704 return res
705 end
706
707 redef fun class_name_string(value)
708 do
709 var res = self.get_name("var_class_name")
710 self.add_decl("const char* {res};")
711 if value.mtype.ctype == "val*" then
712 self.add "{res} = class_names[{value}->classid];"
713 else
714 self.add "{res} = class_names[{self.compiler.classid(value.mtype.as(MClassType))}];"
715 end
716 return res
717 end
718
719 redef fun equal_test(value1, value2)
720 do
721 var res = self.new_var(bool_type)
722 if value2.mtype.ctype != "val*" and value1.mtype.ctype == "val*" then
723 var tmp = value1
724 value1 = value2
725 value2 = tmp
726 end
727 if value1.mtype.ctype != "val*" then
728 if value2.mtype == value1.mtype then
729 self.add("{res} = {value1} == {value2};")
730 else if value2.mtype.ctype != "val*" then
731 self.add("{res} = 0; /* incompatible types {value1.mtype} vs. {value2.mtype}*/")
732 else
733 var mtype1 = value1.mtype.as(MClassType)
734 self.add("{res} = ({value2} != NULL) && ({value2}->classid == {self.compiler.classid(mtype1)});")
735 self.add("if ({res}) \{")
736 self.add("{res} = ({self.autobox(value2, value1.mtype)} == {value1});")
737 self.add("\}")
738 end
739 else
740 var s = new Array[String]
741 for t in self.compiler.live_primitive_types do
742 if not t.is_subtype(self.compiler.mainmodule, null, value1.mcasttype) then continue
743 if not t.is_subtype(self.compiler.mainmodule, null, value2.mcasttype) then continue
744 s.add "({value1}->classid == {self.compiler.classid(t)} && ((struct {t.c_name}*){value1})->value == ((struct {t.c_name}*){value2})->value)"
745 end
746 if s.is_empty then
747 self.add("{res} = {value1} == {value2};")
748 else
749 self.add("{res} = {value1} == {value2} || ({value1} != NULL && {value2} != NULL && {value1}->classid == {value2}->classid && ({s.join(" || ")}));")
750 end
751 end
752 return res
753 end
754
755 redef fun check_init_instance(recv, mtype)
756 do
757 if self.compiler.modelbuilder.toolcontext.opt_no_check_initialization.value then return
758
759 mtype = self.anchor(mtype).as(MClassType)
760 if not self.compiler.runtime_type_analysis.live_types.has(mtype) then
761 debug "problem: {mtype} was detected dead"
762 end
763
764 self.add("CHECK_NEW_{mtype.c_name}({recv});")
765 end
766
767 redef fun array_instance(array, elttype)
768 do
769 elttype = self.anchor(elttype)
770 var arraytype = self.get_class("Array").get_mtype([elttype])
771 var res = self.init_instance(arraytype)
772 self.add("\{ /* {res} = array_instance Array[{elttype}] */")
773 var nat = self.new_var(self.get_class("NativeArray").get_mtype([elttype]))
774 nat.is_exact = true
775 self.add("{nat} = NEW_{nat.mtype.c_name}({array.length});")
776 for i in [0..array.length[ do
777 var r = self.autobox(array[i], elttype)
778 self.add("((struct {nat.mtype.c_name}*) {nat})->values[{i}] = {r};")
779 end
780 var length = self.int_instance(array.length)
781 self.send(self.get_property("with_native", arraytype), [res, nat, length])
782 self.check_init_instance(res, arraytype)
783 self.add("\}")
784 return res
785 end
786 end
787
788 # A runtime function customized on a specific monomrph receiver type
789 private class CustomizedRuntimeFunction
790 super AbstractRuntimeFunction
791
792 redef type COMPILER: GlobalCompiler
793 redef type VISITOR: GlobalCompilerVisitor
794
795 # The considered reciever
796 # (usually is a live type but no strong guarantee)
797 var recv: MClassType
798
799 init(mmethoddef: MMethodDef, recv: MClassType)
800 do
801 super(mmethoddef)
802 self.recv = recv
803 end
804
805 redef fun build_c_name
806 do
807 var res = self.c_name_cache
808 if res != null then return res
809 if self.mmethoddef.mclassdef.bound_mtype == self.recv then
810 res = self.mmethoddef.c_name
811 else
812 res = "{mmethoddef.c_name}__{recv.c_name}"
813 end
814 self.c_name_cache = res
815 return res
816 end
817
818 # used in the compiler worklist
819 redef fun ==(o)
820 do
821 if not o isa CustomizedRuntimeFunction then return false
822 if self.mmethoddef != o.mmethoddef then return false
823 if self.recv != o.recv then return false
824 return true
825 end
826
827 # used in the compiler work-list
828 redef fun hash do return self.mmethoddef.hash + self.recv.hash
829
830 redef fun to_s
831 do
832 if self.mmethoddef.mclassdef.bound_mtype == self.recv then
833 return self.mmethoddef.to_s
834 else
835 return "{self.mmethoddef}@{self.recv}"
836 end
837 end
838
839 # compile the code customized for the reciever
840 redef fun compile_to_c(compiler)
841 do
842 var recv = self.recv
843 var mmethoddef = self.mmethoddef
844 if not recv.is_subtype(compiler.mainmodule, null, mmethoddef.mclassdef.bound_mtype) then
845 print("problem: why do we compile {self} for {recv}?")
846 abort
847 end
848
849 var v = compiler.new_visitor
850 var selfvar = new RuntimeVariable("self", recv, recv)
851 if compiler.runtime_type_analysis.live_types.has(recv) then
852 selfvar.is_exact = true
853 end
854 var arguments = new Array[RuntimeVariable]
855 var frame = new Frame(v, mmethoddef, recv, arguments)
856 v.frame = frame
857
858 var sig = new Buffer
859 var comment = new Buffer
860 var ret = mmethoddef.msignature.return_mtype
861 if ret != null then
862 ret = v.resolve_for(ret, selfvar)
863 sig.append("{ret.ctype} ")
864 else if mmethoddef.mproperty.is_new then
865 ret = recv
866 sig.append("{ret.ctype} ")
867 else
868 sig.append("void ")
869 end
870 sig.append(self.c_name)
871 sig.append("({recv.ctype} {selfvar}")
872 comment.append("(self: {recv}")
873 arguments.add(selfvar)
874 for i in [0..mmethoddef.msignature.arity[ do
875 var mtype = mmethoddef.msignature.mparameters[i].mtype
876 if i == mmethoddef.msignature.vararg_rank then
877 mtype = v.get_class("Array").get_mtype([mtype])
878 end
879 mtype = v.resolve_for(mtype, selfvar)
880 comment.append(", {mtype}")
881 sig.append(", {mtype.ctype} p{i}")
882 var argvar = new RuntimeVariable("p{i}", mtype, mtype)
883 arguments.add(argvar)
884 end
885 sig.append(")")
886 comment.append(")")
887 if ret != null then
888 comment.append(": {ret}")
889 end
890 compiler.header.add_decl("{sig};")
891
892 v.add_decl("/* method {self} for {comment} */")
893 v.add_decl("{sig} \{")
894 #v.add("printf(\"method {self} for {comment}\\n\");")
895 if ret != null then
896 frame.returnvar = v.new_var(ret)
897 end
898 frame.returnlabel = v.get_name("RET_LABEL")
899
900 mmethoddef.compile_inside_to_c(v, arguments)
901
902 v.add("{frame.returnlabel.as(not null)}:;")
903 if ret != null then
904 v.add("return {frame.returnvar.as(not null)};")
905 end
906 v.add("\}")
907 end
908
909 redef fun call(v: VISITOR, arguments: Array[RuntimeVariable]): nullable RuntimeVariable
910 do
911 var ret = self.mmethoddef.msignature.return_mtype
912 if self.mmethoddef.mproperty.is_new then
913 ret = recv
914 end
915 if ret != null then
916 ret = v.resolve_for(ret, arguments.first)
917 end
918 if self.mmethoddef.can_inline(v) then
919 var frame = new Frame(v, self.mmethoddef, self.recv, arguments)
920 frame.returnlabel = v.get_name("RET_LABEL")
921 if ret != null then
922 frame.returnvar = v.new_var(ret)
923 end
924 var old_frame = v.frame
925 v.frame = frame
926 v.add("\{ /* Inline {self} ({arguments.join(",")}) */")
927 self.mmethoddef.compile_inside_to_c(v, arguments)
928 v.add("{frame.returnlabel.as(not null)}:(void)0;")
929 v.add("\}")
930 v.frame = old_frame
931 return frame.returnvar
932 end
933 v.adapt_signature(self.mmethoddef, arguments)
934 v.compiler.todo(self)
935 if ret == null then
936 v.add("{self.c_name}({arguments.join(",")});")
937 return null
938 else
939 var res = v.new_var(ret)
940 v.add("{res} = {self.c_name}({arguments.join(",")});")
941 return res
942 end
943 end
944 end