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