1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2008 Jean Privat <jean@pryen.org>
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
9 # http://www.apache.org/licenses/LICENSE-2.0
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.
17 # Compute and generate tables for classes and modules.
18 package compiling_global
20 import table_computation
21 private import compiling_icode
23 class GlobalCompilerVisitor
24 special CompilerVisitor
25 # The global analysis result
26 readable var _program
: Program
27 init(m
: MMModule, tc
: ToolContext, prog
: Program)
35 # Compile module and class tables
36 fun compile_tables_to_c
(v
: GlobalCompilerVisitor)
38 for m
in module.mhe
.greaters_and_self
do
39 m
.compile_local_table_to_c
(v
)
42 for c
in module.local_classes
do
43 c
.compile_tables_to_c
(v
)
45 var s
= new Buffer.from
("classtable_t TAG2VFT[4] = \{NULL")
46 for t
in ["Int","Char","Bool"] do
47 if module.has_global_class_named
(t
.to_symbol
) then
48 s
.append
(", (const classtable_t)VFT_{t}")
57 # Compile main part (for _table.c)
58 fun compile_main_part
(v
: GlobalCompilerVisitor)
60 v
.add_instr
("int main(int argc, char **argv) \{")
62 v
.add_instr
("prepare_signals();")
63 v
.add_instr
("glob_argc = argc; glob_argv = argv;")
64 var sysname
= once
"Sys".to_symbol
65 if not module.has_global_class_named
(sysname
) then
68 var sys
= module.class_by_name
(sysname
)
69 var name
= once
"main".to_symbol
70 if not sys
.has_global_property_by_name
(name
) then
73 var mainm
= sys
.select_method
(name
)
74 v
.add_instr
("G_sys = NEW_Sys();")
75 v
.add_instr
("register_static_object(&G_sys);")
76 v
.add_instr
("{mainm.cname}(G_sys);")
79 v
.add_instr
("return 0;")
86 # Declare class table (for _sep.h)
87 fun declare_class_tables_to_c
(v
: GlobalCompilerVisitor)
89 for c
in local_classes
do
90 if c
.global
.module == self then
91 c
.declare_tables_to_c
(v
)
97 fun compile_mod_to_c
(v
: GlobalCompilerVisitor)
99 v
.add_decl
("extern const char *LOCATE_{name};")
100 if not v
.tc
.global
then
101 v
.add_decl
("extern const int SFT_{name}[];")
104 for e
in local_table
do
107 value
= "{e.value(v.program)}"
109 value
= "SFT_{name}[{i}]"
112 e
.compile_macros
(v
, value
)
114 for c
in local_classes
do
115 if not c
isa MMConcreteClass then continue
116 for pg
in c
.global_properties
do
118 if p
.local_class
== c
and p
isa MMMethod then
119 p
.compile_property_to_c
(v
)
121 if pg
.is_init_for
(c
) then
122 # Declare constructors
123 var params
= new Array[String]
124 for j
in [0..p
.signature
.arity
[ do
125 params
.add
("val_t p{j}")
127 v
.add_decl
("val_t NEW_{c}_{p.global.intro.cname}({params.join(", ")});")
133 # Compile module file for the current module
134 fun compile_local_table_to_c
(v
: GlobalCompilerVisitor)
136 v
.add_instr
("const char *LOCATE_{name} = \"{location.file}\
";")
138 if v
.tc
.global
or local_table
.is_empty
then
142 v
.add_instr
("const int SFT_{name}[{local_table.length}] = \{")
144 for e
in local_table
do
145 v
.add_instr
(e
.value
(v
.program
) + ",")
152 ###############################################################################
154 redef class AbsTableElt
155 # Compile the macro needed to use the element and other related elements
156 fun compile_macros
(v
: GlobalCompilerVisitor, value
: String) is abstract
160 # Return the value of the element for a given class
161 fun compile_to_c
(v
: GlobalCompilerVisitor, c
: MMLocalClass): String is abstract
164 redef class ModuleTableElt
165 # Return the value of the element once the global analisys is performed
166 fun value
(prog
: Program): String is abstract
169 redef class ModuleTableEltGroup
170 redef fun value
(prog
) do return "{prog.table_information.color(elements.first)} /* Group of ? */"
171 redef fun compile_macros
(v
, value
)
175 e
.compile_macros
(v
, "{value} + {i}")
181 redef class TableEltMeth
182 redef fun compile_macros
(v
, value
)
184 var pg
= property
.global
185 v
.add_decl
("#define {pg.meth_call}(recv) (({pg.intro.cname}_t)CALL((recv), ({value})))")
188 redef fun compile_to_c
(v
, c
)
190 var p
= c
[property
.global
]
195 redef class TableEltSuper
196 redef fun compile_macros
(v
, value
)
199 v
.add_decl
("#define {p.super_meth_call}(recv) (({p.cname}_t)CALL((recv), ({value})))")
202 redef fun compile_to_c
(v
, c
)
204 var pc
= property
.local_class
205 var g
= property
.global
206 var lin
= c
.che
.linear_extension
209 #print "{c.module}::{c} for {pc.module}::{pc}::{_property} try {s.module}:{s}"
212 else if found
and c
.che
< s
then
213 if s
.has_global_property
(g
) then
214 #print "found {s.module}::{s}::{p}"
223 redef class TableEltAttr
224 redef fun compile_macros
(v
, value
)
226 var pg
= property
.global
227 v
.add_decl
("#define {pg.attr_access}(recv) ATTR(recv, ({value}))")
230 redef fun compile_to_c
(v
, c
)
233 var p
= c
[property
.global
]
234 return "/* {prog.table_information.color(self)}: Attribute {c}::{p} */"
238 redef class AbsTableEltClass
239 # The C macro name refering the value
240 fun symbol
: String is abstract
242 redef fun compile_macros
(v
, value
)
244 v
.add_decl
("#define {symbol} ({value})")
248 redef class TableEltClassId
249 redef fun symbol
do return local_class
.global
.id_id
251 redef fun value
(prog
)
253 return "{prog.compiled_classes[local_class.global].id} /* Id of {local_class} */"
257 redef class TableEltClassInitTable
258 redef fun symbol
do return local_class
.global
.init_table_pos_id
260 redef fun compile_to_c
(v
, c
)
263 var cc
= prog
.compiled_classes
[local_class
.global
]
264 var linext
= c
.cshe
.reverse_linear_extension
266 while linext
[i
].global
!= local_class
.global
do
269 return "{i} /* {prog.table_information.color(self)}: {c} < {cc.local_class}: superclass init_table position */"
273 redef class TableEltClassColor
274 redef fun symbol
do return local_class
.global
.color_id
276 redef fun value
(prog
)
278 return "{prog.table_information.color(self)} /* Color of {local_class} */"
281 redef fun compile_to_c
(v
, c
)
284 var cc
= prog
.compiled_classes
[local_class
.global
]
285 return "{cc.id} /* {prog.table_information.color(self)}: {c} < {cc.local_class}: superclass typecheck marker */"
289 redef class TableEltComposite
290 redef fun compile_to_c
(v
, c
) do abort
293 redef class TableEltClassSelfId
294 redef fun compile_to_c
(v
, c
)
297 return "{prog.compiled_classes[c.global].id} /* {prog.table_information.color(self)}: Identity */"
301 redef class TableEltClassObjectSize
302 redef fun compile_to_c
(v
, c
)
306 if c
.name
== "NativeArray".to_symbol
then
309 var cc
= p
.compiled_classes
[c
.global
]
310 var itab
= cc
.instance_table
315 return "{nb} /* {p.table_information.color(self)}: Object size (-1 if a NativeArray)*/"
319 redef class TableEltObjectId
320 redef fun compile_to_c
(v
, c
)
323 return "/* {p.table_information.color(self)}: Object_id */"
327 redef class TableEltVftPointer
328 redef fun compile_to_c
(v
, c
)
331 return "/* {prog.table_information.color(self)}: Pointer to the classtable */"
335 ###############################################################################
337 redef class MMLocalClass
338 # IRoutine for the initialization of the default attributes (called by IInitAttributes)
339 var _init_var_iroutine
: nullable IRoutine = null
340 # IRoutine to validate the instance after initialization (called by ICheckInstance)
341 var _checknew_iroutine
: nullable IRoutine = null
342 # IRoutines to call to create a new valid instance (memory allocated, object initialized and validated)
343 # These iroutines will call: IAllocateInstance, IInitAttributes, some init function and ICheckInstance
344 # These routines will be called by INew
345 var _new_instance_iroutine
: HashMap[MMMethod, IRoutine] = new HashMap[MMMethod, IRoutine]
347 # Declaration and macros related to the class table
348 fun declare_tables_to_c
(v
: GlobalCompilerVisitor)
351 var pi
= primitive_info
352 v
.add_decl
("extern const classtable_elt_t VFT_{name}[];")
353 if name
== "NativeArray".to_symbol
then
354 v
.add_decl
("val_t NEW_NativeArray(size_t length, size_t size);")
355 else if pi
== null then
356 # v.add_decl("val_t NEW_{name}(void);")
357 else if not pi
.tagged
then
359 var tbox
= "struct TBOX_{name}"
360 v
.add_decl
("{tbox} \{ const classtable_elt_t * vft; bigint object_id; {t} val;};")
361 v
.add_decl
("val_t BOX_{name}({t} val);")
362 v
.add_decl
("#define UNBOX_{name}(x) ((({tbox} *)(VAL2OBJ(x)))->val)")
366 # Generation of allocation function of this class
367 fun generate_allocation_iroutines
(prog
: Program)
369 var cc
= prog
.compiled_classes
[self.global
]
371 var pi
= primitive_info
374 # Generate INIT_ATTRIBUTES routine
375 var iself
= new IRegister(get_type
)
377 var iroutine
= new IRoutine(iselfa
, null)
378 var icb
= new ICodeBuilder(module, iroutine
)
380 for g
in global_properties
do
382 var t
= p
.signature
.return_type
383 if p
isa MMAttribute and t
!= null then
385 if ir
== null then continue
386 # FIXME: Not compatible with sep compilation
387 var e
= icb
.inline_routine
(ir
, iselfa
, null).as(not null)
388 icb
.stmt
(new IAttrWrite(p
, iself
, e
))
392 _init_var_iroutine
= iroutine
396 var iself
= new IRegister(get_type
)
398 var iroutine
= new IRoutine(iselfa
, null)
399 var icb
= new ICodeBuilder(module, iroutine
)
400 for g
in global_properties
do
402 var t
= p
.signature
.return_type
403 if p
isa MMAttribute and t
!= null and not t
.is_nullable
then
404 icb
.add_attr_check
(p
, iself
)
408 _checknew_iroutine
= iroutine
411 var init_table_size
= cshe
.greaters
.length
+ 1
413 for g
in global_properties
do
415 # FIXME skip invisible constructors
416 if not p
.global
.is_init_for
(self) then continue
417 assert p
isa MMMethod
419 var iself
= new IRegister(get_type
)
420 var iparams
= new Array[IRegister]
421 for i
in [0..p
.signature
.arity
[ do iparams
.add
(new IRegister(p
.signature
[i
]))
422 var iroutine
= new IRoutine(iparams
, iself
)
423 iroutine
.location
= p
.iroutine
.location
424 var icb
= new ICodeBuilder(module, iroutine
)
426 var inew
= new IAllocateInstance(get_type
)
430 iargs
.add_all
(iparams
)
432 icb
.stmt
(new IInitAttributes(get_type
, iself
))
433 icb
.stmt
(new IStaticCall(p
, iargs
))
434 icb
.stmt
(new ICheckInstance(get_type
, iself
))
436 _new_instance_iroutine
[p
] = iroutine
441 # Compilation of table and new (or box)
442 fun compile_tables_to_c
(v
: GlobalCompilerVisitor)
444 var cc
= v
.program
.compiled_classes
[self.global
]
445 var ctab
= cc
.class_table
446 var clen
= ctab
.length
447 if v
.program
.table_information
.max_class_table_length
> ctab
.length
then
448 clen
= v
.program
.table_information
.max_class_table_length
451 v
.add_instr
("const classtable_elt_t VFT_{name}[{clen}] = \{")
455 v
.add_instr
("\{0} /* Class Hole :( */,")
457 v
.add_instr
("\{(bigint) {e.compile_to_c(v, self)}},")
460 if clen
> ctab
.length
then
461 v
.add_instr
("\{0},"*(clen-ctab
.length
))
465 var itab
= cc
.instance_table
468 v
.add_instr
("/* Instance Hole :( */")
470 v
.add_instr
(e
.compile_to_c
(v
, self))
474 var pi
= primitive_info
475 if name
== "NativeArray".to_symbol
then
476 v
.add_instr
("val_t NEW_NativeArray(size_t length, size_t size) \{")
478 v
.add_instr
("Nit_NativeArray array;")
479 v
.add_instr
("array = (Nit_NativeArray)alloc(sizeof(struct Nit_NativeArray) + ((length - 1) * size));")
480 v
.add_instr
("array->vft = (classtable_elt_t*)VFT_{name};")
481 v
.add_instr
("array->object_id = object_id_counter;")
482 v
.add_instr
("object_id_counter = object_id_counter + 1;")
483 v
.add_instr
("array->size = length;")
484 v
.add_instr
("return OBJ2VAL(array);")
487 else if pi
== null then
489 # Generate INIT_ATTRIBUTES routine
490 var cname
= "INIT_ATTRIBUTES__{name}"
491 var args
= _init_var_iroutine
.compile_signature_to_c
(v
, cname
, "init var of {name}", null, null)
494 _init_var_iroutine
.compile_to_c
(v
, cname
, args
)
495 ctx_old
.append
(v
.ctx
)
501 # Generate NEW routine
502 v
.add_decl
("val_t NEW_{name}(void);")
503 v
.add_instr
("val_t NEW_{name}(void)")
506 v
.add_instr
("obj_t obj;")
507 v
.add_instr
("obj = alloc(sizeof(val_t) * {itab.length});")
508 v
.add_instr
("obj->vft = (classtable_elt_t*)VFT_{name};")
509 v
.add_instr
("obj[1].object_id = object_id_counter;")
510 v
.add_instr
("object_id_counter = object_id_counter + 1;")
511 v
.add_instr
("return OBJ2VAL(obj);")
517 var cname
= "CHECKNEW_{name}"
518 var args
= _checknew_iroutine
.compile_signature_to_c
(v
, cname
, "check new {name}", null, null)
521 _checknew_iroutine
.compile_to_c
(v
, cname
, args
)
522 ctx_old
.append
(v
.ctx
)
528 var init_table_size
= cshe
.greaters
.length
+ 1
529 var init_table_decl
= "int init_table[{init_table_size}] = \{0{", 0" * (init_table_size-1)}};"
531 for g
in global_properties
do
533 # FIXME skip invisible constructors
534 if not p
.global
.is_init_for
(self) then continue
535 assert p
isa MMMethod
537 var cname
= "NEW_{self}_{p.global.intro.cname}"
538 var new_args
= _new_instance_iroutine
[p
].compile_signature_to_c
(v
, cname
, "new {self} {p.full_name}", null, null)
541 v
.add_instr
(init_table_decl
)
542 var e
= _new_instance_iroutine
[p
].compile_to_c
(v
, cname
, new_args
).as(not null)
543 v
.add_instr
("return {e};")
544 ctx_old
.append
(v
.ctx
)
549 else if not pi
.tagged
then
551 var tbox
= "struct TBOX_{name}"
552 v
.add_instr
("val_t BOX_{name}({t} val) \{")
554 v
.add_instr
("{tbox} *box = ({tbox}*)alloc(sizeof({tbox}));")
555 v
.add_instr
("box->vft = VFT_{name};")
556 v
.add_instr
("box->val = val;")
557 v
.add_instr
("box->object_id = object_id_counter;")
558 v
.add_instr
("object_id_counter = object_id_counter + 1;")
559 v
.add_instr
("return OBJ2VAL(box);")
567 fun compile_property_to_c
(v
: CompilerVisitor)
572 var more_params
: nullable String = null
573 if global
.is_init
then more_params
= "int* init_table"
574 var args
= ir
.compile_signature_to_c
(v
, cname
, full_name
, null, more_params
)
580 var itpos
: nullable String = null
581 if global
.is_init
then
582 itpos
= "itpos{v.new_number}"
583 v
.add_decl
("int {itpos} = VAL2OBJ({args.first})->vft[{local_class.global.init_table_pos_id}].i;")
584 v
.add_instr
("if (init_table[{itpos}]) return;")
587 var s
= ir
.compile_to_c
(v
, cname
, args
)
589 if itpos
!= null then
590 v
.add_instr
("init_table[{itpos}] = 1;")
593 v
.add_instr
("return;")
595 v
.add_instr
("return ", s
, ";")
598 ctx_old
.append
(v
.ctx
)
603 for ctx
in v
.out_contexts
do v
.ctx
.merge
(ctx
)