Callref bugfix in interpreter and compilers + autosav
[nit.git] / src / compiler / 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 ToolContext
30 # option --global
31 var opt_global = new OptionBool("Use global compilation", "--global")
32
33 var global_compiler_phase = new GlobalCompilerPhase(self, null)
34
35 redef init do
36 super
37 option_context.add_option(opt_global)
38 end
39 end
40
41 class GlobalCompilerPhase
42 super Phase
43 redef fun process_mainmodule(mainmodule, given_mmodules) do
44 if not toolcontext.opt_global.value then return
45
46 var modelbuilder = toolcontext.modelbuilder
47 var analysis = modelbuilder.do_rapid_type_analysis(mainmodule)
48 modelbuilder.run_global_compiler(mainmodule, analysis)
49 end
50 end
51
52 redef class ModelBuilder
53 # Entry point to performs a global compilation on the AST of a complete program.
54 # `mainmodule` is the main module of the program
55 # `runtime_type_analysis` is a already computer type analysis.
56 fun run_global_compiler(mainmodule: MModule, runtime_type_analysis: RapidTypeAnalysis)
57 do
58 var time0 = get_time
59 self.toolcontext.info("*** GENERATING C ***", 1)
60
61 var compiler = new GlobalCompiler(mainmodule, self, runtime_type_analysis)
62 compiler.do_compilation
63 compiler.display_stats
64
65 var time1 = get_time
66 self.toolcontext.info("*** END GENERATING C: {time1-time0} ***", 2)
67 write_and_make(compiler)
68 end
69 end
70
71 # Compiler that use global compilation and perform hard optimisations like:
72 # * customization
73 # * switch dispatch
74 # * inlining
75 class GlobalCompiler
76 super AbstractCompiler
77
78 redef type VISITOR: GlobalCompilerVisitor
79
80 # The result of the RTA (used to know live types and methods)
81 var runtime_type_analysis: RapidTypeAnalysis
82
83 init
84 do
85 var file = new_file("{mainmodule.c_name}.nitgg")
86 self.header = new CodeWriter(file)
87 self.live_primitive_types = new Array[MClassType]
88 for t in runtime_type_analysis.live_types do
89 if t.is_c_primitive or t.mclass.name == "Pointer" then
90 self.live_primitive_types.add(t)
91 end
92 end
93 end
94
95 redef fun do_compilation
96 do
97 var compiler = self
98
99 compiler.compile_header
100
101 if mainmodule.model.get_mclasses_by_name("Pointer") != null then
102 runtime_type_analysis.live_types.add(mainmodule.pointer_type)
103 end
104 for t in runtime_type_analysis.live_types do
105 compiler.declare_runtimeclass(t)
106 end
107
108 compiler.compile_class_names
109
110 # Init instance code (allocate and init-arguments)
111 for t in runtime_type_analysis.live_types do
112 if not t.is_c_primitive then
113 compiler.generate_init_instance(t)
114 if t.mclass.kind == extern_kind then
115 compiler.generate_box_instance(t)
116 end
117 else
118 compiler.generate_box_instance(t)
119 end
120 end
121
122 # The main function of the C
123 compiler.compile_nitni_global_ref_functions
124 compiler.compile_main_function
125
126 # Compile until all runtime_functions are visited
127 while not compiler.todos.is_empty do
128 var m = compiler.todos.shift
129 modelbuilder.toolcontext.info("Compile {m} ({compiler.seen.length-compiler.todos.length}/{compiler.seen.length})", 3)
130 m.compile_to_c(compiler)
131 end
132 modelbuilder.toolcontext.info("Total methods to compile to C: {compiler.seen.length}", 2)
133
134 end
135
136 # Compile class names (for the class_name and output_class_name methods)
137 protected fun compile_class_names do
138 var v = new_visitor
139 self.header.add_decl("extern const char *class_names[];")
140 v.add("const char *class_names[] = \{")
141 for t in self.runtime_type_analysis.live_types do
142 v.add("\"{t}\", /* {self.classid(t)} */")
143 end
144 v.add("\};")
145 end
146
147 # Return the C symbol associated to a live type runtime
148 # REQUIRE: self.runtime_type_analysis.live_types.has(mtype)
149 fun classid(mtype: MClassType): String
150 do
151 if self.classids.has_key(mtype) then
152 return self.classids[mtype]
153 end
154 print_error "No classid for {mtype}"
155 abort
156 end
157
158 # Cache for classid
159 protected var classids: HashMap[MClassType, String] = new HashMap[MClassType, String]
160
161 # Declaration of structures the live Nit types
162 # Each live type is generated as an independent C `struct` type.
163 # They only share a common first field `classid` used to implement the polymorphism.
164 # Usualy, all C variables that refers to a Nit object are typed on the abstract struct `val` that contains only the `classid` field.
165 redef fun compile_header_structs do
166 self.header.add_decl("typedef struct \{int classid;\} val; /* general C type representing a Nit instance. */")
167 end
168
169 # Subset of runtime_type_analysis.live_types that contains only primitive types
170 # Used to implement the equal test
171 var live_primitive_types: Array[MClassType] is noinit
172
173 # Add a new todo task
174 fun todo(m: AbstractRuntimeFunction)
175 do
176 if seen.has(m) then return
177 todos.add(m)
178 seen.add(m)
179 end
180
181 # runtime_functions that need to be compiled
182 private var todos: List[AbstractRuntimeFunction] = new List[AbstractRuntimeFunction]
183
184 # runtime_functions already seen (todo or done)
185 private var seen: HashSet[AbstractRuntimeFunction] = new HashSet[AbstractRuntimeFunction]
186
187 # Declare C structures and identifiers for a runtime class
188 fun declare_runtimeclass(mtype: MClassType)
189 do
190 var v = self.header
191 assert self.runtime_type_analysis.live_types.has(mtype)
192 v.add_decl("/* runtime class {mtype} */")
193 var idnum = classids.length
194 var idname = "ID_" + mtype.c_name
195 self.classids[mtype] = idname
196 v.add_decl("#define {idname} {idnum} /* {mtype} */")
197
198 v.add_decl("struct {mtype.c_name} \{")
199 v.add_decl("int classid; /* must be {idname} */")
200
201 if mtype.mclass.name == "NativeArray" then
202 # NativeArrays are just a instance header followed by an array of values
203 v.add_decl("int length;")
204 v.add_decl("{mtype.arguments.first.ctype} values[1];")
205 end
206
207 if all_routine_types_name.has(mtype.mclass.name) then
208 v.add_decl("val* recv;")
209 var c_args = ["val* self"]
210 var c_ret = "void"
211 var k = mtype.arguments.length
212 if mtype.mclass.name.has("Fun") then
213 c_ret = mtype.arguments.last.ctype
214 k -= 1
215 end
216 for i in [0..k[ do
217 var t = mtype.arguments[i]
218 c_args.push("{t.ctype} p{i}")
219 end
220 var c_sig = c_args.join(", ")
221 v.add_decl("{c_ret} (*method)({c_sig});")
222 end
223
224 if mtype.ctype_extern != "val*" then
225 # Is the Nit type is native then the struct is a box with two fields:
226 # * the `classid` to be polymorph
227 # * the `value` that contains the native value.
228 v.add_decl("{mtype.ctype_extern} value;")
229 end
230
231 # Collect all attributes and associate them a field in the structure.
232 # Note: we do not try to optimize the order and helps CC to optimize the client code.
233 for cd in mtype.collect_mclassdefs(self.mainmodule) do
234 for p in cd.intro_mproperties do
235 if not p isa MAttribute then continue
236 var t = p.intro.static_mtype.as(not null)
237 t = t.anchor_to(self.mainmodule, mtype)
238 v.add_decl("{t.ctype} {p.intro.c_name}; /* {p}: {t} */")
239 end
240 end
241 v.add_decl("\};")
242 end
243
244 # Generate the init-instance of a live type (allocate + init-instance)
245 fun generate_init_instance(mtype: MClassType)
246 do
247 assert self.runtime_type_analysis.live_types.has(mtype)
248 assert not mtype.is_c_primitive
249 var v = self.new_visitor
250
251 var is_native_array = mtype.mclass.name == "NativeArray"
252 var is_routine_ref = all_routine_types_name.has(mtype.mclass.name)
253 var sig
254 if is_native_array then
255 sig = "int length"
256 else
257 sig = "void"
258 end
259 if is_routine_ref then
260 var c_args = ["val* self"]
261 var c_ret = "void"
262 var k = mtype.arguments.length
263 if mtype.mclass.name.has("Fun") then
264 c_ret = mtype.arguments.last.ctype
265 k -= 1
266 end
267 for i in [0..k[ do
268 var t = mtype.arguments[i]
269 c_args.push("{t.ctype} p{i}")
270 end
271 # The underlying method signature
272 var method_sig = "{c_ret} (*method)({c_args.join(", ")})"
273 sig = "val* recv, {method_sig}"
274 end
275
276 self.header.add_decl("{mtype.ctype} NEW_{mtype.c_name}({sig});")
277 v.add_decl("/* allocate {mtype} */")
278 v.add_decl("{mtype.ctype} NEW_{mtype.c_name}({sig}) \{")
279 var res = v.new_var(mtype)
280 res.is_exact = true
281 if is_native_array then
282 v.add("{res} = nit_alloc(sizeof(struct {mtype.c_name}) + length*sizeof(val*));")
283 v.add("((struct {mtype.c_name}*){res})->length = length;")
284 else
285 v.add("{res} = nit_alloc(sizeof(struct {mtype.c_name}));")
286 end
287 if is_routine_ref then
288 v.add("((struct {mtype.c_name}*){res})->recv = recv;")
289 v.add("((struct {mtype.c_name}*){res})->method = method;")
290 end
291 v.add("{res}->classid = {self.classid(mtype)};")
292
293 self.generate_init_attr(v, res, mtype)
294 v.set_finalizer res
295 v.add("return {res};")
296 v.add("\}")
297 end
298
299 fun generate_box_instance(mtype: MClassType)
300 do
301 assert self.runtime_type_analysis.live_types.has(mtype)
302 var v = self.new_visitor
303
304 self.header.add_decl("val* BOX_{mtype.c_name}({mtype.ctype});")
305 v.add_decl("/* allocate {mtype} */")
306 v.add_decl("val* BOX_{mtype.c_name}({mtype.ctype} value) \{")
307 v.add("struct {mtype.c_name}*res = nit_alloc(sizeof(struct {mtype.c_name}));")
308 v.add("res->classid = {self.classid(mtype)};")
309 v.add("res->value = value;")
310 v.add("return (val*)res;")
311 v.add("\}")
312 end
313
314 redef fun new_visitor do return new GlobalCompilerVisitor(self)
315
316 private var collect_types_cache: HashMap[MType, Array[MClassType]] = new HashMap[MType, Array[MClassType]]
317
318 redef fun compile_nitni_structs
319 do
320 self.header.add_decl """
321 struct nitni_instance \{
322 struct nitni_instance *next,
323 *prev; /* adjacent global references in global list */
324 int count; /* number of time this global reference has been marked */
325 val *value;
326 \};"""
327 super
328 end
329 end
330
331 # A visitor on the AST of property definition that generate the C code.
332 # Because of inlining, a visitor can visit more than one property.
333 class GlobalCompilerVisitor
334 super AbstractCompilerVisitor
335
336 redef type COMPILER: GlobalCompiler
337
338 redef fun autobox(value, mtype)
339 do
340 if value.mtype == mtype then
341 return value
342 else if not value.mtype.is_c_primitive and not mtype.is_c_primitive then
343 return value
344 else if not value.mtype.is_c_primitive then
345 return self.new_expr("((struct {mtype.c_name}*){value})->value; /* autounbox from {value.mtype} to {mtype} */", mtype)
346 else if not mtype.is_c_primitive then
347 var valtype = value.mtype.as(MClassType)
348 var res = self.new_var(mtype)
349 if not compiler.runtime_type_analysis.live_types.has(valtype) then
350 self.add("/*no autobox from {value.mtype} to {mtype}: {value.mtype} is not live! */")
351 self.add("PRINT_ERROR(\"Dead code executed!\\n\"); fatal_exit(1);")
352 return res
353 end
354 self.add("{res} = BOX_{valtype.c_name}({value}); /* autobox from {value.mtype} to {mtype} */")
355 return res
356 else if value.mtype.ctype == "void*" and mtype.ctype == "void*" then
357 return value
358 else
359 # Bad things will appen!
360 var res = self.new_var(mtype)
361 self.add("/* {res} left unintialized (cannot convert {value.mtype} to {mtype}) */")
362 self.add("PRINT_ERROR(\"Cast error: Cannot cast %s to %s.\\n\", \"{value.mtype}\", \"{mtype}\"); fatal_exit(1);")
363 return res
364 end
365 end
366
367 redef fun unbox_extern(value, mtype)
368 do
369 if mtype isa MClassType and mtype.mclass.kind == extern_kind and
370 mtype.mclass.name != "CString" then
371 var res = self.new_var_extern(mtype)
372 self.add "{res} = ((struct {mtype.c_name}*){value})->value; /* unboxing {value.mtype} */"
373 return res
374 else
375 return value
376 end
377 end
378
379 redef fun box_extern(value, mtype)
380 do
381 if not mtype isa MClassType or mtype.mclass.kind != extern_kind or
382 mtype.mclass.name == "CString" then return value
383
384 var valtype = value.mtype.as(MClassType)
385 var res = self.new_var(mtype)
386 if not compiler.runtime_type_analysis.live_types.has(value.mtype.as(MClassType)) then
387 self.add("/*no boxing of {value.mtype}: {value.mtype} is not live! */")
388 self.add("PRINT_ERROR(\"Dead code executed!\\n\"); fatal_exit(1);")
389 return res
390 end
391 self.add("{res} = BOX_{valtype.c_name}({value}); /* boxing {value.mtype} */")
392 return res
393 end
394
395 # The runtime types that are acceptable for a given receiver.
396 fun collect_types(recv: RuntimeVariable): Array[MClassType]
397 do
398 var mtype = recv.mcasttype
399 if recv.is_exact then
400 assert mtype isa MClassType
401 assert self.compiler.runtime_type_analysis.live_types.has(mtype)
402 var types = [mtype]
403 return types
404 end
405 var cache = self.compiler.collect_types_cache
406 if cache.has_key(mtype) then
407 return cache[mtype]
408 end
409 var types = new Array[MClassType]
410 var mainmodule = self.compiler.mainmodule
411 for t in self.compiler.runtime_type_analysis.live_types do
412 if not t.is_subtype(mainmodule, null, mtype) then continue
413 types.add(t)
414 end
415 cache[mtype] = types
416 return types
417 end
418
419 redef fun native_array_def(pname, ret_type, arguments)
420 do
421 var elttype = arguments.first.mtype
422 var recv = "((struct {arguments[0].mcasttype.c_name}*){arguments[0]})->values"
423 if pname == "[]" then
424 self.ret(self.new_expr("{recv}[{arguments[1]}]", ret_type.as(not null)))
425 return true
426 else if pname == "[]=" then
427 self.add("{recv}[{arguments[1]}]={arguments[2]};")
428 return true
429 else if pname == "length" then
430 self.ret(self.new_expr("((struct {arguments[0].mcasttype.c_name}*){arguments[0]})->length", ret_type.as(not null)))
431 return true
432 else if pname == "copy_to" then
433 var recv1 = "((struct {arguments[1].mcasttype.c_name}*){arguments[1]})->values"
434 self.add("memmove({recv1},{recv},{arguments[2]}*sizeof({elttype.ctype}));")
435 return true
436 else if pname == "memmove" then
437 # fun memmove(start: Int, length: Int, dest: NativeArray[E], dest_start: Int) is intern do
438 var recv1 = "((struct {arguments[3].mcasttype.c_name}*){arguments[3]})->values"
439 self.add("memmove({recv1}+{arguments[4]}, {recv}+{arguments[1]}, {arguments[2]}*sizeof({elttype.ctype}));")
440 return true
441 end
442 return false
443 end
444
445 redef fun native_array_instance(elttype, length)
446 do
447 var ret_type = mmodule.native_array_type(elttype)
448 ret_type = anchor(ret_type).as(MClassType)
449 length = autobox(length, compiler.mainmodule.int_type)
450 return self.new_expr("NEW_{ret_type.c_name}((int){length})", ret_type)
451 end
452
453 redef fun native_array_get(nat, i)
454 do
455 var recv = "((struct {nat.mcasttype.c_name}*){nat})->values"
456 var ret_type = nat.mcasttype.as(MClassType).arguments.first
457 return self.new_expr("{recv}[{i}]", ret_type)
458 end
459
460 redef fun native_array_set(nat, i, val)
461 do
462 var recv = "((struct {nat.mcasttype.c_name}*){nat})->values"
463 self.add("{recv}[{i}]={val};")
464 end
465
466 redef fun routine_ref_instance(routine_mclass_type, recv, callsite)
467 do
468 var mmethoddef = callsite.mpropdef
469 var method = new CustomizedRuntimeFunction(mmethoddef, recv.mcasttype.as(MClassType))
470 var my_recv = recv
471 if recv.mtype.is_c_primitive then
472 var object_type = mmodule.object_type
473 my_recv = autobox(recv, object_type)
474 end
475 var thunk = new CustomizedThunkFunction(mmethoddef, my_recv.mtype.as(MClassType))
476 thunk.polymorph_call_flag = not my_recv.is_exact
477 compiler.todo(method)
478 compiler.todo(thunk)
479 var ret_type = self.anchor(routine_mclass_type).as(MClassType)
480 var res = self.new_expr("NEW_{ret_type.c_name}({my_recv}, &{thunk.c_name})", ret_type)
481 return res
482 end
483
484 redef fun routine_ref_call(mmethoddef, arguments)
485 do
486 var routine = arguments.first
487 var routine_type = routine.mtype.as(MClassType)
488 var routine_class = routine_type.mclass
489 var underlying_recv = "((struct {routine.mcasttype.c_name}*){routine})->recv"
490 var underlying_method = "((struct {routine.mcasttype.c_name}*){routine})->method"
491 adapt_signature(mmethoddef, arguments)
492 arguments.shift
493 var ss = "{underlying_recv}"
494 if arguments.length > 0 then
495 ss = "{ss}, {arguments.join(", ")}"
496 end
497 arguments.unshift routine
498
499 var ret_mtype = mmethoddef.msignature.return_mtype
500
501 if ret_mtype != null then
502 ret_mtype = resolve_for(ret_mtype, routine)
503 end
504 var callsite = "{underlying_method}({ss})"
505 if ret_mtype != null then
506 var subres = new_expr("{callsite}", ret_mtype)
507 ret(subres)
508 else
509 add("{callsite};")
510 end
511 end
512
513 redef fun send(m, args)
514 do
515 var types = self.collect_types(args.first)
516
517 var res: nullable RuntimeVariable
518 var ret = m.intro.msignature.return_mtype
519 if ret == null then
520 res = null
521 else
522 ret = self.resolve_for(ret, args.first)
523 res = self.new_var(ret)
524 end
525
526 self.add("/* send {m} on {args.first.inspect} */")
527 if args.first.mtype.is_c_primitive then
528 var mclasstype = args.first.mtype.as(MClassType)
529 if not self.compiler.runtime_type_analysis.live_types.has(mclasstype) then
530 self.add("/* skip, dead class {mclasstype} */")
531 return res
532 end
533 if not mclasstype.has_mproperty(self.compiler.mainmodule, m) then
534 self.add("/* skip, no method {m} */")
535 return res
536 end
537 var propdef = m.lookup_first_definition(self.compiler.mainmodule, mclasstype)
538 var res2 = self.call(propdef, mclasstype, args)
539 if res != null then self.assign(res, res2.as(not null))
540 return res
541 end
542 var consider_null = not self.compiler.modelbuilder.toolcontext.opt_no_check_null.value or m.name == "==" or m.name == "!="
543 if args.first.mcasttype isa MNullableType or args.first.mcasttype isa MNullType and consider_null then
544 # The reciever is potentially null, so we have to 3 cases: ==, != or NullPointerException
545 self.add("if ({args.first} == NULL) \{ /* Special null case */")
546 if m.name == "==" or m.name == "is_same_instance" then
547 assert res != null
548 if args[1].mcasttype isa MNullableType then
549 self.add("{res} = ({args[1]} == NULL);")
550 else if args[1].mcasttype isa MNullType then
551 self.add("{res} = 1; /* is null */")
552 else
553 self.add("{res} = 0; /* {args[1].inspect} cannot be null */")
554 end
555 else if m.name == "!=" then
556 assert res != null
557 if args[1].mcasttype isa MNullableType then
558 self.add("{res} = ({args[1]} != NULL);")
559 else if args[1].mcasttype isa MNullType then
560 self.add("{res} = 0; /* is null */")
561 else
562 self.add("{res} = 1; /* {args[1].inspect} cannot be null */")
563 end
564 else
565 self.add_abort("Receiver is null")
566 end
567 self.add "\} else"
568 end
569 if types.is_empty then
570 self.add("\{")
571 self.add("/*BUG: no live types for {args.first.inspect} . {m}*/")
572 self.bugtype(args.first)
573 self.add("\}")
574 return res
575 end
576
577 self.add("switch({args.first}->classid) \{")
578 var last = types.last
579 var defaultpropdef: nullable MMethodDef = null
580 for t in types do
581 var propdef = m.lookup_first_definition(self.compiler.mainmodule, t)
582 if propdef.mclassdef.mclass.name == "Object" and not t.is_c_primitive then
583 defaultpropdef = propdef
584 continue
585 end
586 if not self.compiler.hardening and t == last and defaultpropdef == null then
587 self.add("default: /* test {t} */")
588 else
589 self.add("case {self.compiler.classid(t)}: /* test {t} */")
590 end
591 var res2 = self.call(propdef, t, args)
592 if res != null then self.assign(res, res2.as(not null))
593 self.add "break;"
594 end
595 if defaultpropdef != null then
596 self.add("default: /* default is Object */")
597 var res2 = self.call(defaultpropdef, defaultpropdef.mclassdef.bound_mtype, args)
598 if res != null then self.assign(res, res2.as(not null))
599 else if self.compiler.hardening then
600 self.add("default: /* bug */")
601 self.bugtype(args.first)
602 end
603 self.add("\}")
604 return res
605 end
606
607 fun check_valid_reciever(recvtype: MClassType)
608 do
609 if self.compiler.runtime_type_analysis.live_types.has(recvtype) or recvtype.mclass.name == "Object" then return
610 print_error "{recvtype} is not a live type"
611 abort
612 end
613
614 # Subpart of old call function
615 #
616 # Checks if the type of the receiver is valid and corrects it if necessary
617 private fun get_recvtype(m: MMethodDef, recvtype: MClassType, args: Array[RuntimeVariable]): MClassType
618 do
619 check_valid_reciever(recvtype)
620 return recvtype
621 end
622
623 redef fun call(m, recvtype, args)
624 do
625 var recv_type = get_recvtype(m, recvtype, args)
626 var recv = self.autoadapt(self.autobox(args.first, recvtype), recvtype)
627 if m.is_extern then recv = unbox_extern(recv, recv_type)
628
629 args = args.to_a
630 args.first = recv
631
632 assert args.length == m.msignature.arity + 1 else debug("Invalid arity for {m}. {args.length} arguments given.")
633
634 var rm = new CustomizedRuntimeFunction(m, recvtype)
635 return rm.call(self, args)
636 end
637
638 redef fun supercall(m: MMethodDef, recvtype: MClassType, args: Array[RuntimeVariable]): nullable RuntimeVariable
639 do
640 var types = self.collect_types(args.first)
641
642 var res: nullable RuntimeVariable
643 var ret = m.mproperty.intro.msignature.return_mtype
644 if ret == null then
645 res = null
646 else
647 ret = self.resolve_for(ret, args.first)
648 res = self.new_var(ret)
649 end
650
651 self.add("/* super {m} on {args.first.inspect} */")
652 if args.first.mtype.is_c_primitive then
653 var mclasstype = args.first.mtype.as(MClassType)
654 if not self.compiler.runtime_type_analysis.live_types.has(mclasstype) then
655 self.add("/* skip, no method {m} */")
656 return res
657 end
658 var propdef = m.lookup_next_definition(self.compiler.mainmodule, mclasstype)
659 var res2 = self.call(propdef, mclasstype, args)
660 if res != null then self.assign(res, res2.as(not null))
661 return res
662 end
663
664 if types.is_empty then
665 self.add("\{")
666 self.add("/*BUG: no live types for {args.first.inspect} . {m}*/")
667 self.bugtype(args.first)
668 self.add("\}")
669 return res
670 end
671
672 self.add("switch({args.first}->classid) \{")
673 var last = types.last
674 for t in types do
675 var propdef = m.lookup_next_definition(self.compiler.mainmodule, t)
676 if not self.compiler.hardening and t == last then
677 self.add("default: /* test {t} */")
678 else
679 self.add("case {self.compiler.classid(t)}: /* test {t} */")
680 end
681 var res2 = self.call(propdef, t, args)
682 if res != null then self.assign(res, res2.as(not null))
683 self.add "break;"
684 end
685 if self.compiler.hardening then
686 self.add("default: /* bug */")
687 self.bugtype(args.first)
688 end
689 self.add("\}")
690 return res
691 end
692
693 redef fun adapt_signature(m, args)
694 do
695 var recv = args.first
696 for i in [0..m.msignature.arity[ do
697 var mp = m.msignature.mparameters[i]
698 var t = mp.mtype
699 if mp.is_vararg then
700 t = args[i+1].mtype
701 end
702 t = self.resolve_for(t, recv)
703 args[i+1] = self.autobox(args[i+1], t)
704 end
705 end
706
707 redef fun unbox_signature_extern(m, args)
708 do
709 var recv = args.first
710 for i in [0..m.msignature.arity[ do
711 var mp = m.msignature.mparameters[i]
712 var t = mp.mtype
713 if mp.is_vararg then
714 t = args[i+1].mtype
715 end
716 t = self.resolve_for(t, recv)
717 if m.is_extern then args[i+1] = self.unbox_extern(args[i+1], t)
718 end
719 end
720
721 # FIXME: this is currently buggy since recv is not exact
722 redef fun vararg_instance(mpropdef, recv, varargs, elttype)
723 do
724 elttype = self.resolve_for(elttype, recv)
725 return self.array_instance(varargs, elttype)
726 end
727
728 fun bugtype(recv: RuntimeVariable)
729 do
730 if recv.mtype.is_c_primitive then return
731 self.add("PRINT_ERROR(\"BTD BUG: Dynamic type is %s, static type is %s\\n\", class_names[{recv}->classid], \"{recv.mcasttype}\");")
732 self.add("fatal_exit(1);")
733 end
734
735 redef fun isset_attribute(a, recv)
736 do
737 check_recv_notnull(recv)
738
739 var types = self.collect_types(recv)
740 var res = self.new_var(bool_type)
741
742 if types.is_empty then
743 self.add("/*BUG: no live types for {recv.inspect} . {a}*/")
744 self.bugtype(recv)
745 return res
746 end
747 self.add("/* isset {a} on {recv.inspect} */")
748 self.add("switch({recv}->classid) \{")
749 var last = types.last
750 for t in types do
751 if not self.compiler.hardening and t == last then
752 self.add("default: /*{self.compiler.classid(t)}*/")
753 else
754 self.add("case {self.compiler.classid(t)}:")
755 end
756 var recv2 = self.autoadapt(recv, t)
757 var ta = a.intro.static_mtype.as(not null)
758 ta = self.resolve_for(ta, recv2)
759 var attr = self.new_expr("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta)
760 if not ta isa MNullableType then
761 if not ta.is_c_primitive then
762 self.add("{res} = ({attr} != NULL);")
763 else
764 self.add("{res} = 1; /*NOTYET isset on primitive attributes*/")
765 end
766 end
767 self.add("break;")
768 end
769 if self.compiler.hardening then
770 self.add("default: /* Bug */")
771 self.bugtype(recv)
772 end
773 self.add("\}")
774
775 return res
776 end
777
778 redef fun read_attribute(a, recv)
779 do
780 check_recv_notnull(recv)
781
782 var types = self.collect_types(recv)
783
784 var ret = a.intro.static_mtype.as(not null)
785 ret = self.resolve_for(ret, recv)
786 var res = self.new_var(ret)
787
788 if types.is_empty then
789 self.add("/*BUG: no live types for {recv.inspect} . {a}*/")
790 self.bugtype(recv)
791 return res
792 end
793 self.add("/* read {a} on {recv.inspect} */")
794 self.add("switch({recv}->classid) \{")
795 var last = types.last
796 for t in types do
797 if not self.compiler.hardening and t == last then
798 self.add("default: /*{self.compiler.classid(t)}*/")
799 else
800 self.add("case {self.compiler.classid(t)}:")
801 end
802 var recv2 = self.autoadapt(recv, t)
803 var ta = a.intro.static_mtype.as(not null)
804 ta = self.resolve_for(ta, recv2)
805 var res2 = self.new_expr("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta)
806 if not ta isa MNullableType and not self.compiler.modelbuilder.toolcontext.opt_no_check_attr_isset.value then
807 if not ta.is_c_primitive then
808 self.add("if ({res2} == NULL) \{")
809 self.add_abort("Uninitialized attribute {a.name}")
810 self.add("\}")
811 else
812 self.add("/*NOTYET isset on primitive attributes*/")
813 end
814 end
815 self.assign(res, res2)
816 self.add("break;")
817 end
818 if self.compiler.hardening then
819 self.add("default: /* Bug */")
820 self.bugtype(recv)
821 end
822 self.add("\}")
823
824 return res
825 end
826
827 redef fun write_attribute(a, recv, value)
828 do
829 check_recv_notnull(recv)
830
831 var types = self.collect_types(recv)
832
833 if types.is_empty then
834 self.add("/*BUG: no live types for {recv.inspect} . {a}*/")
835 self.bugtype(recv)
836 return
837 end
838 self.add("/* write {a} on {recv.inspect} */")
839 self.add("switch({recv}->classid) \{")
840 var last = types.last
841 for t in types do
842 if not self.compiler.hardening and t == last then
843 self.add("default: /*{self.compiler.classid(t)}*/")
844 else
845 self.add("case {self.compiler.classid(t)}:")
846 end
847 var recv2 = self.autoadapt(recv, t)
848 var ta = a.intro.static_mtype.as(not null)
849 ta = self.resolve_for(ta, recv2)
850 self.add("((struct {t.c_name}*){recv})->{a.intro.c_name} = {self.autobox(value, ta)};")
851 self.add("break;")
852 end
853 if self.compiler.hardening then
854 self.add("default: /* Bug*/")
855 self.bugtype(recv)
856 end
857 self.add("\}")
858 end
859
860 redef fun init_instance(mtype)
861 do
862 mtype = self.anchor(mtype).as(MClassType)
863 if not self.compiler.runtime_type_analysis.live_types.has(mtype) then
864 debug "problem: {mtype} was detected dead"
865 end
866 var res = self.new_expr("NEW_{mtype.c_name}()", mtype)
867 res.is_exact = true
868 return res
869 end
870
871 redef fun type_test(value, mtype, tag)
872 do
873 mtype = self.anchor(mtype)
874 if not self.compiler.runtime_type_analysis.live_cast_types.has(mtype) then
875 debug "problem: {mtype} was detected cast-dead"
876 abort
877 end
878
879 var types = self.collect_types(value)
880 var res = self.new_var(bool_type)
881
882 self.add("/* isa {mtype} on {value.inspect} */")
883 if value.mtype.is_c_primitive then
884 if value.mtype.is_subtype(self.compiler.mainmodule, null, mtype) then
885 self.add("{res} = 1;")
886 else
887 self.add("{res} = 0;")
888 end
889 return res
890 end
891 if value.mcasttype isa MNullableType or value.mcasttype isa MNullType then
892 self.add("if ({value} == NULL) \{")
893 if mtype isa MNullableType then
894 self.add("{res} = 1; /* isa {mtype} */")
895 else
896 self.add("{res} = 0; /* not isa {mtype} */")
897 end
898 self.add("\} else ")
899 end
900 self.add("switch({value}->classid) \{")
901 for t in types do
902 if t.is_subtype(self.compiler.mainmodule, null, mtype) then
903 self.add("case {self.compiler.classid(t)}: /* {t} */")
904 end
905 end
906 self.add("{res} = 1;")
907 self.add("break;")
908 self.add("default:")
909 self.add("{res} = 0;")
910 self.add("\}")
911
912 return res
913 end
914
915 redef fun is_same_type_test(value1, value2)
916 do
917 var res = self.new_var(bool_type)
918 if not value2.mtype.is_c_primitive then
919 if not value1.mtype.is_c_primitive then
920 self.add "{res} = {value1}->classid == {value2}->classid;"
921 else
922 self.add "{res} = {self.compiler.classid(value1.mtype.as(MClassType))} == {value2}->classid;"
923 end
924 else
925 if not value1.mtype.is_c_primitive then
926 self.add "{res} = {value1}->classid == {self.compiler.classid(value2.mtype.as(MClassType))};"
927 else if value1.mcasttype == value2.mcasttype then
928 self.add "{res} = 1;"
929 else
930 self.add "{res} = 0;"
931 end
932 end
933 return res
934 end
935
936 redef fun class_name_string(value)
937 do
938 var res = self.get_name("var_class_name")
939 self.add_decl("const char* {res};")
940 if not value.mtype.is_c_primitive then
941 self.add "{res} = class_names[{value}->classid];"
942 else
943 self.add "{res} = class_names[{self.compiler.classid(value.mtype.as(MClassType))}];"
944 end
945 return res
946 end
947
948 redef fun equal_test(value1, value2)
949 do
950 var res = self.new_var(bool_type)
951 if value2.mtype.is_c_primitive and not value1.mtype.is_c_primitive then
952 var tmp = value1
953 value1 = value2
954 value2 = tmp
955 end
956 if value1.mtype.is_c_primitive then
957 if value2.mtype == value1.mtype then
958 self.add("{res} = {value1} == {value2};")
959 else if value2.mtype.is_c_primitive then
960 self.add("{res} = 0; /* incompatible types {value1.mtype} vs. {value2.mtype}*/")
961 else
962 var mtype1 = value1.mtype.as(MClassType)
963 self.add("{res} = ({value2} != NULL) && ({value2}->classid == {self.compiler.classid(mtype1)});")
964 self.add("if ({res}) \{")
965 self.add("{res} = ({self.autobox(value2, value1.mtype)} == {value1});")
966 self.add("\}")
967 end
968 else
969 var s = new Array[String]
970 for t in self.compiler.live_primitive_types do
971 if not t.is_subtype(self.compiler.mainmodule, null, value1.mcasttype) then continue
972 if not t.is_subtype(self.compiler.mainmodule, null, value2.mcasttype) then continue
973 s.add "({value1}->classid == {self.compiler.classid(t)} && ((struct {t.c_name}*){value1})->value == ((struct {t.c_name}*){value2})->value)"
974 end
975
976 if self.compiler.mainmodule.model.get_mclasses_by_name("Pointer") != null then
977 var pointer_type = self.compiler.mainmodule.pointer_type
978 if value1.mcasttype.is_subtype(self.compiler.mainmodule, null, pointer_type) or
979 value2.mcasttype.is_subtype(self.compiler.mainmodule, null, pointer_type) then
980 s.add "(((struct {pointer_type.c_name}*){value1})->value == ((struct {pointer_type.c_name}*){value2})->value)"
981 end
982 end
983
984 if s.is_empty then
985 self.add("{res} = {value1} == {value2};")
986 else
987 self.add("{res} = {value1} == {value2} || ({value1} != NULL && {value2} != NULL && {value1}->classid == {value2}->classid && ({s.join(" || ")}));")
988 end
989 end
990 return res
991 end
992
993 redef fun array_instance(array, elttype)
994 do
995 elttype = self.anchor(elttype)
996 var arraytype = mmodule.array_type(elttype)
997 var res = self.init_instance(arraytype)
998 self.add("\{ /* {res} = array_instance Array[{elttype}] */")
999 var nat = self.new_var(mmodule.native_array_type(elttype))
1000 nat.is_exact = true
1001 self.add("{nat} = NEW_{nat.mtype.c_name}({array.length});")
1002 for i in [0..array.length[ do
1003 var r = self.autobox(array[i], elttype)
1004 self.add("((struct {nat.mtype.c_name}*) {nat})->values[{i}] = {r};")
1005 end
1006 var length = self.int_instance(array.length)
1007 self.send(self.get_property("with_native", arraytype), [res, nat, length])
1008 self.add("\}")
1009 return res
1010 end
1011 end
1012
1013 # A runtime function customized on a specific monomorph receiver type
1014 private class CustomizedRuntimeFunction
1015 super AbstractRuntimeFunction
1016
1017 redef type COMPILER: GlobalCompiler
1018 redef type VISITOR: GlobalCompilerVisitor
1019
1020 # The considered reciever
1021 # (usually is a live type but no strong guarantee)
1022 var recv: MClassType
1023
1024 redef fun build_c_name
1025 do
1026 var res = self.c_name_cache
1027 if res != null then return res
1028 if self.mmethoddef.mclassdef.bound_mtype == self.recv then
1029 res = self.mmethoddef.c_name
1030 else
1031 res = "{mmethoddef.c_name}__{recv.c_name}"
1032 end
1033 self.c_name_cache = res
1034 return res
1035 end
1036
1037 # used in the compiler worklist
1038 redef fun ==(o)
1039 do
1040 if not o isa CustomizedRuntimeFunction then return false
1041 if self.mmethoddef != o.mmethoddef then return false
1042 if self.recv != o.recv then return false
1043 return true
1044 end
1045
1046 # used in the compiler work-list
1047 redef fun hash do return self.mmethoddef.hash + self.recv.hash
1048
1049 redef fun to_s
1050 do
1051 if self.mmethoddef.mclassdef.bound_mtype == self.recv then
1052 return self.mmethoddef.to_s
1053 else
1054 return "{self.mmethoddef}@{self.recv}"
1055 end
1056 end
1057
1058 redef fun recv_mtype
1059 do
1060 return recv
1061 end
1062
1063 redef var return_mtype
1064
1065 redef fun resolve_receiver(v)
1066 do
1067 var selfvar = new RuntimeVariable("self", recv, recv)
1068 if v.compiler.runtime_type_analysis.live_types.has(recv) then
1069 selfvar.is_exact = true
1070 end
1071 return selfvar
1072 end
1073
1074 redef fun resolve_return_mtype(v)
1075 do
1076 var selfvar = v.frame.selfvar
1077 if has_return then
1078 var ret = msignature.return_mtype.as(not null)
1079 return_mtype = v.resolve_for(ret, selfvar)
1080 end
1081 end
1082 redef fun resolve_ith_parameter(v, i)
1083 do
1084 var selfvar = v.frame.selfvar
1085 var mp = msignature.mparameters[i]
1086 var mtype = mp.mtype
1087 if mp.is_vararg then
1088 mtype = v.mmodule.array_type(mtype)
1089 end
1090 mtype = v.resolve_for(mtype, selfvar)
1091 return new RuntimeVariable("p{i}", mtype, mtype)
1092 end
1093
1094 redef fun declare_signature(v, sig)
1095 do
1096 v.compiler.header.add_decl("{sig};")
1097 end
1098
1099 redef fun end_compile_to_c(v)
1100 do
1101 if not self.c_name.has_substring("VIRTUAL", 0) then v.compiler.names[self.c_name] = "{mmethoddef.mclassdef.mmodule.name}::{mmethoddef.mclassdef.mclass.name}::{mmethoddef.mproperty.name} ({mmethoddef.location.file.filename}:{mmethoddef.location.line_start})"
1102 end
1103
1104 redef fun call(v: VISITOR, arguments: Array[RuntimeVariable]): nullable RuntimeVariable
1105 do
1106 var ret = self.mmethoddef.msignature.return_mtype
1107 if ret != null then
1108 ret = v.resolve_for(ret, arguments.first)
1109 end
1110
1111 # TODO: remove this guard when gcc warning issue (#2781) is resolved
1112 # WARNING: the next two lines of code is used to prevent inlining.
1113 # Inlining of a callref seems to work all the time. However,
1114 # it will produce some deadcode in certain scenarios (when using nullable type).
1115 #
1116 # ~~~~nitish
1117 # class A[E]
1118 # fun toto(x: E)
1119 # do
1120 # # ...do something with x...
1121 # end
1122 # end
1123 # end
1124 # var a = new A[nullable Int]
1125 # var f = &a.toto
1126 # f.call(null) # Will produce a proper C callsite, but it will
1127 # # produce unreachable (dead code) for type checking
1128 # # and covariance. Thus, creating warnings when
1129 # # compiling in global. However, if you ignore
1130 # # those warnings, the binary works perfectly fine.
1131 # ~~~~
1132 var intromclassdef = self.mmethoddef.mproperty.intro_mclassdef
1133 var is_callref = v.compiler.all_routine_types_name.has(intromclassdef.name)
1134
1135 if self.mmethoddef.can_inline(v) and not is_callref then
1136 var frame = new StaticFrame(v, self.mmethoddef, self.recv, arguments)
1137 frame.returnlabel = v.get_name("RET_LABEL")
1138 if ret != null then
1139 frame.returnvar = v.new_var(ret)
1140 end
1141 var old_frame = v.frame
1142 v.frame = frame
1143 v.add("\{ /* Inline {self} ({arguments.join(",")}) */")
1144 self.mmethoddef.compile_inside_to_c(v, arguments)
1145 v.add("{frame.returnlabel.as(not null)}:(void)0;")
1146 v.add("\}")
1147 v.frame = old_frame
1148 return frame.returnvar
1149 end
1150 v.adapt_signature(self.mmethoddef, arguments)
1151 v.compiler.todo(self)
1152 if ret == null then
1153 v.add("{self.c_name}({arguments.join(",")});")
1154 return null
1155 else
1156 var res = v.new_var(ret)
1157 v.add("{res} = {self.c_name}({arguments.join(",")});")
1158 return res
1159 end
1160 end
1161 end
1162
1163 # Thunk implementation for global compiler.
1164 # For more detail see `abstract_compiler::ThunkFunction` documentation.
1165 class CustomizedThunkFunction
1166 super ThunkFunction
1167 super CustomizedRuntimeFunction
1168
1169 redef fun c_name
1170 do
1171 return "THUNK_" + super
1172 end
1173
1174 redef fun hash
1175 do
1176 return super + c_name.hash
1177 end
1178
1179 redef fun resolve_receiver(v)
1180 do
1181 var res = super(v)
1182 if res.is_exact then res.is_exact = not polymorph_call_flag
1183 return res
1184 end
1185
1186 redef fun target_recv
1187 do
1188 # If the targeted method was introduced by a primitive type,
1189 # then target_recv must be set to it. Otherwise, there will
1190 # be a missing cast. Here's an example:
1191 #
1192 # ~~~~nitish
1193 # class Int
1194 # fun mult_by(x:Int):Int do return x * self
1195 # end
1196 #
1197 # var f = &10.mult_by
1198 # ~~~~
1199 # Here the thunk `f` must box the receiver `10` into an object.
1200 # This is due to the memory representation of a call ref which
1201 # has a pointer to an opaque type `val*`:
1202 #
1203 # ```C
1204 # struct Mult_by_callref_struct {
1205 # classid;
1206 # // The receiver `10` would be here
1207 # val* recv;
1208 # // the targeted receiver is a `long`
1209 # long (*pointer_to_mult_by)(long, long);
1210 # }
1211 # ```
1212 #
1213 # Thus, every primitive type must be boxed into an `Object` when
1214 # instantiating a callref.
1215 #
1216 # However, if the underlying method was introduced by a primitive
1217 # type then a cast must be invoked to convert our boxed receiver
1218 # to its original primitive type.
1219 var intro_recv = mmethoddef.mproperty.intro_mclassdef.bound_mtype
1220 if intro_recv.is_c_primitive then
1221 return intro_recv
1222 end
1223 return recv_mtype
1224 end
1225 end