1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2014 Julien Pagès <julien.pages@lirmm.fr>
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 # Implementation of the Nit virtual machine
20 import interpreter
::naive_interpreter
22 import perfect_hashing
24 redef class ModelBuilder
25 redef fun run_naive_interpreter
(mainmodule
: MModule, arguments
: Array[String])
28 self.toolcontext
.info
("*** NITVM STARTING ***", 1)
30 var interpreter
= new VirtualMachine(self, mainmodule
, arguments
)
31 interpreter
.start
(mainmodule
)
34 self.toolcontext
.info
("*** NITVM STOPPING : {time1-time0} ***", 2)
38 # A virtual machine based on the naive_interpreter
39 class VirtualMachine super NaiveInterpreter
41 # Perfect hashing and perfect numbering
42 var ph
: Perfecthashing = new Perfecthashing
44 # Handles memory allocated in C
45 var memory_manager
: MemoryManager = new MemoryManager
47 # The unique instance of the `MInit` value
48 var initialization_value
: Instance
50 init(modelbuilder
: ModelBuilder, mainmodule
: MModule, arguments
: Array[String])
52 var init_type
= new MInitType(mainmodule
.model
)
53 initialization_value
= new MutableInstance(init_type
)
57 # Subtyping test for the virtual machine
58 redef fun is_subtype
(sub
, sup
: MType): Bool
60 var anchor
= self.frame
.arguments
.first
.mtype
.as(MClassType)
61 var sup_accept_null
= false
62 if sup
isa MNullableType then
63 sup_accept_null
= true
65 else if sup
isa MNullType then
66 sup_accept_null
= true
69 # Can `sub` provides null or not?
70 # Thus we can match with `sup_accept_null`
71 # Also discard the nullable marker if it exists
72 if sub
isa MNullableType then
73 if not sup_accept_null
then return false
75 else if sub
isa MNullType then
76 return sup_accept_null
78 # Now the case of direct null and nullable is over
80 # An unfixed formal type can only accept itself
81 if sup
isa MParameterType or sup
isa MVirtualType then
85 if sub
isa MParameterType or sub
isa MVirtualType then
86 sub
= sub
.anchor_to
(mainmodule
, anchor
)
87 # Manage the second layer of null/nullable
88 if sub
isa MNullableType then
89 if not sup_accept_null
then return false
91 else if sub
isa MNullType then
92 return sup_accept_null
96 assert sub
isa MClassType
98 # `sup` accepts only null
99 if sup
isa MNullType then return false
101 assert sup
isa MClassType
103 # Create the sup vtable if not create
104 if not sup
.mclass
.loaded
then create_class
(sup
.mclass
)
106 # Sub can be discovered inside a Generic type during the subtyping test
107 if not sub
.mclass
.loaded
then create_class
(sub
.mclass
)
109 if sup
isa MGenericType then
110 var sub2
= sub
.supertype_to
(mainmodule
, anchor
, sup
.mclass
)
111 assert sub2
.mclass
== sup
.mclass
113 for i
in [0..sup
.mclass
.arity
[ do
114 var sub_arg
= sub2
.arguments
[i
]
115 var sup_arg
= sup
.arguments
[i
]
116 var res
= is_subtype
(sub_arg
, sup_arg
)
118 if res
== false then return false
123 var super_id
= sup
.mclass
.vtable
.id
124 var mask
= sub
.mclass
.vtable
.mask
126 return inter_is_subtype
(super_id
, mask
, sub
.mclass
.vtable
.internal_vtable
)
129 # Subtyping test with perfect hashing
130 private fun inter_is_subtype
(id
: Int, mask
:Int, vtable
: Pointer): Bool `{
131 // hv is the position in hashtable
134 // Follow the pointer to somewhere in the vtable
135 long unsigned int *offset = (long unsigned int*)(((long int *)vtable)[-hv]);
137 // If the pointed value is corresponding to the identifier, the test is true, otherwise false
138 return *offset == id;
141 # Redef init_instance to simulate the loading of a class
142 redef fun init_instance
(recv
: Instance)
144 if not recv
.mtype
.as(MClassType).mclass
.loaded
then create_class
(recv
.mtype
.as(MClassType).mclass
)
146 recv
.vtable
= recv
.mtype
.as(MClassType).mclass
.vtable
148 assert recv
isa MutableInstance
150 recv
.internal_attributes
= init_internal_attributes
(initialization_value
, recv
.mtype
.as(MClassType).mclass
.all_mattributes
(mainmodule
, none_visibility
).length
)
154 # Associate a `PrimitiveInstance` to its `VTable`
155 redef fun init_instance_primitive
(recv
: Instance)
157 if not recv
.mtype
.as(MClassType).mclass
.loaded
then create_class
(recv
.mtype
.as(MClassType).mclass
)
159 recv
.vtable
= recv
.mtype
.as(MClassType).mclass
.vtable
162 # Create a virtual table for this `MClass` if not already done
163 redef fun get_primitive_class
(name
: String): MClass
167 if not mclass
.loaded
then create_class
(mclass
)
172 # Initialize the internal representation of an object (its attribute values)
173 # `init_instance` is the initial value of attributes
174 private fun init_internal_attributes
(init_instance
: Instance, size
: Int): Pointer
175 import Array[Instance].length
, Array[Instance].[] `{
177 Instance* attributes = malloc(sizeof(Instance) * size);
180 for(i=0; i<size; i++)
181 attributes[i] = init_instance;
183 Instance_incr_ref(init_instance);
187 # Creates the runtime structures for this class
188 fun create_class
(mclass
: MClass) do mclass
.make_vt
(self)
190 # Execute `mproperty` for a `args` (where `args[0]` is the receiver).
191 redef fun send
(mproperty
: MMethod, args
: Array[Instance]): nullable Instance
193 var recv
= args
.first
194 var mtype
= recv
.mtype
195 var ret
= send_commons
(mproperty
, args
, mtype
)
196 if ret
!= null then return ret
198 var propdef
= method_dispatch
(mproperty
, recv
.vtable
.as(not null))
200 return self.call
(propdef
, args
)
203 # Method dispatch, for a given global method `mproperty`
204 # returns the most specific local method in the class corresponding to `vtable`
205 private fun method_dispatch
(mproperty
: MMethod, vtable
: VTable): MMethodDef
207 return method_dispatch_ph
(vtable
.internal_vtable
, vtable
.mask
,
208 mproperty
.intro_mclassdef
.mclass
.vtable
.id
, mproperty
.offset
)
211 # Execute a method dispatch with perfect hashing
212 private fun method_dispatch_ph
(vtable
: Pointer, mask
: Int, id
: Int, offset
: Int): MMethodDef `{
213 // Perfect hashing position
215 long unsigned int *pointer = (long unsigned int*)(((long int *)vtable)[-hv]);
217 // pointer+2 is the position where methods are
218 // Add the offset of property and get the method implementation
219 MMethodDef propdef = (MMethodDef)*(pointer + 2 + offset);
224 # Return the value of the attribute `mproperty` for the object `recv`
225 redef fun read_attribute
(mproperty
: MAttribute, recv
: Instance): Instance
227 assert recv
isa MutableInstance
231 if mproperty
.intro_mclassdef
.mclass
.positions_attributes
[recv
.mtype
.as(MClassType).mclass
] != -1 then
232 # if this attribute class has an unique position for this receiver, then use direct access
233 i
= read_attribute_sst
(recv
.internal_attributes
, mproperty
.absolute_offset
)
235 # Otherwise, read the attribute value with perfect hashing
236 var id
= mproperty
.intro_mclassdef
.mclass
.vtable
.id
238 i
= read_attribute_ph
(recv
.internal_attributes
, recv
.vtable
.internal_vtable
,
239 recv
.vtable
.mask
, id
, mproperty
.offset
)
242 # If we get a `MInit` value, throw an error
243 if i
== initialization_value
then
244 fatal
("Uninitialized attribute {mproperty.name}")
251 # Return the attribute value in `instance` with a sequence of perfect_hashing
252 # `instance` is the attributes array of the receiver
253 # `vtable` is the pointer to the virtual table of the class (of the receiver)
254 # `mask` is the perfect hashing mask of the class
255 # `id` is the identifier of the class
256 # `offset` is the relative offset of this attribute
257 private fun read_attribute_ph
(instance
: Pointer, vtable
: Pointer, mask
: Int, id
: Int, offset
: Int): Instance `{
258 // Perfect hashing position
260 long unsigned int *pointer = (long unsigned int*)(((long int *)vtable)[-hv]);
262 // pointer+1 is the position where the delta of the class is
263 int absolute_offset = *(pointer + 1);
265 Instance res = ((Instance *)instance)[absolute_offset + offset];
270 # Return the attribute value in `instance` with a direct access (SST)
271 # `instance` is the attributes array of the receiver
272 # `offset` is the absolute offset of this attribute
273 private fun read_attribute_sst
(instance
: Pointer, offset
: Int): Instance `{
274 /* We can make a direct access to the attribute value
275 because this attribute is always at the same position
276 for the class of this receiver */
277 Instance res = ((Instance *)instance)[offset];
282 # Replace in `recv` the value of the attribute `mproperty` by `value`
283 redef fun write_attribute
(mproperty
: MAttribute, recv
: Instance, value
: Instance)
285 assert recv
isa MutableInstance
287 var id
= mproperty
.intro_mclassdef
.mclass
.vtable
.id
289 # Replace the old value of mproperty in recv
290 write_attribute_ph
(recv
.internal_attributes
, recv
.vtable
.internal_vtable
,
291 recv
.vtable
.mask
, id
, mproperty
.offset
, value
)
294 # Replace the value of an attribute in an instance
295 # `instance` is the attributes array of the receiver
296 # `vtable` is the pointer to the virtual table of the class (of the receiver)
297 # `mask` is the perfect hashing mask of the class
298 # `id` is the identifier of the class
299 # `offset` is the relative offset of this attribute
300 # `value` is the new value for this attribute
301 private fun write_attribute_ph
(instance
: Pointer, vtable
: Pointer, mask
: Int, id
: Int, offset
: Int, value
: Instance) `{
302 // Perfect hashing position
304 long unsigned int *pointer = (long unsigned int*)(((long int *)vtable)[-hv]);
306 // pointer+1 is the position where the delta of the class is
307 int absolute_offset = *(pointer + 1);
309 ((Instance *)instance)[absolute_offset + offset] = value;
310 Instance_incr_ref(value);
313 # Is the attribute `mproperty` initialized in the instance `recv`?
314 redef fun isset_attribute
(mproperty
: MAttribute, recv
: Instance): Bool
316 assert recv
isa MutableInstance
318 # Read the attribute value with internal perfect hashing read
319 # because we do not want to throw an error if the value is `initialization_value`
320 var id
= mproperty
.intro_mclassdef
.mclass
.vtable
.id
322 var i
= read_attribute_ph
(recv
.internal_attributes
, recv
.vtable
.internal_vtable
,
323 recv
.vtable
.mask
, id
, mproperty
.offset
)
325 return i
!= initialization_value
330 # A reference to the virtual table of this class
331 var vtable
: nullable VTable
333 # True when the class is effectively loaded by the vm, false otherwise
334 var loaded
: Bool = false
336 # For each loaded subclass, keep the position of the group of attributes
337 # introduced by self class in the object
338 var positions_attributes
: HashMap[MClass, Int] = new HashMap[MClass, Int]
340 # For each loaded subclass, keep the position of the group of methods
341 # introduced by self class in the vtable
342 var positions_methods
: HashMap[MClass, Int] = new HashMap[MClass, Int]
344 # Allocates a VTable for this class and gives it an id
345 private fun make_vt
(v
: VirtualMachine)
347 if loaded
then return
349 # `superclasses` contains the order of superclasses for virtual tables
350 var superclasses
= superclasses_ordering
(v
)
351 superclasses
.remove
(self)
353 # Make_vt for super-classes
354 var ids
= new Array[Int]
355 var nb_methods
= new Array[Int]
356 var nb_attributes
= new Array[Int]
358 # Absolute offset of attribute from the beginning of the attributes table
359 var offset_attributes
= 0
360 # Absolute offset of method from the beginning of the methods table
361 var offset_methods
= 0
363 # The previous element in `superclasses`
364 var previous_parent
: nullable MClass = null
365 if superclasses
.length
> 0 then previous_parent
= superclasses
[0]
366 for parent
in superclasses
do
367 if not parent
.loaded
then parent
.make_vt
(v
)
369 # Get the number of introduced methods and attributes for this class
373 for p
in parent
.intro_mproperties
(none_visibility
) do
374 if p
isa MMethod then methods
+= 1
375 if p
isa MAttribute then attributes
+= 1
378 ids
.push
(parent
.vtable
.id
)
379 nb_methods
.push
(methods
)
380 nb_attributes
.push
(attributes
)
382 # Update `positions_attributes` and `positions_methods` in `parent`.
383 # If the position is invariant for this parent, store this position
384 # else store a special value (-1)
388 if previous_parent
.as(not null).positions_attributes
[parent
] == offset_attributes
then pos_attr
= offset_attributes
389 if previous_parent
.as(not null).positions_methods
[parent
] == offset_methods
then pos_meth
= offset_methods
391 parent
.update_positions
(pos_attr
, pos_meth
, self)
393 offset_attributes
+= attributes
394 offset_methods
+= methods
397 # When all super-classes have their identifiers and vtables, allocate current one
398 allocate_vtable
(v
, ids
, nb_methods
, nb_attributes
, offset_attributes
, offset_methods
)
401 # The virtual table now needs to be filled with pointer to methods
402 superclasses
.add
(self)
403 for cl
in superclasses
do
404 fill_vtable
(v
, vtable
.as(not null), cl
)
408 # Allocate a single vtable
409 # `ids : Array of superclasses identifiers
410 # `nb_methods : Array which contain the number of introduced methods for each class in ids
411 # `nb_attributes : Array which contain the number of introduced attributes for each class in ids
412 # `offset_attributes : Offset from the beginning of the table of the group of attributes
413 # `offset_methods : Offset from the beginning of the table of the group of methods
414 private fun allocate_vtable
(v
: VirtualMachine, ids
: Array[Int], nb_methods
: Array[Int], nb_attributes
: Array[Int],
415 offset_attributes
: Int, offset_methods
: Int)
418 var idc
= new Array[Int]
420 vtable
.mask
= v
.ph
.pnand
(ids
, 1, idc
) - 1
422 vtable
.classname
= name
424 # Add current id to Array of super-ids
425 var ids_total
= new Array[Int]
426 ids_total
.add_all
(ids
)
427 ids_total
.push
(vtable
.id
)
429 var nb_methods_total
= new Array[Int]
430 var nb_attributes_total
= new Array[Int]
433 var nb_introduced_attributes
= 0
435 # Fixing offsets for self attributes and methods
436 var relative_offset_attr
= 0
437 var relative_offset_meth
= 0
438 for p
in intro_mproperties
(none_visibility
) do
439 if p
isa MMethod then
441 p
.offset
= relative_offset_meth
442 p
.absolute_offset
= offset_methods
+ relative_offset_meth
443 relative_offset_meth
+= 1
445 if p
isa MAttribute then
446 nb_introduced_attributes
+= 1
447 p
.offset
= relative_offset_attr
448 p
.absolute_offset
= offset_attributes
+ relative_offset_attr
449 relative_offset_attr
+= 1
453 nb_methods_total
.add_all
(nb_methods
)
454 nb_methods_total
.push
(self_methods
)
456 nb_attributes_total
.add_all
(nb_attributes
)
457 nb_attributes_total
.push
(nb_introduced_attributes
)
459 # Save the offsets of self class
460 update_positions
(offset_attributes
, offset_methods
, self)
462 # Since we have the number of attributes for each class, calculate the delta
463 var deltas
= calculate_delta
(nb_attributes_total
)
464 vtable
.internal_vtable
= v
.memory_manager
.init_vtable
(ids_total
, nb_methods_total
, deltas
, vtable
.mask
)
467 # Fill the vtable with methods of `self` class
468 # `v` : Current instance of the VirtualMachine
469 # `table` : the table of self class, will be filled with its methods
470 private fun fill_vtable
(v
:VirtualMachine, table
: VTable, cl
: MClass)
472 var methods
= new Array[MMethodDef]
473 for m
in cl
.intro_mproperties
(none_visibility
) do
474 if m
isa MMethod then
475 # `propdef` is the most specific implementation for this MMethod
476 var propdef
= m
.lookup_first_definition
(v
.mainmodule
, self.intro
.bound_mtype
)
477 methods
.push
(propdef
)
481 # Call a method in C to put propdefs of self methods in the vtables
482 v
.memory_manager
.put_methods
(vtable
.internal_vtable
, vtable
.mask
, cl
.vtable
.id
, methods
)
485 # Computes delta for each class
486 # A delta represents the offset for this group of attributes in the object
487 # `nb_attributes` : number of attributes for each class (classes are linearized from Object to current)
488 # return deltas for each class
489 private fun calculate_delta
(nb_attributes
: Array[Int]): Array[Int]
491 var deltas
= new Array[Int]
494 for nb
in nb_attributes
do
502 # Order superclasses of self
503 # Return the order of superclasses in runtime structures of this class
504 private fun superclasses_ordering
(v
: VirtualMachine): Array[MClass]
506 var superclasses
= new Array[MClass]
507 superclasses
.add_all
(ancestors
)
509 var res
= new Array[MClass]
510 if superclasses
.length
> 1 then
512 var ordering
= self.dfs
(v
, res
)
516 # There is no super-class, self is Object
521 # A kind of Depth-First-Search for superclasses ordering
522 # `v` : the current executed instance of VirtualMachine
523 # `res` : Result Array, ie current superclasses ordering
524 private fun dfs
(v
: VirtualMachine, res
: Array[MClass]): Array[MClass]
526 # Add this class at the beginning
529 var direct_parents
= self.in_hierarchy
(v
.mainmodule
).direct_greaters
.to_a
531 if direct_parents
.length
> 1 then
532 # Prefix represents the class which has the most properties
533 # we try to choose it in first to reduce the number of potential recompilations
536 for cl
in direct_parents
do
537 # If we never have visited this class
538 if not res
.has
(cl
) then
539 var properties_length
= cl
.all_mproperties
(v
.mainmodule
, none_visibility
).length
540 if properties_length
> max
then
541 max
= properties_length
547 if prefix
!= null then
548 # Add the prefix class ordering at the beginning of our sequence
549 var prefix_res
= new Array[MClass]
550 prefix_res
= prefix
.dfs
(v
, prefix_res
)
552 # Then we recurse on other classes
553 for cl
in direct_parents
do
555 res
= new Array[MClass]
559 if not prefix_res
.has
(cl_res
) then prefix_res
.push
(cl_res
)
568 if direct_parents
.length
> 0 then
569 res
= direct_parents
.first
.dfs
(v
, res
)
573 if not res
.has
(self) then res
.push
(self)
578 # Update positions of the class `cl`
579 # `attributes_offset`: absolute offset of introduced attributes
580 # `methods_offset`: absolute offset of introduced methods
581 private fun update_positions
(attributes_offsets
: Int, methods_offset
:Int, cl
: MClass)
583 positions_attributes
[cl
] = attributes_offsets
584 positions_methods
[cl
] = methods_offset
588 redef class MAttribute
589 # Relative offset of this attribute in the runtime instance
590 # (beginning of the block of its introducing class)
593 # Absolute offset of this attribute in the runtime instance (beginning of the attribute table)
594 var absolute_offset
: Int
598 # Relative offset of this method in the virtual table (from the beginning of the block)
601 # Absolute offset of this method in the virtual table (from the beginning of the vtable)
602 var absolute_offset
: Int
605 # Redef MutableInstance to improve implementation of attributes in objects
606 redef class MutableInstance
608 # C-array to store pointers to attributes of this Object
609 var internal_attributes
: Pointer
612 # Redef to associate an `Instance` to its `VTable`
614 var vtable
: nullable VTable
617 # Is the type of the initial value inside attributes
621 redef var model
: Model
622 protected init(model
: Model)
627 redef fun to_s
do return "InitType"
628 redef fun as_nullable
do return self
629 redef fun need_anchor
do return false
630 redef fun resolve_for
(mtype
, anchor
, mmodule
, cleanup_virtual
) do return self
631 redef fun can_resolve_for
(mtype
, anchor
, mmodule
) do return true
633 redef fun collect_mclassdefs
(mmodule
) do return new HashSet[MClassDef]
635 redef fun collect_mclasses
(mmodule
) do return new HashSet[MClass]
637 redef fun collect_mtypes
(mmodule
) do return new HashSet[MClassType]
640 # A VTable contains the virtual method table for the dispatch
641 # and informations to perform subtyping tests
643 # The mask to perform perfect hashing
644 var mask
: Int is noinit
646 # Unique identifier given by perfect hashing
647 var id
: Int is noinit
649 # Pointer to the c-allocated area, represents the virtual table
650 var internal_vtable
: Pointer is noinit
652 # The short classname of this class
653 var classname
: String is noinit
656 # Handle memory, used for allocate virtual table and associated structures
659 # Allocate and fill a virtual table
660 fun init_vtable
(ids
: Array[Int], nb_methods
: Array[Int], nb_attributes
: Array[Int], mask
: Int): Pointer
662 # Allocate in C current virtual table
663 var res
= intern_init_vtable
(ids
, nb_methods
, nb_attributes
, mask
)
668 # Construct virtual tables with a bi-dimensional layout
669 private fun intern_init_vtable
(ids
: Array[Int], nb_methods
: Array[Int], deltas
: Array[Int], mask
: Int): Pointer
670 import Array[Int].length
, Array[Int].[] `{
672 // Allocate and fill current virtual table
674 int total_size = 0; // total size of this virtual table
675 int nb_classes = Array_of_Int_length(nb_methods);
676 for(i = 0; i<nb_classes; i++) {
677 /* - One for each method of this class
678 * - One for the delta (offset of this group of attributes in objects)
681 total_size += Array_of_Int__index(nb_methods, i);
685 // Add the size of the perfect hashtable (mask +1)
686 // Add one because we start to fill the vtable at position 1 (0 is the init position)
687 total_size += mask+2;
688 long unsigned int* vtable = malloc(sizeof(long unsigned int)*total_size);
690 // Initialisation to the first position of the virtual table (ie : Object)
691 long unsigned int *init = vtable + mask + 2;
692 for(i=0; i<total_size; i++)
693 vtable[i] = (long unsigned int)init;
695 // Set the virtual table to its position 0
696 // ie: after the hashtable
697 vtable = vtable + mask + 1;
699 int current_size = 1;
700 for(i = 0; i < nb_classes; i++) {
702 vtable[hv] contains a pointer to the group of introduced methods
703 For each superclasse we have in virtual table :
704 (id | delta | introduced methods)
706 int hv = mask & Array_of_Int__index(ids, i);
708 vtable[current_size] = Array_of_Int__index(ids, i);
709 vtable[current_size + 1] = Array_of_Int__index(deltas, i);
710 vtable[-hv] = (long unsigned int)&(vtable[current_size]);
713 current_size += Array_of_Int__index(nb_methods, i);
719 # Put implementation of methods of a class in `vtable`
720 # `vtable` : Pointer to the C-virtual table
721 # `mask` : perfect-hashing mask of the class corresponding to the vtable
722 # `id` : id of the target class
723 # `methods` : array of MMethodDef of the target class
724 fun put_methods
(vtable
: Pointer, mask
: Int, id
: Int, methods
: Array[MMethodDef])
725 import Array[MMethodDef].length
, Array[MMethodDef].[] `{
727 // Get the area to fill with methods by a sequence of perfect hashing
729 long unsigned int *pointer = (long unsigned int*)(((long unsigned int *)vtable)[-hv]);
731 // pointer+2 is the beginning of the area for methods implementation
732 int length = Array_of_MMethodDef_length(methods);
733 long unsigned int *area = (pointer + 2);
736 for(i=0; i<length; i++)
738 MMethodDef method = Array_of_MMethodDef__index(methods, i);
739 area[i] = (long unsigned int)method;
740 MMethodDef_incr_ref(method);