ce61657c4c45819354801a56fa93935f9c7ec058
[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 mtype.ctype_extern != "val*" then
208 # Is the Nit type is native then the struct is a box with two fields:
209 # * the `classid` to be polymorph
210 # * the `value` that contains the native value.
211 v.add_decl("{mtype.ctype_extern} value;")
212 end
213
214 # Collect all attributes and associate them a field in the structure.
215 # Note: we do not try to optimize the order and helps CC to optimize the client code.
216 for cd in mtype.collect_mclassdefs(self.mainmodule) do
217 for p in cd.intro_mproperties do
218 if not p isa MAttribute then continue
219 var t = p.intro.static_mtype.as(not null)
220 t = t.anchor_to(self.mainmodule, mtype)
221 v.add_decl("{t.ctype} {p.intro.c_name}; /* {p}: {t} */")
222 end
223 end
224 v.add_decl("\};")
225 end
226
227 # Generate the init-instance of a live type (allocate + init-instance)
228 fun generate_init_instance(mtype: MClassType)
229 do
230 assert self.runtime_type_analysis.live_types.has(mtype)
231 assert not mtype.is_c_primitive
232 var v = self.new_visitor
233
234 var is_native_array = mtype.mclass.name == "NativeArray"
235
236 var sig
237 if is_native_array then
238 sig = "int length"
239 else
240 sig = "void"
241 end
242
243 self.header.add_decl("{mtype.ctype} NEW_{mtype.c_name}({sig});")
244 v.add_decl("/* allocate {mtype} */")
245 v.add_decl("{mtype.ctype} NEW_{mtype.c_name}({sig}) \{")
246 var res = v.new_var(mtype)
247 res.is_exact = true
248 if is_native_array then
249 v.add("{res} = nit_alloc(sizeof(struct {mtype.c_name}) + length*sizeof(val*));")
250 v.add("((struct {mtype.c_name}*){res})->length = length;")
251 else
252 v.add("{res} = nit_alloc(sizeof(struct {mtype.c_name}));")
253 end
254 v.add("{res}->classid = {self.classid(mtype)};")
255
256 self.generate_init_attr(v, res, mtype)
257 v.set_finalizer res
258 v.add("return {res};")
259 v.add("\}")
260 end
261
262 fun generate_box_instance(mtype: MClassType)
263 do
264 assert self.runtime_type_analysis.live_types.has(mtype)
265 var v = self.new_visitor
266
267 self.header.add_decl("val* BOX_{mtype.c_name}({mtype.ctype});")
268 v.add_decl("/* allocate {mtype} */")
269 v.add_decl("val* BOX_{mtype.c_name}({mtype.ctype} value) \{")
270 v.add("struct {mtype.c_name}*res = nit_alloc(sizeof(struct {mtype.c_name}));")
271 v.add("res->classid = {self.classid(mtype)};")
272 v.add("res->value = value;")
273 v.add("return (val*)res;")
274 v.add("\}")
275 end
276
277 redef fun new_visitor do return new GlobalCompilerVisitor(self)
278
279 private var collect_types_cache: HashMap[MType, Array[MClassType]] = new HashMap[MType, Array[MClassType]]
280
281 redef fun compile_nitni_structs
282 do
283 self.header.add_decl """
284 struct nitni_instance \{
285 struct nitni_instance *next,
286 *prev; /* adjacent global references in global list */
287 int count; /* number of time this global reference has been marked */
288 val *value;
289 \};"""
290 super
291 end
292 end
293
294 # A visitor on the AST of property definition that generate the C code.
295 # Because of inlining, a visitor can visit more than one property.
296 class GlobalCompilerVisitor
297 super AbstractCompilerVisitor
298
299 redef type COMPILER: GlobalCompiler
300
301 redef fun autobox(value, mtype)
302 do
303 if value.mtype == mtype then
304 return value
305 else if not value.mtype.is_c_primitive and not mtype.is_c_primitive then
306 return value
307 else if not value.mtype.is_c_primitive then
308 return self.new_expr("((struct {mtype.c_name}*){value})->value; /* autounbox from {value.mtype} to {mtype} */", mtype)
309 else if not mtype.is_c_primitive then
310 var valtype = value.mtype.as(MClassType)
311 var res = self.new_var(mtype)
312 if not compiler.runtime_type_analysis.live_types.has(valtype) then
313 self.add("/*no autobox from {value.mtype} to {mtype}: {value.mtype} is not live! */")
314 self.add("PRINT_ERROR(\"Dead code executed!\\n\"); fatal_exit(1);")
315 return res
316 end
317 self.add("{res} = BOX_{valtype.c_name}({value}); /* autobox from {value.mtype} to {mtype} */")
318 return res
319 else if value.mtype.ctype == "void*" and mtype.ctype == "void*" then
320 return value
321 else
322 # Bad things will appen!
323 var res = self.new_var(mtype)
324 self.add("/* {res} left unintialized (cannot convert {value.mtype} to {mtype}) */")
325 self.add("PRINT_ERROR(\"Cast error: Cannot cast %s to %s.\\n\", \"{value.mtype}\", \"{mtype}\"); fatal_exit(1);")
326 return res
327 end
328 end
329
330 redef fun unbox_extern(value, mtype)
331 do
332 if mtype isa MClassType and mtype.mclass.kind == extern_kind and
333 mtype.mclass.name != "CString" then
334 var res = self.new_var_extern(mtype)
335 self.add "{res} = ((struct {mtype.c_name}*){value})->value; /* unboxing {value.mtype} */"
336 return res
337 else
338 return value
339 end
340 end
341
342 redef fun box_extern(value, mtype)
343 do
344 if not mtype isa MClassType or mtype.mclass.kind != extern_kind or
345 mtype.mclass.name == "CString" then return value
346
347 var valtype = value.mtype.as(MClassType)
348 var res = self.new_var(mtype)
349 if not compiler.runtime_type_analysis.live_types.has(value.mtype.as(MClassType)) then
350 self.add("/*no boxing of {value.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}); /* boxing {value.mtype} */")
355 return res
356 end
357
358 # The runtime types that are acceptable for a given receiver.
359 fun collect_types(recv: RuntimeVariable): Array[MClassType]
360 do
361 var mtype = recv.mcasttype
362 if recv.is_exact then
363 assert mtype isa MClassType
364 assert self.compiler.runtime_type_analysis.live_types.has(mtype)
365 var types = [mtype]
366 return types
367 end
368 var cache = self.compiler.collect_types_cache
369 if cache.has_key(mtype) then
370 return cache[mtype]
371 end
372 var types = new Array[MClassType]
373 var mainmodule = self.compiler.mainmodule
374 for t in self.compiler.runtime_type_analysis.live_types do
375 if not t.is_subtype(mainmodule, null, mtype) then continue
376 types.add(t)
377 end
378 cache[mtype] = types
379 return types
380 end
381
382 redef fun native_array_def(pname, ret_type, arguments)
383 do
384 var elttype = arguments.first.mtype
385 var recv = "((struct {arguments[0].mcasttype.c_name}*){arguments[0]})->values"
386 if pname == "[]" then
387 self.ret(self.new_expr("{recv}[{arguments[1]}]", ret_type.as(not null)))
388 return true
389 else if pname == "[]=" then
390 self.add("{recv}[{arguments[1]}]={arguments[2]};")
391 return true
392 else if pname == "length" then
393 self.ret(self.new_expr("((struct {arguments[0].mcasttype.c_name}*){arguments[0]})->length", ret_type.as(not null)))
394 return true
395 else if pname == "copy_to" then
396 var recv1 = "((struct {arguments[1].mcasttype.c_name}*){arguments[1]})->values"
397 self.add("memmove({recv1},{recv},{arguments[2]}*sizeof({elttype.ctype}));")
398 return true
399 else if pname == "memmove" then
400 # fun memmove(start: Int, length: Int, dest: NativeArray[E], dest_start: Int) is intern do
401 var recv1 = "((struct {arguments[3].mcasttype.c_name}*){arguments[3]})->values"
402 self.add("memmove({recv1}+{arguments[4]}, {recv}+{arguments[1]}, {arguments[2]}*sizeof({elttype.ctype}));")
403 return true
404 end
405 return false
406 end
407
408 redef fun native_array_instance(elttype, length)
409 do
410 var ret_type = mmodule.native_array_type(elttype)
411 ret_type = anchor(ret_type).as(MClassType)
412 length = autobox(length, compiler.mainmodule.int_type)
413 return self.new_expr("NEW_{ret_type.c_name}((int){length})", ret_type)
414 end
415
416 redef fun native_array_get(nat, i)
417 do
418 var recv = "((struct {nat.mcasttype.c_name}*){nat})->values"
419 var ret_type = nat.mcasttype.as(MClassType).arguments.first
420 return self.new_expr("{recv}[{i}]", ret_type)
421 end
422
423 redef fun native_array_set(nat, i, val)
424 do
425 var recv = "((struct {nat.mcasttype.c_name}*){nat})->values"
426 self.add("{recv}[{i}]={val};")
427 end
428
429 redef fun send(m, args)
430 do
431 var types = self.collect_types(args.first)
432
433 var res: nullable RuntimeVariable
434 var ret = m.intro.msignature.return_mtype
435 if ret == null then
436 res = null
437 else
438 ret = self.resolve_for(ret, args.first)
439 res = self.new_var(ret)
440 end
441
442 self.add("/* send {m} on {args.first.inspect} */")
443 if args.first.mtype.is_c_primitive then
444 var mclasstype = args.first.mtype.as(MClassType)
445 if not self.compiler.runtime_type_analysis.live_types.has(mclasstype) then
446 self.add("/* skip, dead class {mclasstype} */")
447 return res
448 end
449 if not mclasstype.has_mproperty(self.compiler.mainmodule, m) then
450 self.add("/* skip, no method {m} */")
451 return res
452 end
453 var propdef = m.lookup_first_definition(self.compiler.mainmodule, mclasstype)
454 var res2 = self.call(propdef, mclasstype, args)
455 if res != null then self.assign(res, res2.as(not null))
456 return res
457 end
458 var consider_null = not self.compiler.modelbuilder.toolcontext.opt_no_check_null.value or m.name == "==" or m.name == "!="
459 if args.first.mcasttype isa MNullableType or args.first.mcasttype isa MNullType and consider_null then
460 # The reciever is potentially null, so we have to 3 cases: ==, != or NullPointerException
461 self.add("if ({args.first} == NULL) \{ /* Special null case */")
462 if m.name == "==" or m.name == "is_same_instance" then
463 assert res != null
464 if args[1].mcasttype isa MNullableType then
465 self.add("{res} = ({args[1]} == NULL);")
466 else if args[1].mcasttype isa MNullType then
467 self.add("{res} = 1; /* is null */")
468 else
469 self.add("{res} = 0; /* {args[1].inspect} cannot be null */")
470 end
471 else if m.name == "!=" then
472 assert res != null
473 if args[1].mcasttype isa MNullableType then
474 self.add("{res} = ({args[1]} != NULL);")
475 else if args[1].mcasttype isa MNullType then
476 self.add("{res} = 0; /* is null */")
477 else
478 self.add("{res} = 1; /* {args[1].inspect} cannot be null */")
479 end
480 else
481 self.add_abort("Receiver is null")
482 end
483 self.add "\} else"
484 end
485 if types.is_empty then
486 self.add("\{")
487 self.add("/*BUG: no live types for {args.first.inspect} . {m}*/")
488 self.bugtype(args.first)
489 self.add("\}")
490 return res
491 end
492
493 self.add("switch({args.first}->classid) \{")
494 var last = types.last
495 var defaultpropdef: nullable MMethodDef = null
496 for t in types do
497 var propdef = m.lookup_first_definition(self.compiler.mainmodule, t)
498 if propdef.mclassdef.mclass.name == "Object" and not t.is_c_primitive then
499 defaultpropdef = propdef
500 continue
501 end
502 if not self.compiler.hardening and t == last and defaultpropdef == null then
503 self.add("default: /* test {t} */")
504 else
505 self.add("case {self.compiler.classid(t)}: /* test {t} */")
506 end
507 var res2 = self.call(propdef, t, args)
508 if res != null then self.assign(res, res2.as(not null))
509 self.add "break;"
510 end
511 if defaultpropdef != null then
512 self.add("default: /* default is Object */")
513 var res2 = self.call(defaultpropdef, defaultpropdef.mclassdef.bound_mtype, args)
514 if res != null then self.assign(res, res2.as(not null))
515 else if self.compiler.hardening then
516 self.add("default: /* bug */")
517 self.bugtype(args.first)
518 end
519 self.add("\}")
520 return res
521 end
522
523 fun check_valid_reciever(recvtype: MClassType)
524 do
525 if self.compiler.runtime_type_analysis.live_types.has(recvtype) or recvtype.mclass.name == "Object" then return
526 print_error "{recvtype} is not a live type"
527 abort
528 end
529
530 # Subpart of old call function
531 #
532 # Checks if the type of the receiver is valid and corrects it if necessary
533 private fun get_recvtype(m: MMethodDef, recvtype: MClassType, args: Array[RuntimeVariable]): MClassType
534 do
535 check_valid_reciever(recvtype)
536 return recvtype
537 end
538
539 redef fun call(m, recvtype, args)
540 do
541 var recv_type = get_recvtype(m, recvtype, args)
542 var recv = self.autoadapt(self.autobox(args.first, recvtype), recvtype)
543 if m.is_extern then recv = unbox_extern(recv, recv_type)
544
545 args = args.to_a
546 args.first = recv
547
548 assert args.length == m.msignature.arity + 1 else debug("Invalid arity for {m}. {args.length} arguments given.")
549
550 var rm = new CustomizedRuntimeFunction(m, recvtype)
551 return rm.call(self, args)
552 end
553
554 redef fun supercall(m: MMethodDef, recvtype: MClassType, args: Array[RuntimeVariable]): nullable RuntimeVariable
555 do
556 var types = self.collect_types(args.first)
557
558 var res: nullable RuntimeVariable
559 var ret = m.mproperty.intro.msignature.return_mtype
560 if ret == null then
561 res = null
562 else
563 ret = self.resolve_for(ret, args.first)
564 res = self.new_var(ret)
565 end
566
567 self.add("/* super {m} on {args.first.inspect} */")
568 if args.first.mtype.is_c_primitive then
569 var mclasstype = args.first.mtype.as(MClassType)
570 if not self.compiler.runtime_type_analysis.live_types.has(mclasstype) then
571 self.add("/* skip, no method {m} */")
572 return res
573 end
574 var propdef = m.lookup_next_definition(self.compiler.mainmodule, mclasstype)
575 var res2 = self.call(propdef, mclasstype, args)
576 if res != null then self.assign(res, res2.as(not null))
577 return res
578 end
579
580 if types.is_empty then
581 self.add("\{")
582 self.add("/*BUG: no live types for {args.first.inspect} . {m}*/")
583 self.bugtype(args.first)
584 self.add("\}")
585 return res
586 end
587
588 self.add("switch({args.first}->classid) \{")
589 var last = types.last
590 for t in types do
591 var propdef = m.lookup_next_definition(self.compiler.mainmodule, t)
592 if not self.compiler.hardening and t == last then
593 self.add("default: /* test {t} */")
594 else
595 self.add("case {self.compiler.classid(t)}: /* test {t} */")
596 end
597 var res2 = self.call(propdef, t, args)
598 if res != null then self.assign(res, res2.as(not null))
599 self.add "break;"
600 end
601 if self.compiler.hardening then
602 self.add("default: /* bug */")
603 self.bugtype(args.first)
604 end
605 self.add("\}")
606 return res
607 end
608
609 redef fun adapt_signature(m, args)
610 do
611 var recv = args.first
612 for i in [0..m.msignature.arity[ do
613 var mp = m.msignature.mparameters[i]
614 var t = mp.mtype
615 if mp.is_vararg then
616 t = args[i+1].mtype
617 end
618 t = self.resolve_for(t, recv)
619 args[i+1] = self.autobox(args[i+1], t)
620 end
621 end
622
623 redef fun unbox_signature_extern(m, args)
624 do
625 var recv = args.first
626 for i in [0..m.msignature.arity[ do
627 var mp = m.msignature.mparameters[i]
628 var t = mp.mtype
629 if mp.is_vararg then
630 t = args[i+1].mtype
631 end
632 t = self.resolve_for(t, recv)
633 if m.is_extern then args[i+1] = self.unbox_extern(args[i+1], t)
634 end
635 end
636
637 # FIXME: this is currently buggy since recv is not exact
638 redef fun vararg_instance(mpropdef, recv, varargs, elttype)
639 do
640 elttype = self.resolve_for(elttype, recv)
641 return self.array_instance(varargs, elttype)
642 end
643
644 fun bugtype(recv: RuntimeVariable)
645 do
646 if recv.mtype.is_c_primitive then return
647 self.add("PRINT_ERROR(\"BTD BUG: Dynamic type is %s, static type is %s\\n\", class_names[{recv}->classid], \"{recv.mcasttype}\");")
648 self.add("fatal_exit(1);")
649 end
650
651 redef fun isset_attribute(a, recv)
652 do
653 check_recv_notnull(recv)
654
655 var types = self.collect_types(recv)
656 var res = self.new_var(bool_type)
657
658 if types.is_empty then
659 self.add("/*BUG: no live types for {recv.inspect} . {a}*/")
660 self.bugtype(recv)
661 return res
662 end
663 self.add("/* isset {a} on {recv.inspect} */")
664 self.add("switch({recv}->classid) \{")
665 var last = types.last
666 for t in types do
667 if not self.compiler.hardening and t == last then
668 self.add("default: /*{self.compiler.classid(t)}*/")
669 else
670 self.add("case {self.compiler.classid(t)}:")
671 end
672 var recv2 = self.autoadapt(recv, t)
673 var ta = a.intro.static_mtype.as(not null)
674 ta = self.resolve_for(ta, recv2)
675 var attr = self.new_expr("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta)
676 if not ta isa MNullableType then
677 if not ta.is_c_primitive then
678 self.add("{res} = ({attr} != NULL);")
679 else
680 self.add("{res} = 1; /*NOTYET isset on primitive attributes*/")
681 end
682 end
683 self.add("break;")
684 end
685 if self.compiler.hardening then
686 self.add("default: /* Bug */")
687 self.bugtype(recv)
688 end
689 self.add("\}")
690
691 return res
692 end
693
694 redef fun read_attribute(a, recv)
695 do
696 check_recv_notnull(recv)
697
698 var types = self.collect_types(recv)
699
700 var ret = a.intro.static_mtype.as(not null)
701 ret = self.resolve_for(ret, recv)
702 var res = self.new_var(ret)
703
704 if types.is_empty then
705 self.add("/*BUG: no live types for {recv.inspect} . {a}*/")
706 self.bugtype(recv)
707 return res
708 end
709 self.add("/* read {a} on {recv.inspect} */")
710 self.add("switch({recv}->classid) \{")
711 var last = types.last
712 for t in types do
713 if not self.compiler.hardening and t == last then
714 self.add("default: /*{self.compiler.classid(t)}*/")
715 else
716 self.add("case {self.compiler.classid(t)}:")
717 end
718 var recv2 = self.autoadapt(recv, t)
719 var ta = a.intro.static_mtype.as(not null)
720 ta = self.resolve_for(ta, recv2)
721 var res2 = self.new_expr("((struct {t.c_name}*){recv})->{a.intro.c_name}", ta)
722 if not ta isa MNullableType and not self.compiler.modelbuilder.toolcontext.opt_no_check_attr_isset.value then
723 if not ta.is_c_primitive then
724 self.add("if ({res2} == NULL) \{")
725 self.add_abort("Uninitialized attribute {a.name}")
726 self.add("\}")
727 else
728 self.add("/*NOTYET isset on primitive attributes*/")
729 end
730 end
731 self.assign(res, res2)
732 self.add("break;")
733 end
734 if self.compiler.hardening then
735 self.add("default: /* Bug */")
736 self.bugtype(recv)
737 end
738 self.add("\}")
739
740 return res
741 end
742
743 redef fun write_attribute(a, recv, value)
744 do
745 check_recv_notnull(recv)
746
747 var types = self.collect_types(recv)
748
749 if types.is_empty then
750 self.add("/*BUG: no live types for {recv.inspect} . {a}*/")
751 self.bugtype(recv)
752 return
753 end
754 self.add("/* write {a} on {recv.inspect} */")
755 self.add("switch({recv}->classid) \{")
756 var last = types.last
757 for t in types do
758 if not self.compiler.hardening and t == last then
759 self.add("default: /*{self.compiler.classid(t)}*/")
760 else
761 self.add("case {self.compiler.classid(t)}:")
762 end
763 var recv2 = self.autoadapt(recv, t)
764 var ta = a.intro.static_mtype.as(not null)
765 ta = self.resolve_for(ta, recv2)
766 self.add("((struct {t.c_name}*){recv})->{a.intro.c_name} = {self.autobox(value, ta)};")
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 end
775
776 redef fun init_instance(mtype)
777 do
778 mtype = self.anchor(mtype).as(MClassType)
779 if not self.compiler.runtime_type_analysis.live_types.has(mtype) then
780 debug "problem: {mtype} was detected dead"
781 end
782 var res = self.new_expr("NEW_{mtype.c_name}()", mtype)
783 res.is_exact = true
784 return res
785 end
786
787 redef fun type_test(value, mtype, tag)
788 do
789 mtype = self.anchor(mtype)
790 if not self.compiler.runtime_type_analysis.live_cast_types.has(mtype) then
791 debug "problem: {mtype} was detected cast-dead"
792 abort
793 end
794
795 var types = self.collect_types(value)
796 var res = self.new_var(bool_type)
797
798 self.add("/* isa {mtype} on {value.inspect} */")
799 if value.mtype.is_c_primitive then
800 if value.mtype.is_subtype(self.compiler.mainmodule, null, mtype) then
801 self.add("{res} = 1;")
802 else
803 self.add("{res} = 0;")
804 end
805 return res
806 end
807 if value.mcasttype isa MNullableType or value.mcasttype isa MNullType then
808 self.add("if ({value} == NULL) \{")
809 if mtype isa MNullableType then
810 self.add("{res} = 1; /* isa {mtype} */")
811 else
812 self.add("{res} = 0; /* not isa {mtype} */")
813 end
814 self.add("\} else ")
815 end
816 self.add("switch({value}->classid) \{")
817 for t in types do
818 if t.is_subtype(self.compiler.mainmodule, null, mtype) then
819 self.add("case {self.compiler.classid(t)}: /* {t} */")
820 end
821 end
822 self.add("{res} = 1;")
823 self.add("break;")
824 self.add("default:")
825 self.add("{res} = 0;")
826 self.add("\}")
827
828 return res
829 end
830
831 redef fun is_same_type_test(value1, value2)
832 do
833 var res = self.new_var(bool_type)
834 if not value2.mtype.is_c_primitive then
835 if not value1.mtype.is_c_primitive then
836 self.add "{res} = {value1}->classid == {value2}->classid;"
837 else
838 self.add "{res} = {self.compiler.classid(value1.mtype.as(MClassType))} == {value2}->classid;"
839 end
840 else
841 if not value1.mtype.is_c_primitive then
842 self.add "{res} = {value1}->classid == {self.compiler.classid(value2.mtype.as(MClassType))};"
843 else if value1.mcasttype == value2.mcasttype then
844 self.add "{res} = 1;"
845 else
846 self.add "{res} = 0;"
847 end
848 end
849 return res
850 end
851
852 redef fun class_name_string(value)
853 do
854 var res = self.get_name("var_class_name")
855 self.add_decl("const char* {res};")
856 if not value.mtype.is_c_primitive then
857 self.add "{res} = class_names[{value}->classid];"
858 else
859 self.add "{res} = class_names[{self.compiler.classid(value.mtype.as(MClassType))}];"
860 end
861 return res
862 end
863
864 redef fun equal_test(value1, value2)
865 do
866 var res = self.new_var(bool_type)
867 if value2.mtype.is_c_primitive and not value1.mtype.is_c_primitive then
868 var tmp = value1
869 value1 = value2
870 value2 = tmp
871 end
872 if value1.mtype.is_c_primitive then
873 if value2.mtype == value1.mtype then
874 self.add("{res} = {value1} == {value2};")
875 else if value2.mtype.is_c_primitive then
876 self.add("{res} = 0; /* incompatible types {value1.mtype} vs. {value2.mtype}*/")
877 else
878 var mtype1 = value1.mtype.as(MClassType)
879 self.add("{res} = ({value2} != NULL) && ({value2}->classid == {self.compiler.classid(mtype1)});")
880 self.add("if ({res}) \{")
881 self.add("{res} = ({self.autobox(value2, value1.mtype)} == {value1});")
882 self.add("\}")
883 end
884 else
885 var s = new Array[String]
886 for t in self.compiler.live_primitive_types do
887 if not t.is_subtype(self.compiler.mainmodule, null, value1.mcasttype) then continue
888 if not t.is_subtype(self.compiler.mainmodule, null, value2.mcasttype) then continue
889 s.add "({value1}->classid == {self.compiler.classid(t)} && ((struct {t.c_name}*){value1})->value == ((struct {t.c_name}*){value2})->value)"
890 end
891
892 if self.compiler.mainmodule.model.get_mclasses_by_name("Pointer") != null then
893 var pointer_type = self.compiler.mainmodule.pointer_type
894 if value1.mcasttype.is_subtype(self.compiler.mainmodule, null, pointer_type) or
895 value2.mcasttype.is_subtype(self.compiler.mainmodule, null, pointer_type) then
896 s.add "(((struct {pointer_type.c_name}*){value1})->value == ((struct {pointer_type.c_name}*){value2})->value)"
897 end
898 end
899
900 if s.is_empty then
901 self.add("{res} = {value1} == {value2};")
902 else
903 self.add("{res} = {value1} == {value2} || ({value1} != NULL && {value2} != NULL && {value1}->classid == {value2}->classid && ({s.join(" || ")}));")
904 end
905 end
906 return res
907 end
908
909 redef fun array_instance(array, elttype)
910 do
911 elttype = self.anchor(elttype)
912 var arraytype = mmodule.array_type(elttype)
913 var res = self.init_instance(arraytype)
914 self.add("\{ /* {res} = array_instance Array[{elttype}] */")
915 var nat = self.new_var(mmodule.native_array_type(elttype))
916 nat.is_exact = true
917 self.add("{nat} = NEW_{nat.mtype.c_name}({array.length});")
918 for i in [0..array.length[ do
919 var r = self.autobox(array[i], elttype)
920 self.add("((struct {nat.mtype.c_name}*) {nat})->values[{i}] = {r};")
921 end
922 var length = self.int_instance(array.length)
923 self.send(self.get_property("with_native", arraytype), [res, nat, length])
924 self.add("\}")
925 return res
926 end
927 end
928
929 # A runtime function customized on a specific monomorph receiver type
930 private class CustomizedRuntimeFunction
931 super AbstractRuntimeFunction
932
933 redef type COMPILER: GlobalCompiler
934 redef type VISITOR: GlobalCompilerVisitor
935
936 # The considered reciever
937 # (usually is a live type but no strong guarantee)
938 var recv: MClassType
939
940 redef fun build_c_name
941 do
942 var res = self.c_name_cache
943 if res != null then return res
944 if self.mmethoddef.mclassdef.bound_mtype == self.recv then
945 res = self.mmethoddef.c_name
946 else
947 res = "{mmethoddef.c_name}__{recv.c_name}"
948 end
949 self.c_name_cache = res
950 return res
951 end
952
953 # used in the compiler worklist
954 redef fun ==(o)
955 do
956 if not o isa CustomizedRuntimeFunction then return false
957 if self.mmethoddef != o.mmethoddef then return false
958 if self.recv != o.recv then return false
959 return true
960 end
961
962 # used in the compiler work-list
963 redef fun hash do return self.mmethoddef.hash + self.recv.hash
964
965 redef fun to_s
966 do
967 if self.mmethoddef.mclassdef.bound_mtype == self.recv then
968 return self.mmethoddef.to_s
969 else
970 return "{self.mmethoddef}@{self.recv}"
971 end
972 end
973
974 redef fun recv_mtype
975 do
976 return recv
977 end
978
979 redef var return_mtype
980
981 redef fun resolve_receiver(v)
982 do
983 var selfvar = new RuntimeVariable("self", recv, recv)
984 if v.compiler.runtime_type_analysis.live_types.has(recv) then
985 selfvar.is_exact = true
986 end
987 return selfvar
988 end
989
990 redef fun resolve_return_mtype(v)
991 do
992 var selfvar = v.frame.selfvar
993 if has_return then
994 var ret = msignature.return_mtype.as(not null)
995 return_mtype = v.resolve_for(ret, selfvar)
996 end
997 end
998 redef fun resolve_ith_parameter(v, i)
999 do
1000 var selfvar = v.frame.selfvar
1001 var mp = msignature.mparameters[i]
1002 var mtype = mp.mtype
1003 if mp.is_vararg then
1004 mtype = v.mmodule.array_type(mtype)
1005 end
1006 mtype = v.resolve_for(mtype, selfvar)
1007 return new RuntimeVariable("p{i}", mtype, mtype)
1008 end
1009
1010 redef fun declare_signature(v, sig)
1011 do
1012 v.compiler.header.add_decl("{sig};")
1013 end
1014
1015 redef fun end_compile_to_c(v)
1016 do
1017 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})"
1018 end
1019
1020 redef fun call(v: VISITOR, arguments: Array[RuntimeVariable]): nullable RuntimeVariable
1021 do
1022 var ret = self.mmethoddef.msignature.return_mtype
1023 if ret != null then
1024 ret = v.resolve_for(ret, arguments.first)
1025 end
1026 if self.mmethoddef.can_inline(v) then
1027 var frame = new StaticFrame(v, self.mmethoddef, self.recv, arguments)
1028 frame.returnlabel = v.get_name("RET_LABEL")
1029 if ret != null then
1030 frame.returnvar = v.new_var(ret)
1031 end
1032 var old_frame = v.frame
1033 v.frame = frame
1034 v.add("\{ /* Inline {self} ({arguments.join(",")}) */")
1035 self.mmethoddef.compile_inside_to_c(v, arguments)
1036 v.add("{frame.returnlabel.as(not null)}:(void)0;")
1037 v.add("\}")
1038 v.frame = old_frame
1039 return frame.returnvar
1040 end
1041 v.adapt_signature(self.mmethoddef, arguments)
1042 v.compiler.todo(self)
1043 if ret == null then
1044 v.add("{self.c_name}({arguments.join(",")});")
1045 return null
1046 else
1047 var res = v.new_var(ret)
1048 v.add("{res} = {self.c_name}({arguments.join(",")});")
1049 return res
1050 end
1051 end
1052 end