compile: remove GlobalAnalysis
[nit.git] / src / compiling / compiling_global.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2008 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 # Compute and generate tables for classes and modules.
18 package compiling_global
19
20 import program
21 private import compiling_icode
22
23 # Something that store color of table elements
24 class ColorContext
25 var _colors: HashMap[TableElt, Int] = new HashMap[TableElt, Int]
26
27 # The color of a table element.
28 fun color(e: TableElt): Int
29 do
30 return _colors[e]
31 end
32
33 # Is a table element already colored?
34 fun has_color(e: TableElt): Bool
35 do
36 return _colors.has_key(e)
37 end
38
39 # Assign a color to a table element.
40 fun color=(e: TableElt, c: Int)
41 do
42 _colors[e] = c
43 var idx = c
44 for i in [0..e.length[ do
45 _colors[e.item(i)] = idx
46 idx = idx + 1
47 end
48 end
49 end
50
51 # All information and results of the global analysis.
52 class TableInformation
53 special ColorContext
54 # FIXME: do something better.
55 readable writable var _max_class_table_length: Int = 0
56 end
57
58 class GlobalCompilerVisitor
59 special CompilerVisitor
60 # The global analysis result
61 readable var _program: Program
62 init(m: MMModule, tc: ToolContext, prog: Program)
63 do
64 super(m, tc)
65 _program = prog
66 end
67 end
68
69 # A compiled class is a class in a program
70 class CompiledClass
71 special ColorContext
72 # The corresponding local class in the main module of the prgram
73 readable var _local_class: MMLocalClass
74
75 # The identifier of the class
76 readable writable var _id: Int = 0
77
78 # The full class table of the class
79 readable var _class_table: Array[nullable TableElt] = new Array[nullable TableElt]
80
81 # The full instance table of the class
82 readable var _instance_table: Array[nullable TableElt] = new Array[nullable TableElt]
83
84 # The proper class table part (no superclasses but all refinements)
85 readable writable var _class_layout: TableEltComposite = new TableEltComposite(self)
86
87 # The proper instance table part (no superclasses but all refinements)
88 readable writable var _instance_layout: TableEltComposite = new TableEltComposite(self)
89
90 init(c: MMLocalClass) do _local_class = c
91 end
92
93 redef class MMConcreteClass
94 # The table element of the subtype check
95 fun class_color_pos: TableEltClassColor do return _class_color_pos.as(not null)
96 var _class_color_pos: nullable TableEltClassColor
97
98 # The proper local class table part (nor superclasses nor refinments)
99 readable var _class_layout: Array[TableElt] = new Array[TableElt]
100
101 # The proper local instance table part (nor superclasses nor refinments)
102 readable var _instance_layout: Array[TableElt] = new Array[TableElt]
103
104 # Build the local layout of the class and feed the module table
105 fun build_layout_in(tc: ToolContext, module_table: Array[ModuleTableElt])
106 do
107 var clt = _class_layout
108 var ilt = _instance_layout
109
110 if global.intro == self then
111 module_table.add(new TableEltClassId(self))
112 var cpp = new TableEltClassColor(self)
113 _class_color_pos = cpp
114 module_table.add(cpp)
115 clt.add(new TableEltClassInitTable(self))
116 end
117 for p in local_local_properties do
118 var pg = p.global
119 if pg.intro == p then
120 if p isa MMAttribute then
121 ilt.add(new TableEltAttr(p))
122 else if p isa MMMethod then
123 clt.add(new TableEltMeth(p))
124 end
125 end
126 if p isa MMMethod and p.need_super then
127 clt.add(new TableEltSuper(p))
128 end
129 end
130
131 if not ilt.is_empty then
132 var teg = new ModuleTableEltGroup
133 teg.elements.append(ilt)
134 module_table.add(teg)
135 end
136
137 if not clt.is_empty then
138 var teg = new ModuleTableEltGroup
139 teg.elements.append(clt)
140 module_table.add(teg)
141 end
142 end
143 end
144
145 redef class Program
146 # Information about the class tables
147 readable var _table_information: TableInformation = new TableInformation
148
149 # Associate global classes to compiled classes
150 readable var _compiled_classes: HashMap[MMGlobalClass, CompiledClass] = new HashMap[MMGlobalClass, CompiledClass]
151
152 # Do the complete global analysis
153 fun global_analysis(cctx: ToolContext)
154 do
155 var smallest_classes = new Array[MMLocalClass]
156 var global_properties = new HashSet[MMGlobalProperty]
157 var ctab = new Array[TableElt]
158 var itab = new Array[TableElt]
159
160 ctab.add(new TableEltClassSelfId)
161 ctab.add(new TableEltClassObjectSize)
162 itab.add(new TableEltVftPointer)
163 itab.add(new TableEltObjectId)
164
165 var pclassid = -1
166 var classid = 3
167
168 # We have to work on ALL the classes of the module
169 var classes = new Array[MMLocalClass]
170 for c in module.local_classes do
171 c.compute_super_classes
172 classes.add(c)
173 end
174 (new ClassSorter).sort(classes)
175
176 for c in classes do
177 # Finish processing the class (if invisible)
178 c.compute_ancestors
179 c.inherit_global_properties
180
181 # Associate a CompiledClass to the class
182 var cc = new CompiledClass(c)
183 compiled_classes[c.global] = cc
184
185 # Assign a unique class identifier
186 # (negative are for primitive classes)
187 var gc = c.global
188 var bm = gc.module
189 if c.primitive_info != null then
190 cc.id = pclassid
191 pclassid = pclassid - 4
192 else
193 cc.id = classid
194 classid = classid + 4
195 end
196
197 # Register is the class is a leaf
198 if c.cshe.direct_smallers.is_empty then
199 smallest_classes.add(c)
200 end
201
202 # Store the colortableelt in the class table pool
203 var bc = c.global.intro
204 assert bc isa MMConcreteClass
205 ctab.add(bc.class_color_pos)
206 end
207
208 # Compute core and crown classes for colorization
209 var crown_classes = new HashSet[MMLocalClass]
210 var core_classes = new HashSet[MMLocalClass]
211 for c in smallest_classes do
212 while c.cshe.direct_greaters.length == 1 do
213 c = c.cshe.direct_greaters.first
214 end
215 crown_classes.add(c)
216 core_classes.add_all(c.cshe.greaters_and_self)
217 end
218 #print("nbclasses: {classes.length} leaves: {smallest_classes.length} crown: {crown_classes.length} core: {core_classes.length}")
219
220 # Colorize core color for typechecks
221 colorize(ctab, crown_classes, 0)
222
223 # Compute tables for typechecks
224 var maxcolor = 0
225 for c in classes do
226 var cc = compiled_classes[c.global]
227 if core_classes.has(c) then
228 # For core classes, just build the table
229 build_tables_in(cc.class_table, c, ctab)
230 if maxcolor < cc.class_table.length then maxcolor = cc.class_table.length
231 else
232 # For other classes, it's easier: just append to the parent tables
233 var sc = c.cshe.direct_greaters.first
234 var scc = compiled_classes[sc.global]
235 assert cc.class_table.is_empty
236 cc.class_table.add_all(scc.class_table)
237 var bc = c.global.intro
238 assert bc isa MMConcreteClass
239 var colpos = bc.class_color_pos
240 var colposcolor = cc.class_table.length
241 table_information.color(colpos) = colposcolor
242 cc.class_table.add(colpos)
243 if maxcolor < colposcolor then maxcolor = colposcolor
244 end
245 end
246 table_information.max_class_table_length = maxcolor + 1
247
248 # Fill class table and instance tables pools
249 for c in classes do
250 var cc = compiled_classes[c.global]
251 var cte = cc.class_layout
252 var ite = cc.instance_layout
253 for sc in c.crhe.greaters_and_self do
254 if sc isa MMConcreteClass then
255 cte.add(sc, sc.class_layout)
256 ite.add(sc, sc.instance_layout)
257 end
258 end
259
260 if core_classes.has(c) then
261 if cte.length > 0 then
262 ctab.add(cte)
263 end
264 if ite.length > 0 then
265 itab.add(ite)
266 end
267 end
268 end
269
270 # Colorize all elements in pools tables
271 colorize(ctab, crown_classes, maxcolor+1)
272 colorize(itab, crown_classes, 0)
273
274 # Build class and instance tables now things are colored
275 table_information.max_class_table_length = 0
276 for c in classes do
277 var cc = compiled_classes[c.global]
278 if core_classes.has(c) then
279 # For core classes, just build the table
280 build_tables_in(cc.class_table, c, ctab)
281 build_tables_in(cc.instance_table, c, itab)
282 else
283 # For other classes, it's easier: just append to the parent tables
284 var sc = c.cshe.direct_greaters.first
285 var scc = compiled_classes[sc.global]
286 cc.class_table.clear
287 cc.class_table.add_all(scc.class_table)
288 var bc = c.global.intro
289 assert bc isa MMConcreteClass
290 var colpos = bc.class_color_pos
291 cc.class_table[table_information.color(colpos)] = colpos
292 while cc.class_table.length <= maxcolor do
293 cc.class_table.add(null)
294 end
295 append_to_table(cc.class_table, cc.class_layout)
296 assert cc.instance_table.is_empty
297 cc.instance_table.add_all(scc.instance_table)
298 append_to_table(cc.instance_table, cc.instance_layout)
299 end
300 end
301 end
302
303 # Perform coloring
304 fun colorize(elts: Array[TableElt], classes: Collection[MMLocalClass], startcolor: Int)
305 do
306 var colors = new HashMap[Int, Array[TableElt]]
307 var rel_classes = new Array[MMLocalClass]
308 for e in elts do
309 var color = -1
310 var len = e.length
311 if table_information.has_color(e) then
312 color = table_information.color(e)
313 else
314 rel_classes.clear
315 for c in classes do
316 if e.is_related_to(c) then
317 rel_classes.add(c)
318 end
319 end
320 var trycolor = startcolor
321 while trycolor != color do
322 color = trycolor
323 for c in rel_classes do
324 var idx = 0
325 while idx < len do
326 if colors.has_key(trycolor + idx) and not free_color(colors[trycolor + idx], c) then
327 trycolor = trycolor + idx + 1
328 idx = 0
329 else
330 idx = idx + 1
331 end
332 end
333 end
334 end
335 table_information.color(e) = color
336 end
337 for idx in [0..len[ do
338 if colors.has_key(color + idx) then
339 colors[color + idx].add(e)
340 else
341 colors[color + idx] = [e]
342 end
343 end
344 end
345 end
346
347 private fun free_color(es: Array[TableElt], c: MMLocalClass): Bool
348 do
349 for e2 in es do
350 if e2.is_related_to(c) then
351 return false
352 end
353 end
354 return true
355 end
356
357 private fun append_to_table(table: Array[nullable TableElt], cmp: TableEltComposite)
358 do
359 for j in [0..cmp.length[ do
360 var e = cmp.item(j)
361 table_information.color(e) = table.length
362 table.add(e)
363 end
364 end
365
366 private fun build_tables_in(table: Array[nullable TableElt], c: MMLocalClass, elts: Array[TableElt])
367 do
368 var tab = new HashMap[Int, TableElt]
369 var len = 0
370 for e in elts do
371 if e.is_related_to(c) then
372 var col = table_information.color(e)
373 var l = col + e.length
374 tab[col] = e
375 if len < l then
376 len = l
377 end
378 end
379 end
380 var i = 0
381 while i < len do
382 if tab.has_key(i) then
383 var e = tab[i]
384 for j in [0..e.length[ do
385 table[i] = e.item(j)
386 i = i + 1
387 end
388 else
389 table[i] = null
390 i = i + 1
391 end
392 end
393 end
394
395 # Compile module and class tables
396 fun compile_tables_to_c(v: GlobalCompilerVisitor)
397 do
398 for m in module.mhe.greaters_and_self do
399 m.compile_local_table_to_c(v)
400 end
401
402 for c in module.local_classes do
403 c.compile_tables_to_c(v)
404 end
405 var s = new Buffer.from("classtable_t TAG2VFT[4] = \{NULL")
406 for t in ["Int","Char","Bool"] do
407 if module.has_global_class_named(t.to_symbol) then
408 s.append(", (const classtable_t)VFT_{t}")
409 else
410 s.append(", NULL")
411 end
412 end
413 s.append("};")
414 v.add_instr(s.to_s)
415 end
416
417 # Compile main part (for _table.c)
418 fun compile_main_part(v: GlobalCompilerVisitor)
419 do
420 v.add_instr("int main(int argc, char **argv) \{")
421 v.indent
422 v.add_instr("prepare_signals();")
423 v.add_instr("glob_argc = argc; glob_argv = argv;")
424 var sysname = once "Sys".to_symbol
425 if not module.has_global_class_named(sysname) then
426 print("No main")
427 else
428 var sys = module.class_by_name(sysname)
429 var name = once "main".to_symbol
430 if not sys.has_global_property_by_name(name) then
431 print("No main")
432 else
433 var mainm = sys.select_method(name)
434 v.add_instr("G_sys = NEW_Sys();")
435 v.add_instr("register_static_object(&G_sys);")
436 v.add_instr("{mainm.cname}(G_sys);")
437 end
438 end
439 v.add_instr("return 0;")
440 v.unindent
441 v.add_instr("}")
442 end
443 end
444
445 redef class MMModule
446 # The local table of the module (refers things introduced in the module)
447 var _local_table: Array[ModuleTableElt] = new Array[ModuleTableElt]
448
449 # Builds the local tables and local classes layouts
450 fun local_analysis(tc: ToolContext)
451 do
452 for c in local_classes do
453 if c isa MMConcreteClass then
454 c.build_layout_in(tc, _local_table)
455 end
456 end
457 end
458
459 # Declare class table (for _sep.h)
460 fun declare_class_tables_to_c(v: GlobalCompilerVisitor)
461 do
462 for c in local_classes do
463 if c.global.module == self then
464 c.declare_tables_to_c(v)
465 end
466 end
467 end
468
469 # Compile sep files
470 fun compile_mod_to_c(v: GlobalCompilerVisitor)
471 do
472 v.add_decl("extern const char *LOCATE_{name};")
473 if not v.tc.global then
474 v.add_decl("extern const int SFT_{name}[];")
475 end
476 var i = 0
477 for e in _local_table do
478 var value: String
479 if v.tc.global then
480 value = "{e.value(v.program)}"
481 else
482 value = "SFT_{name}[{i}]"
483 i = i + 1
484 end
485 e.compile_macros(v, value)
486 end
487 for c in local_classes do
488 if not c isa MMConcreteClass then continue
489 for pg in c.global_properties do
490 var p = c[pg]
491 if p.local_class == c and p isa MMMethod then
492 p.compile_property_to_c(v)
493 end
494 if pg.is_init_for(c) then
495 # Declare constructors
496 var params = new Array[String]
497 for j in [0..p.signature.arity[ do
498 params.add("val_t p{j}")
499 end
500 v.add_decl("val_t NEW_{c}_{p.global.intro.cname}({params.join(", ")});")
501 end
502 end
503 end
504 end
505
506 # Compile module file for the current module
507 fun compile_local_table_to_c(v: GlobalCompilerVisitor)
508 do
509 v.add_instr("const char *LOCATE_{name} = \"{location.file}\";")
510
511 if v.tc.global or _local_table.is_empty then
512 return
513 end
514
515 v.add_instr("const int SFT_{name}[{_local_table.length}] = \{")
516 v.indent
517 for e in _local_table do
518 v.add_instr(e.value(v.program) + ",")
519 end
520 v.unindent
521 v.add_instr("\};")
522 end
523 end
524
525 ###############################################################################
526
527 # An element of a class, an instance or a module table
528 abstract class AbsTableElt
529 # Compile the macro needed to use the element and other related elements
530 fun compile_macros(v: GlobalCompilerVisitor, value: String) is abstract
531 end
532
533 # An element of a class or an instance table
534 # Such an elements represent method function pointers, attribute values, etc.
535 abstract class TableElt
536 special AbsTableElt
537 # Is the element conflict to class `c' (used for coloring)
538 fun is_related_to(c: MMLocalClass): Bool is abstract
539
540 # Number of sub-elements. 1 if none
541 fun length: Int do return 1
542
543 # Access the ith subelement.
544 fun item(i: Int): TableElt do return self
545
546 # Return the value of the element for a given class
547 fun compile_to_c(v: GlobalCompilerVisitor, c: MMLocalClass): String is abstract
548 end
549
550 # An element of a module table
551 # Such an elements represent colors or identifiers
552 abstract class ModuleTableElt
553 special AbsTableElt
554 # Return the value of the element once the global analisys is performed
555 fun value(prog: Program): String is abstract
556 end
557
558 # An element of a module table that represents a group of TableElt defined in the same local class
559 class ModuleTableEltGroup
560 special ModuleTableElt
561 readable var _elements: Array[TableElt] = new Array[TableElt]
562
563 redef fun value(prog) do return "{prog.table_information.color(_elements.first)} /* Group of ? */"
564 redef fun compile_macros(v, value)
565 do
566 var i = 0
567 for e in _elements do
568 e.compile_macros(v, "{value} + {i}")
569 i += 1
570 end
571 end
572 end
573
574 # An element that represents a class property
575 abstract class TableEltProp
576 special TableElt
577 var _property: MMLocalProperty
578
579 init(p: MMLocalProperty)
580 do
581 _property = p
582 end
583 end
584
585 # An element that represents a function pointer to a global method
586 class TableEltMeth
587 special TableEltProp
588 redef fun compile_macros(v, value)
589 do
590 var pg = _property.global
591 v.add_decl("#define {pg.meth_call}(recv) (({pg.intro.cname}_t)CALL((recv), ({value})))")
592 end
593
594 redef fun compile_to_c(v, c)
595 do
596 var p = c[_property.global]
597 return p.cname
598 end
599 end
600
601 # An element that represents a function pointer to the super method of a local method
602 class TableEltSuper
603 special TableEltProp
604 redef fun compile_macros(v, value)
605 do
606 var p = _property
607 v.add_decl("#define {p.super_meth_call}(recv) (({p.cname}_t)CALL((recv), ({value})))")
608 end
609
610 redef fun compile_to_c(v, c)
611 do
612 var pc = _property.local_class
613 var g = _property.global
614 var lin = c.che.linear_extension
615 var found = false
616 for s in lin do
617 #print "{c.module}::{c} for {pc.module}::{pc}::{_property} try {s.module}:{s}"
618 if s == pc then
619 found = true
620 else if found and c.che < s then
621 if s.has_global_property(g) then
622 #print "found {s.module}::{s}::{p}"
623 return s[g].cname
624 end
625 end
626 end
627 abort
628 end
629 end
630
631 # An element that represents the value stored for a global attribute
632 class TableEltAttr
633 special TableEltProp
634 redef fun compile_macros(v, value)
635 do
636 var pg = _property.global
637 v.add_decl("#define {pg.attr_access}(recv) ATTR(recv, ({value}))")
638 end
639
640 redef fun compile_to_c(v, c)
641 do
642 var prog = v.program
643 var p = c[_property.global]
644 return "/* {prog.table_information.color(self)}: Attribute {c}::{p} */"
645 end
646 end
647
648 # An element representing a class information
649 class AbsTableEltClass
650 special AbsTableElt
651 # The local class where the information comes from
652 var _local_class: MMLocalClass
653
654 init(c: MMLocalClass)
655 do
656 _local_class = c
657 end
658
659 # The C macro name refering the value
660 fun symbol: String is abstract
661
662 redef fun compile_macros(v, value)
663 do
664 v.add_decl("#define {symbol} ({value})")
665 end
666 end
667
668 # An element of a class table representing a class information
669 class TableEltClass
670 special TableElt
671 special AbsTableEltClass
672 redef fun is_related_to(c)
673 do
674 var bc = c.module[_local_class.global]
675 return c.cshe <= bc
676 end
677 end
678
679 # An element representing the id of a class in a module table
680 class TableEltClassId
681 special ModuleTableElt
682 special AbsTableEltClass
683 redef fun symbol do return _local_class.global.id_id
684
685 redef fun value(prog)
686 do
687 return "{prog.compiled_classes[_local_class.global].id} /* Id of {_local_class} */"
688 end
689 end
690
691 # An element representing the constructor marker position in a class table
692 class TableEltClassInitTable
693 special TableEltClass
694 redef fun symbol do return _local_class.global.init_table_pos_id
695
696 redef fun compile_to_c(v, c)
697 do
698 var prog = v.program
699 var cc = prog.compiled_classes[_local_class.global]
700 var linext = c.cshe.reverse_linear_extension
701 var i = 0
702 while linext[i].global != _local_class.global do
703 i += 1
704 end
705 return "{i} /* {prog.table_information.color(self)}: {c} < {cc.local_class}: superclass init_table position */"
706 end
707 end
708
709 # An element used for a cast
710 # Note: this element is both a TableElt and a ModuleTableElt.
711 # At the TableElt offset, there is the id of the super-class
712 # At the ModuleTableElt offset, there is the TableElt offset (ie. the color of the super-class).
713 class TableEltClassColor
714 special TableEltClass
715 special ModuleTableElt
716 redef fun symbol do return _local_class.global.color_id
717
718 redef fun value(prog)
719 do
720 return "{prog.table_information.color(self)} /* Color of {_local_class} */"
721 end
722
723 redef fun compile_to_c(v, c)
724 do
725 var prog = v.program
726 var cc = prog.compiled_classes[_local_class.global]
727 return "{cc.id} /* {prog.table_information.color(self)}: {c} < {cc.local_class}: superclass typecheck marker */"
728 end
729 end
730
731 # A Group of elements introduced in the same global-class that are colored together
732 class TableEltComposite
733 special TableElt
734 var _table: Array[TableElt]
735 var _cc: CompiledClass
736 var _offsets: HashMap[MMLocalClass, Int]
737 redef fun length do return _table.length
738 redef fun is_related_to(c) do return c.cshe <= _cc.local_class
739
740 fun add(c: MMLocalClass, tab: Array[TableElt])
741 do
742 _offsets[c] = _table.length
743 _table.append(tab)
744 end
745
746 redef fun item(i) do return _table[i]
747
748 redef fun compile_to_c(v, c) do abort
749
750 init(cc: CompiledClass)
751 do
752 _cc = cc
753 _table = new Array[TableElt]
754 _offsets = new HashMap[MMLocalClass, Int]
755 end
756 end
757
758 # The element that represent the class id
759 class TableEltClassSelfId
760 special TableElt
761 redef fun is_related_to(c) do return true
762 redef fun compile_to_c(v, c)
763 do
764 var prog = v.program
765 return "{prog.compiled_classes[c.global].id} /* {prog.table_information.color(self)}: Identity */"
766 end
767 end
768
769
770 # The element that represent the Object Size
771 class TableEltClassObjectSize
772 special TableElt
773 redef fun is_related_to(c) do return true
774 redef fun compile_to_c(v, c)
775 do
776 var nb = 0
777 var p = v.program
778 if c.name == "NativeArray".to_symbol then
779 nb = -1
780 else
781 var cc = p.compiled_classes[c.global]
782 var itab = cc.instance_table
783 for e in itab do
784 nb += 1
785 end
786 end
787 return "{nb} /* {p.table_information.color(self)}: Object size (-1 if a NativeArray)*/"
788 end
789 end
790
791 # The element that represent the object id
792 class TableEltObjectId
793 special TableElt
794 redef fun is_related_to(c) do return true
795 redef fun compile_to_c(v, c)
796 do
797 var p = v.program
798 return "/* {p.table_information.color(self)}: Object_id */"
799 end
800 end
801
802 # The element that
803 class TableEltVftPointer
804 special TableElt
805 redef fun is_related_to(c) do return true
806 redef fun compile_to_c(v, c)
807 do
808 var prog = v.program
809 return "/* {prog.table_information.color(self)}: Pointer to the classtable */"
810 end
811 end
812
813 ###############################################################################
814
815 # Used to sort local class in a deterministic total order
816 # The total order superset the class refinement and the class specialisation relations
817 class ClassSorter
818 special AbstractSorter[MMLocalClass]
819 redef fun compare(a, b) do return a.compare(b)
820 init do end
821 end
822
823 redef class MMLocalClass
824 # Comparaison in a total order that superset the class refinement and the class specialisation relations
825 fun compare(b: MMLocalClass): Int
826 do
827 var a = self
828 if a == b then
829 return 0
830 else if a.module.mhe < b.module then
831 return 1
832 else if b.module.mhe < a.module then
833 return -1
834 end
835 var ar = a.cshe.rank
836 var br = b.cshe.rank
837 if ar > br then
838 return 1
839 else if br > ar then
840 return -1
841 else
842 return b.name.to_s <=> a.name.to_s
843 end
844 end
845
846 # Declaration and macros related to the class table
847 fun declare_tables_to_c(v: GlobalCompilerVisitor)
848 do
849 v.add_decl("")
850 var pi = primitive_info
851 v.add_decl("extern const classtable_elt_t VFT_{name}[];")
852 if name == "NativeArray".to_symbol then
853 v.add_decl("val_t NEW_NativeArray(size_t length, size_t size);")
854 else if pi == null then
855 # v.add_decl("val_t NEW_{name}(void);")
856 else if not pi.tagged then
857 var t = pi.cname
858 var tbox = "struct TBOX_{name}"
859 v.add_decl("{tbox} \{ const classtable_elt_t * vft; bigint object_id; {t} val;};")
860 v.add_decl("val_t BOX_{name}({t} val);")
861 v.add_decl("#define UNBOX_{name}(x) ((({tbox} *)(VAL2OBJ(x)))->val)")
862 end
863 end
864
865 # Compilation of table and new (or box)
866 fun compile_tables_to_c(v: GlobalCompilerVisitor)
867 do
868 var cc = v.program.compiled_classes[self.global]
869 var ctab = cc.class_table
870 var clen = ctab.length
871 if v.program.table_information.max_class_table_length > ctab.length then
872 clen = v.program.table_information.max_class_table_length
873 end
874
875 v.add_instr("const classtable_elt_t VFT_{name}[{clen}] = \{")
876 v.indent
877 for e in ctab do
878 if e == null then
879 v.add_instr("\{0} /* Class Hole :( */,")
880 else
881 v.add_instr("\{(bigint) {e.compile_to_c(v, self)}},")
882 end
883 end
884 if clen > ctab.length then
885 v.add_instr("\{0},"*(clen-ctab.length))
886 end
887 v.unindent
888 v.add_instr("};")
889 var itab = cc.instance_table
890 for e in itab do
891 if e == null then
892 v.add_instr("/* Instance Hole :( */")
893 else
894 v.add_instr(e.compile_to_c(v, self))
895 end
896 end
897
898 var pi = primitive_info
899 if name == "NativeArray".to_symbol then
900 v.add_instr("val_t NEW_NativeArray(size_t length, size_t size) \{")
901 v.indent
902 v.add_instr("Nit_NativeArray array;")
903 v.add_instr("array = (Nit_NativeArray)alloc(sizeof(struct Nit_NativeArray) + ((length - 1) * size));")
904 v.add_instr("array->vft = (classtable_elt_t*)VFT_{name};")
905 v.add_instr("array->object_id = object_id_counter;")
906 v.add_instr("object_id_counter = object_id_counter + 1;")
907 v.add_instr("array->size = length;")
908 v.add_instr("return OBJ2VAL(array);")
909 v.unindent
910 v.add_instr("}")
911 else if pi == null then
912 do
913 # Generate INIT_ATTRIBUTES routine
914 var iself = new IRegister(get_type)
915 var iselfa = [iself]
916 var iroutine = new IRoutine(iselfa, null)
917 var icb = new ICodeBuilder(module, iroutine)
918
919 for g in global_properties do
920 var p = self[g]
921 var t = p.signature.return_type
922 if p isa MMAttribute and t != null then
923 var ir = p.iroutine
924 if ir == null then continue
925 # FIXME: Not compatible with sep compilation
926 var e = icb.inline_routine(ir, iselfa, null).as(not null)
927 icb.stmt(new IAttrWrite(p, iself, e))
928 end
929 end
930
931 var cname = "INIT_ATTRIBUTES__{name}"
932 var args = iroutine.compile_signature_to_c(v, cname, "init attributes of {name}", null, null)
933 var ctx_old = v.ctx
934 v.ctx = new CContext
935 iroutine.compile_to_c(v, cname, args)
936 ctx_old.append(v.ctx)
937 v.ctx = ctx_old
938 v.unindent
939 v.add_instr("}")
940 end
941 do
942 # Generate NEW routine
943 v.add_decl("val_t NEW_{name}(void);")
944 v.add_instr("val_t NEW_{name}(void)")
945 v.add_instr("\{")
946 v.indent
947 v.add_instr("obj_t obj;")
948 v.add_instr("obj = alloc(sizeof(val_t) * {itab.length});")
949 v.add_instr("obj->vft = (classtable_elt_t*)VFT_{name};")
950 v.add_instr("obj[1].object_id = object_id_counter;")
951 v.add_instr("object_id_counter = object_id_counter + 1;")
952 v.add_instr("return OBJ2VAL(obj);")
953 v.unindent
954 v.add_instr("}")
955 end
956 do
957 # Compile CHECKNAME
958 var iself = new IRegister(get_type)
959 var iselfa = [iself]
960 var iroutine = new IRoutine(iselfa, null)
961 var icb = new ICodeBuilder(module, iroutine)
962 for g in global_properties do
963 var p = self[g]
964 var t = p.signature.return_type
965 if p isa MMAttribute and t != null and not t.is_nullable then
966 icb.add_attr_check(p, iself)
967 end
968 end
969 var cname = "CHECKNEW_{name}"
970 var args = iroutine.compile_signature_to_c(v, cname, "check new {name}", null, null)
971 var ctx_old = v.ctx
972 v.ctx = new CContext
973 iroutine.compile_to_c(v, cname, args)
974 ctx_old.append(v.ctx)
975 v.ctx = ctx_old
976 v.unindent
977 v.add_instr("}")
978 end
979
980 var init_table_size = cshe.greaters.length + 1
981 var init_table_decl = "int init_table[{init_table_size}] = \{0{", 0" * (init_table_size-1)}};"
982
983 for g in global_properties do
984 var p = self[g]
985 # FIXME skip invisible constructors
986 if not p.global.is_init_for(self) then continue
987 assert p isa MMMethod
988
989 var iself = new IRegister(get_type)
990 var iparams = new Array[IRegister]
991 for i in [0..p.signature.arity[ do iparams.add(new IRegister(p.signature[i]))
992 var iroutine = new IRoutine(iparams, iself)
993 iroutine.location = p.iroutine.location
994 var icb = new ICodeBuilder(module, iroutine)
995
996 var inew = new IAllocateInstance(get_type)
997 inew.result = iself
998 icb.stmt(inew)
999 var iargs = [iself]
1000 iargs.add_all(iparams)
1001
1002 icb.stmt(new IInitAttributes(get_type, iself))
1003 icb.stmt(new IStaticCall(p, iargs))
1004 icb.stmt(new ICheckInstance(get_type, iself))
1005
1006 var cname = "NEW_{self}_{p.global.intro.cname}"
1007 var new_args = iroutine.compile_signature_to_c(v, cname, "new {self} {p.full_name}", null, null)
1008 var ctx_old = v.ctx
1009 v.ctx = new CContext
1010 v.add_instr(init_table_decl)
1011 var e = iroutine.compile_to_c(v, cname, new_args).as(not null)
1012 v.add_instr("return {e};")
1013 ctx_old.append(v.ctx)
1014 v.ctx = ctx_old
1015 v.unindent
1016 v.add_instr("}")
1017 end
1018 else if not pi.tagged then
1019 var t = pi.cname
1020 var tbox = "struct TBOX_{name}"
1021 v.add_instr("val_t BOX_{name}({t} val) \{")
1022 v.indent
1023 v.add_instr("{tbox} *box = ({tbox}*)alloc(sizeof({tbox}));")
1024 v.add_instr("box->vft = VFT_{name};")
1025 v.add_instr("box->val = val;")
1026 v.add_instr("box->object_id = object_id_counter;")
1027 v.add_instr("object_id_counter = object_id_counter + 1;")
1028 v.add_instr("return OBJ2VAL(box);")
1029 v.unindent
1030 v.add_instr("}")
1031 end
1032 end
1033 end
1034
1035 redef class MMMethod
1036 fun compile_property_to_c(v: CompilerVisitor)
1037 do
1038 var ir = iroutine
1039 assert ir != null
1040
1041 var more_params: nullable String = null
1042 if global.is_init then more_params = "int* init_table"
1043 var args = ir.compile_signature_to_c(v, cname, full_name, null, more_params)
1044 var ctx_old = v.ctx
1045 v.ctx = new CContext
1046
1047 v.out_contexts.clear
1048
1049 var itpos: nullable String = null
1050 if global.is_init then
1051 itpos = "itpos{v.new_number}"
1052 v.add_decl("int {itpos} = VAL2OBJ({args.first})->vft[{local_class.global.init_table_pos_id}].i;")
1053 v.add_instr("if (init_table[{itpos}]) return;")
1054 end
1055
1056 var s = ir.compile_to_c(v, cname, args)
1057
1058 if itpos != null then
1059 v.add_instr("init_table[{itpos}] = 1;")
1060 end
1061 if s == null then
1062 v.add_instr("return;")
1063 else
1064 v.add_instr("return ", s, ";")
1065 end
1066
1067 ctx_old.append(v.ctx)
1068 v.ctx = ctx_old
1069 v.unindent
1070 v.add_instr("}")
1071
1072 for ctx in v.out_contexts do v.ctx.merge(ctx)
1073 end
1074 end
1075