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 # Declaration and macros related to the class table
339 fun declare_tables_to_c
(v
: GlobalCompilerVisitor)
342 var pi
= primitive_info
343 v
.add_decl
("extern const classtable_elt_t VFT_{name}[];")
344 if name
== "NativeArray".to_symbol
then
345 v
.add_decl
("val_t NEW_NativeArray(size_t length, size_t size);")
346 else if pi
== null then
347 # v.add_decl("val_t NEW_{name}(void);")
348 else if not pi
.tagged
then
350 var tbox
= "struct TBOX_{name}"
351 v
.add_decl
("{tbox} \{ const classtable_elt_t * vft; bigint object_id; {t} val;};")
352 v
.add_decl
("val_t BOX_{name}({t} val);")
353 v
.add_decl
("#define UNBOX_{name}(x) ((({tbox} *)(VAL2OBJ(x)))->val)")
357 # Compilation of table and new (or box)
358 fun compile_tables_to_c
(v
: GlobalCompilerVisitor)
360 var cc
= v
.program
.compiled_classes
[self.global
]
361 var ctab
= cc
.class_table
362 var clen
= ctab
.length
363 if v
.program
.table_information
.max_class_table_length
> ctab
.length
then
364 clen
= v
.program
.table_information
.max_class_table_length
367 v
.add_instr
("const classtable_elt_t VFT_{name}[{clen}] = \{")
371 v
.add_instr
("\{0} /* Class Hole :( */,")
373 v
.add_instr
("\{(bigint) {e.compile_to_c(v, self)}},")
376 if clen
> ctab
.length
then
377 v
.add_instr
("\{0},"*(clen-ctab
.length
))
381 var itab
= cc
.instance_table
384 v
.add_instr
("/* Instance Hole :( */")
386 v
.add_instr
(e
.compile_to_c
(v
, self))
390 var pi
= primitive_info
391 if name
== "NativeArray".to_symbol
then
392 v
.add_instr
("val_t NEW_NativeArray(size_t length, size_t size) \{")
394 v
.add_instr
("Nit_NativeArray array;")
395 v
.add_instr
("array = (Nit_NativeArray)alloc(sizeof(struct Nit_NativeArray) + ((length - 1) * size));")
396 v
.add_instr
("array->vft = (classtable_elt_t*)VFT_{name};")
397 v
.add_instr
("array->object_id = object_id_counter;")
398 v
.add_instr
("object_id_counter = object_id_counter + 1;")
399 v
.add_instr
("array->size = length;")
400 v
.add_instr
("return OBJ2VAL(array);")
403 else if pi
== null then
405 # Generate INIT_ATTRIBUTES routine
406 var iself
= new IRegister(get_type
)
408 var iroutine
= new IRoutine(iselfa
, null)
409 var icb
= new ICodeBuilder(module, iroutine
)
411 for g
in global_properties
do
413 var t
= p
.signature
.return_type
414 if p
isa MMAttribute and t
!= null then
416 if ir
== null then continue
417 # FIXME: Not compatible with sep compilation
418 var e
= icb
.inline_routine
(ir
, iselfa
, null).as(not null)
419 icb
.stmt
(new IAttrWrite(p
, iself
, e
))
423 var cname
= "INIT_ATTRIBUTES__{name}"
424 var args
= iroutine
.compile_signature_to_c
(v
, cname
, "init attributes of {name}", null, null)
427 iroutine
.compile_to_c
(v
, cname
, args
)
428 ctx_old
.append
(v
.ctx
)
434 # Generate NEW routine
435 v
.add_decl
("val_t NEW_{name}(void);")
436 v
.add_instr
("val_t NEW_{name}(void)")
439 v
.add_instr
("obj_t obj;")
440 v
.add_instr
("obj = alloc(sizeof(val_t) * {itab.length});")
441 v
.add_instr
("obj->vft = (classtable_elt_t*)VFT_{name};")
442 v
.add_instr
("obj[1].object_id = object_id_counter;")
443 v
.add_instr
("object_id_counter = object_id_counter + 1;")
444 v
.add_instr
("return OBJ2VAL(obj);")
450 var iself
= new IRegister(get_type
)
452 var iroutine
= new IRoutine(iselfa
, null)
453 var icb
= new ICodeBuilder(module, iroutine
)
454 for g
in global_properties
do
456 var t
= p
.signature
.return_type
457 if p
isa MMAttribute and t
!= null and not t
.is_nullable
then
458 icb
.add_attr_check
(p
, iself
)
461 var cname
= "CHECKNEW_{name}"
462 var args
= iroutine
.compile_signature_to_c
(v
, cname
, "check new {name}", null, null)
465 iroutine
.compile_to_c
(v
, cname
, args
)
466 ctx_old
.append
(v
.ctx
)
472 var init_table_size
= cshe
.greaters
.length
+ 1
473 var init_table_decl
= "int init_table[{init_table_size}] = \{0{", 0" * (init_table_size-1)}};"
475 for g
in global_properties
do
477 # FIXME skip invisible constructors
478 if not p
.global
.is_init_for
(self) then continue
479 assert p
isa MMMethod
481 var iself
= new IRegister(get_type
)
482 var iparams
= new Array[IRegister]
483 for i
in [0..p
.signature
.arity
[ do iparams
.add
(new IRegister(p
.signature
[i
]))
484 var iroutine
= new IRoutine(iparams
, iself
)
485 iroutine
.location
= p
.iroutine
.location
486 var icb
= new ICodeBuilder(module, iroutine
)
488 var inew
= new IAllocateInstance(get_type
)
492 iargs
.add_all
(iparams
)
494 icb
.stmt
(new IInitAttributes(get_type
, iself
))
495 icb
.stmt
(new IStaticCall(p
, iargs
))
496 icb
.stmt
(new ICheckInstance(get_type
, iself
))
498 var cname
= "NEW_{self}_{p.global.intro.cname}"
499 var new_args
= iroutine
.compile_signature_to_c
(v
, cname
, "new {self} {p.full_name}", null, null)
502 v
.add_instr
(init_table_decl
)
503 var e
= iroutine
.compile_to_c
(v
, cname
, new_args
).as(not null)
504 v
.add_instr
("return {e};")
505 ctx_old
.append
(v
.ctx
)
510 else if not pi
.tagged
then
512 var tbox
= "struct TBOX_{name}"
513 v
.add_instr
("val_t BOX_{name}({t} val) \{")
515 v
.add_instr
("{tbox} *box = ({tbox}*)alloc(sizeof({tbox}));")
516 v
.add_instr
("box->vft = VFT_{name};")
517 v
.add_instr
("box->val = val;")
518 v
.add_instr
("box->object_id = object_id_counter;")
519 v
.add_instr
("object_id_counter = object_id_counter + 1;")
520 v
.add_instr
("return OBJ2VAL(box);")
528 fun compile_property_to_c
(v
: CompilerVisitor)
533 var more_params
: nullable String = null
534 if global
.is_init
then more_params
= "int* init_table"
535 var args
= ir
.compile_signature_to_c
(v
, cname
, full_name
, null, more_params
)
541 var itpos
: nullable String = null
542 if global
.is_init
then
543 itpos
= "itpos{v.new_number}"
544 v
.add_decl
("int {itpos} = VAL2OBJ({args.first})->vft[{local_class.global.init_table_pos_id}].i;")
545 v
.add_instr
("if (init_table[{itpos}]) return;")
548 var s
= ir
.compile_to_c
(v
, cname
, args
)
550 if itpos
!= null then
551 v
.add_instr
("init_table[{itpos}] = 1;")
554 v
.add_instr
("return;")
556 v
.add_instr
("return ", s
, ";")
559 ctx_old
.append
(v
.ctx
)
564 for ctx
in v
.out_contexts
do v
.ctx
.merge
(ctx
)