compile: extract table computation from compiling_global to table_computation
[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 table_computation
21 private import compiling_icode
22
23 class GlobalCompilerVisitor
24 special CompilerVisitor
25 # The global analysis result
26 readable var _program: Program
27 init(m: MMModule, tc: ToolContext, prog: Program)
28 do
29 super(m, tc)
30 _program = prog
31 end
32 end
33
34 redef class Program
35 # Compile module and class tables
36 fun compile_tables_to_c(v: GlobalCompilerVisitor)
37 do
38 for m in module.mhe.greaters_and_self do
39 m.compile_local_table_to_c(v)
40 end
41
42 for c in module.local_classes do
43 c.compile_tables_to_c(v)
44 end
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}")
49 else
50 s.append(", NULL")
51 end
52 end
53 s.append("};")
54 v.add_instr(s.to_s)
55 end
56
57 # Compile main part (for _table.c)
58 fun compile_main_part(v: GlobalCompilerVisitor)
59 do
60 v.add_instr("int main(int argc, char **argv) \{")
61 v.indent
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
66 print("No main")
67 else
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
71 print("No main")
72 else
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);")
77 end
78 end
79 v.add_instr("return 0;")
80 v.unindent
81 v.add_instr("}")
82 end
83 end
84
85 redef class MMModule
86 # Declare class table (for _sep.h)
87 fun declare_class_tables_to_c(v: GlobalCompilerVisitor)
88 do
89 for c in local_classes do
90 if c.global.module == self then
91 c.declare_tables_to_c(v)
92 end
93 end
94 end
95
96 # Compile sep files
97 fun compile_mod_to_c(v: GlobalCompilerVisitor)
98 do
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}[];")
102 end
103 var i = 0
104 for e in local_table do
105 var value: String
106 if v.tc.global then
107 value = "{e.value(v.program)}"
108 else
109 value = "SFT_{name}[{i}]"
110 i = i + 1
111 end
112 e.compile_macros(v, value)
113 end
114 for c in local_classes do
115 if not c isa MMConcreteClass then continue
116 for pg in c.global_properties do
117 var p = c[pg]
118 if p.local_class == c and p isa MMMethod then
119 p.compile_property_to_c(v)
120 end
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}")
126 end
127 v.add_decl("val_t NEW_{c}_{p.global.intro.cname}({params.join(", ")});")
128 end
129 end
130 end
131 end
132
133 # Compile module file for the current module
134 fun compile_local_table_to_c(v: GlobalCompilerVisitor)
135 do
136 v.add_instr("const char *LOCATE_{name} = \"{location.file}\";")
137
138 if v.tc.global or local_table.is_empty then
139 return
140 end
141
142 v.add_instr("const int SFT_{name}[{local_table.length}] = \{")
143 v.indent
144 for e in local_table do
145 v.add_instr(e.value(v.program) + ",")
146 end
147 v.unindent
148 v.add_instr("\};")
149 end
150 end
151
152 ###############################################################################
153
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
157 end
158
159 redef class TableElt
160 # Return the value of the element for a given class
161 fun compile_to_c(v: GlobalCompilerVisitor, c: MMLocalClass): String is abstract
162 end
163
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
167 end
168
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)
172 do
173 var i = 0
174 for e in elements do
175 e.compile_macros(v, "{value} + {i}")
176 i += 1
177 end
178 end
179 end
180
181 redef class TableEltMeth
182 redef fun compile_macros(v, value)
183 do
184 var pg = property.global
185 v.add_decl("#define {pg.meth_call}(recv) (({pg.intro.cname}_t)CALL((recv), ({value})))")
186 end
187
188 redef fun compile_to_c(v, c)
189 do
190 var p = c[property.global]
191 return p.cname
192 end
193 end
194
195 redef class TableEltSuper
196 redef fun compile_macros(v, value)
197 do
198 var p = property
199 v.add_decl("#define {p.super_meth_call}(recv) (({p.cname}_t)CALL((recv), ({value})))")
200 end
201
202 redef fun compile_to_c(v, c)
203 do
204 var pc = property.local_class
205 var g = property.global
206 var lin = c.che.linear_extension
207 var found = false
208 for s in lin do
209 #print "{c.module}::{c} for {pc.module}::{pc}::{_property} try {s.module}:{s}"
210 if s == pc then
211 found = true
212 else if found and c.che < s then
213 if s.has_global_property(g) then
214 #print "found {s.module}::{s}::{p}"
215 return s[g].cname
216 end
217 end
218 end
219 abort
220 end
221 end
222
223 redef class TableEltAttr
224 redef fun compile_macros(v, value)
225 do
226 var pg = property.global
227 v.add_decl("#define {pg.attr_access}(recv) ATTR(recv, ({value}))")
228 end
229
230 redef fun compile_to_c(v, c)
231 do
232 var prog = v.program
233 var p = c[property.global]
234 return "/* {prog.table_information.color(self)}: Attribute {c}::{p} */"
235 end
236 end
237
238 redef class AbsTableEltClass
239 # The C macro name refering the value
240 fun symbol: String is abstract
241
242 redef fun compile_macros(v, value)
243 do
244 v.add_decl("#define {symbol} ({value})")
245 end
246 end
247
248 redef class TableEltClassId
249 redef fun symbol do return local_class.global.id_id
250
251 redef fun value(prog)
252 do
253 return "{prog.compiled_classes[local_class.global].id} /* Id of {local_class} */"
254 end
255 end
256
257 redef class TableEltClassInitTable
258 redef fun symbol do return local_class.global.init_table_pos_id
259
260 redef fun compile_to_c(v, c)
261 do
262 var prog = v.program
263 var cc = prog.compiled_classes[local_class.global]
264 var linext = c.cshe.reverse_linear_extension
265 var i = 0
266 while linext[i].global != local_class.global do
267 i += 1
268 end
269 return "{i} /* {prog.table_information.color(self)}: {c} < {cc.local_class}: superclass init_table position */"
270 end
271 end
272
273 redef class TableEltClassColor
274 redef fun symbol do return local_class.global.color_id
275
276 redef fun value(prog)
277 do
278 return "{prog.table_information.color(self)} /* Color of {local_class} */"
279 end
280
281 redef fun compile_to_c(v, c)
282 do
283 var prog = v.program
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 */"
286 end
287 end
288
289 redef class TableEltComposite
290 redef fun compile_to_c(v, c) do abort
291 end
292
293 redef class TableEltClassSelfId
294 redef fun compile_to_c(v, c)
295 do
296 var prog = v.program
297 return "{prog.compiled_classes[c.global].id} /* {prog.table_information.color(self)}: Identity */"
298 end
299 end
300
301 redef class TableEltClassObjectSize
302 redef fun compile_to_c(v, c)
303 do
304 var nb = 0
305 var p = v.program
306 if c.name == "NativeArray".to_symbol then
307 nb = -1
308 else
309 var cc = p.compiled_classes[c.global]
310 var itab = cc.instance_table
311 for e in itab do
312 nb += 1
313 end
314 end
315 return "{nb} /* {p.table_information.color(self)}: Object size (-1 if a NativeArray)*/"
316 end
317 end
318
319 redef class TableEltObjectId
320 redef fun compile_to_c(v, c)
321 do
322 var p = v.program
323 return "/* {p.table_information.color(self)}: Object_id */"
324 end
325 end
326
327 redef class TableEltVftPointer
328 redef fun compile_to_c(v, c)
329 do
330 var prog = v.program
331 return "/* {prog.table_information.color(self)}: Pointer to the classtable */"
332 end
333 end
334
335 ###############################################################################
336
337 redef class MMLocalClass
338 # Declaration and macros related to the class table
339 fun declare_tables_to_c(v: GlobalCompilerVisitor)
340 do
341 v.add_decl("")
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
349 var t = pi.cname
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)")
354 end
355 end
356
357 # Compilation of table and new (or box)
358 fun compile_tables_to_c(v: GlobalCompilerVisitor)
359 do
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
365 end
366
367 v.add_instr("const classtable_elt_t VFT_{name}[{clen}] = \{")
368 v.indent
369 for e in ctab do
370 if e == null then
371 v.add_instr("\{0} /* Class Hole :( */,")
372 else
373 v.add_instr("\{(bigint) {e.compile_to_c(v, self)}},")
374 end
375 end
376 if clen > ctab.length then
377 v.add_instr("\{0},"*(clen-ctab.length))
378 end
379 v.unindent
380 v.add_instr("};")
381 var itab = cc.instance_table
382 for e in itab do
383 if e == null then
384 v.add_instr("/* Instance Hole :( */")
385 else
386 v.add_instr(e.compile_to_c(v, self))
387 end
388 end
389
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) \{")
393 v.indent
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);")
401 v.unindent
402 v.add_instr("}")
403 else if pi == null then
404 do
405 # Generate INIT_ATTRIBUTES routine
406 var iself = new IRegister(get_type)
407 var iselfa = [iself]
408 var iroutine = new IRoutine(iselfa, null)
409 var icb = new ICodeBuilder(module, iroutine)
410
411 for g in global_properties do
412 var p = self[g]
413 var t = p.signature.return_type
414 if p isa MMAttribute and t != null then
415 var ir = p.iroutine
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))
420 end
421 end
422
423 var cname = "INIT_ATTRIBUTES__{name}"
424 var args = iroutine.compile_signature_to_c(v, cname, "init attributes of {name}", null, null)
425 var ctx_old = v.ctx
426 v.ctx = new CContext
427 iroutine.compile_to_c(v, cname, args)
428 ctx_old.append(v.ctx)
429 v.ctx = ctx_old
430 v.unindent
431 v.add_instr("}")
432 end
433 do
434 # Generate NEW routine
435 v.add_decl("val_t NEW_{name}(void);")
436 v.add_instr("val_t NEW_{name}(void)")
437 v.add_instr("\{")
438 v.indent
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);")
445 v.unindent
446 v.add_instr("}")
447 end
448 do
449 # Compile CHECKNAME
450 var iself = new IRegister(get_type)
451 var iselfa = [iself]
452 var iroutine = new IRoutine(iselfa, null)
453 var icb = new ICodeBuilder(module, iroutine)
454 for g in global_properties do
455 var p = self[g]
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)
459 end
460 end
461 var cname = "CHECKNEW_{name}"
462 var args = iroutine.compile_signature_to_c(v, cname, "check new {name}", null, null)
463 var ctx_old = v.ctx
464 v.ctx = new CContext
465 iroutine.compile_to_c(v, cname, args)
466 ctx_old.append(v.ctx)
467 v.ctx = ctx_old
468 v.unindent
469 v.add_instr("}")
470 end
471
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)}};"
474
475 for g in global_properties do
476 var p = self[g]
477 # FIXME skip invisible constructors
478 if not p.global.is_init_for(self) then continue
479 assert p isa MMMethod
480
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)
487
488 var inew = new IAllocateInstance(get_type)
489 inew.result = iself
490 icb.stmt(inew)
491 var iargs = [iself]
492 iargs.add_all(iparams)
493
494 icb.stmt(new IInitAttributes(get_type, iself))
495 icb.stmt(new IStaticCall(p, iargs))
496 icb.stmt(new ICheckInstance(get_type, iself))
497
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)
500 var ctx_old = v.ctx
501 v.ctx = new CContext
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)
506 v.ctx = ctx_old
507 v.unindent
508 v.add_instr("}")
509 end
510 else if not pi.tagged then
511 var t = pi.cname
512 var tbox = "struct TBOX_{name}"
513 v.add_instr("val_t BOX_{name}({t} val) \{")
514 v.indent
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);")
521 v.unindent
522 v.add_instr("}")
523 end
524 end
525 end
526
527 redef class MMMethod
528 fun compile_property_to_c(v: CompilerVisitor)
529 do
530 var ir = iroutine
531 assert ir != null
532
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)
536 var ctx_old = v.ctx
537 v.ctx = new CContext
538
539 v.out_contexts.clear
540
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;")
546 end
547
548 var s = ir.compile_to_c(v, cname, args)
549
550 if itpos != null then
551 v.add_instr("init_table[{itpos}] = 1;")
552 end
553 if s == null then
554 v.add_instr("return;")
555 else
556 v.add_instr("return ", s, ";")
557 end
558
559 ctx_old.append(v.ctx)
560 v.ctx = ctx_old
561 v.unindent
562 v.add_instr("}")
563
564 for ctx in v.out_contexts do v.ctx.merge(ctx)
565 end
566 end
567