-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathcompile_calls.rb
More file actions
515 lines (455 loc) · 17.1 KB
/
Copy pathcompile_calls.rb
File metadata and controls
515 lines (455 loc) · 17.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
#
# Method related to function and method calls,
# including yield and super.
#
#
class Compiler
def compile_args_nosplat(scope, ob, args, dynamic_adj = false, &block)
# FIXME: This used to use "with_stack" which aligns to 16 byte boundaries,
# but lifted this in here due to dynamically adjusting the stack based on
# %ebx. Need to determine exactly what to do about this size - it needs to
# be bigger than args.length for some reason, but unsure exactly why and
# how much.
adj = Emitter::PTR_SIZE * (args.length+4)
@e.subl(adj, :esp)
args.each_with_index do |a, i|
param = compile_eval_arg(scope, a)
@e.save_to_stack(param, i)
end
@e.movl(args.length, :ebx)
yield
if dynamic_adj
# Always dynamically adjust the stack based on %ebx for method calls
# (as opposed to C-library calls) due to potential of hitting a
# method_missing thunk or anything else that might mess around with the
# argument list before returning from the call.
@e.comment("Static adj: #{adj}")
@e.addl(4, :ebx) # Need to correspond to the extra space used when assigning "adj" above.
@e.sall(2, :ebx)
@e.addl(:ebx, :esp)
else
@e.addl(adj, :esp)
end
end
def copy_splat_loop(splatcnt, indir)
@e.loop do |br,_|
@e.testl(splatcnt, splatcnt)
@e.je(br)
# x86 will be the death of me.
@e.pushl("(%eax)")
@e.popl("(%#{indir.to_s})")
@e.addl(4,:eax)
@e.addl(4,indir)
@e.subl(1,splatcnt)
end
end
# For a splat argument, push it onto the stack,
# forwards relative to register "indir".
#
# FIXME: This method is almost certainly much
# less efficient than it could be.
#
def compile_args_copysplat(scope, a, indir)
@e.with_register do |splatcnt|
if a[1] == :__copysplat
@e.comment("SPLAT COPY")
param = @e.save_to_reg(compile_eval_arg(scope, [:sub, :numargs, 2]))
@e.movl(param, splatcnt)
param = compile_eval_arg(scope, a[1])
copy_splat_loop(splatcnt, indir)
else
@e.comment("SPLAT ARRAY")
param = compile_eval_arg(scope, a[1])
@e.addl(4,param)
@e.load_indirect(param, splatcnt)
@e.addl(4,param)
@e.load_indirect(param, :eax)
@e.testl(:eax,:eax)
l = @e.get_local
# If Array class ptr has not been allocated yet:
@e.je(l)
copy_splat_loop(splatcnt, indir)
@e.local(l)
end
end
end
def compile_args_splat_loop(scope, args, indir)
args.each do |a|
ary = a.is_a?(Array)
sp = false
if ary
if a[0] == :splat
sp = true
end
end
# ary && (a[0] == :splat)
if sp
compile_args_copysplat(scope, a, indir)
else
param = compile_eval_arg(scope, a)
@e.save_indirect(param, indir)
@e.addl(4, indir)
end
end
end
def compile_args_splat(scope, ob, args)
# Because Ruby evaluation order is left to right,
# we need to first figure out how much space we need on
# the stack.
#
# We do that by first building up an expression that
# adds up the static elements of the parameter list
# and the result of retrieving 'Array#length' from
# each splatted array.
#
# (FIXME: Note that we're not actually type-checking
# what is *actually* passed)
#
num_fixed = 0
exprlist = []
args.each_with_index do |a, i|
if a.is_a?(Array) && a[0] == :splat
if a[1] == :__copysplat
exprlist << [:sub, :numargs, 2]
else
# We do this, rather than Array#length, because the class may not
# have been created yet. This *requires* Array's @len ivar to be
# in the first ivar;
# FIXME: should enforce this.
exprlist << [:index, a[1], 1]
end
else
num_fixed += 1
end
end
expr = num_fixed
while e = exprlist.pop
expr = [:add, e, expr]
end
@e.comment("BEGIN Calculating argument count for splat")
ret = compile_eval_arg(scope, expr)
@e.movl(@e.result, @e.scratch)
@e.comment("END Calculating argument count for splat; numargs is now in #{@e.scratch.to_s}")
@e.comment("Moving stack pointer to start of argument array:")
@e.imull(4,@e.result)
# esp now points to the start of the arguments; ebx holds numargs,
# and end_of_arguments(%esp) also holds numargs
@e.subl(@e.result, :esp)
@e.comment("BEGIN Pushing arguments:")
@e.with_register do |indir|
# We'll use indir to put arguments onto the stack without clobbering esp:
@e.movl(:esp, indir)
@e.pushl(@e.scratch)
@e.comment("BEGIN args.each do |a|")
compile_args_splat_loop(scope, args, indir)
@e.comment("END args.each")
@e.popl(@e.scratch)
end
@e.comment("END Pushing arguments")
yield
@e.comment("Re-adjusting stack post-call:")
@e.imull(4,@e.scratch)
@e.addl(@e.scratch, :esp)
end
def compile_args(scope, ob, args, dynamic_adjust=false, &block)
@e.caller_save do
splat = args.detect {|a| a.is_a?(Array) && a.first == :splat }
#FIXME Mentioned here to lift vars
scope
block
dynamic_adjust
if !splat
compile_args_nosplat(scope,ob,args,dynamic_adjust, &block)
else
compile_args_splat(scope,ob,args, &block)
end
end
end
def compile_callm_args(scope, ob, args, &block)
compile_args(scope, ob, [ob].concat(args), true, &block)
end
# Compiles a function call.
# Takes the current scope, the function to call as well as the arguments
# to call the function with.
def compile_call(scope, func, args, block = nil, pos = nil)
return compile_yield(scope, args, block) if func == :yield
# Handle visibility methods, attr, and module_function at compile time
# These are no-ops since visibility isn't enforced and attr_* are stubs
# But we need to handle them here because method calls in class bodies
# don't work correctly (self/%esi not set up properly)
# module_function makes methods both module methods and private instance methods
if [:private, :protected, :public, :attr, :attr_reader, :attr_writer, :attr_accessor, :module_function].include?(func)
if scope.is_a?(ModuleScope)
# In class/module body - just return nil
@e.movl("nil", :eax)
return Value.new([:subexpr])
end
# Fall through to regular method call in other contexts
end
# Handle 'include' and 'prepend' as compile-time module inclusion
# Works in:
# - ClassScope/ModuleScope (class/module body) - includes into that class/module
# - GlobalScope (top level) - includes into Object
# Other scopes (LocalVarScope, etc.) - treat as regular method call
# Note: prepend is treated same as include (ordering difference not implemented)
if func == :include || func == :prepend
if scope.is_a?(ModuleScope) || scope.is_a?(GlobalScope)
# args is array of module names, but we only support single module for now
mod_name = args.is_a?(Array) ? args[0] : args
# Only handle compile-time constant names - if module name is dynamic expression,
# fall through to runtime method call
if mod_name.is_a?(Symbol)
return compile_include(scope, mod_name, pos)
end
# Fall through to regular method call for dynamic module names
else
# Not in class/module/global scope - fall through to regular method call
# This allows include to work as a method in other contexts (e.g., RSpec matchers)
end
end
# Handle 'extend' at compile time - no-op for now
# (proper implementation would add module methods to singleton class)
if func == :extend
if scope.is_a?(ModuleScope)
@e.movl("nil", :eax)
return Value.new([:subexpr])
end
end
# This is a bit of a hack. get_arg will also be called from
# compile_eval_arg below, but we need to know if it's a callm
fargs = get_arg(scope, func)
return compile_super(scope, args,block) if func == :super
return compile_callm(scope,:self, func, args,block) if fargs and fargs[0] == :possible_callm || fargs[0] == :global
# Wrap single argument in array if needed
# When there's a block, parser passes args unwrapped: [:call, func, arg, block]
# When there's no block, parser wraps args: [:call, func, [args...]]
# Only wrap if it's an AST node (not a symbol/constant name)
if !args.is_a?(Array)
args = [args]
elsif block && args.is_a?(Array) && args[0].is_a?(Symbol) && [:hash, :array, :proc, :block, :lambda].include?(args[0])
# With block, single AST node arg (like [:hash, ...]) needs wrapping
args = [args]
end
compile_args(scope, func, args) do
scope
func
r = get_arg(scope,func)
if r[0] == :addr
@e.call(r[1].to_s)
else
@e.call(compile_eval_arg(scope, func))
end
end
@e.evict_regs_for(:self)
reload_self(scope)
return Value.new([:subexpr])
end
# Load class for the object whose pointer is in %esi.
#
# For now, this is done by testing bit 0, and if it
# is set we know this isn't a valid pointer to a Class
# object. Instead we assume it is a Fixnum.
#
# This is similar to MRI, but MRI uses type tags for
# more types of objects. We probably will here too
# in the future (e.g. Float when it's added, at least)
#
# Upside: Far less need for garbage collection.
# Downside: The cost of *this* every time we need the
# class pointer. This can be mitigated somewhat by
# better code generation (e.g. keeping class pointers
# for objects that are accessed multiple times;
# figuring out inlining and the like, but requires more
# effort to optimize. As a first stage, however, this
# will do as it makes self-compilation viable for this
# compiler for the first time.
#
def load_class(scope)
@e.testl(1, :esi)
l1 = @e.get_local
l2 = @e.get_local
@e.jz(l1)
@e.load(:global, :Fixnum)
@e.jmp(l2)
@e.label(l1)
@e.load_indirect(:esi, :eax)
@e.label(l2)
end
# Load the super-class pointer
def load_super(scope)
@e.load_instance_var(:eax, 3)
end
# if we called a method on something other than self,
# or a function, we have or may have clobbered %esi,
# so lets reload it.
def reload_self(scope)
t,a = get_arg(scope,:self)
end
# FIXME: @bug May need to do this as a rewrite, as if block is taken in, and
# then another block is passed to another method, that other method can not
# contain "yield", as it needs to go through a let_env rewrite.
#
# Yield to the supplied block
def compile_yield(scope, args, block)
@e.comment("yield")
args ||= []
compile_callm(scope, :__closure__, :call, args, block)
end
# Compiles a super method call
#
def compile_super(scope, args, block = nil)
# Walk up the scope chain to find an actual method (not a block/lambda)
# Blocks have string names like "__lambda_L229", methods have symbol names like :here
method = nil
s = scope
while s
if s.method && s.method.name.is_a?(Symbol)
method = s.method.name
break
end
s = s.is_a?(Scope) ? s.next : nil
end
method ||= :__unknown__
@e.comment("super #{method.inspect}")
trace(nil,"=> super #{method.inspect}\n")
# Pass the defining class name so we look up the right superclass
# (not self.class.superclass which would be wrong for deep hierarchies)
# For eigenclasses, fall back to runtime lookup since they don't have globals
cs = scope.class_scope
if cs.is_a?(EigenclassScope)
defining_class = :runtime
else
defining_class = cs.name
end
ret = compile_callm(scope, :self, method, args, block, defining_class)
trace(nil,"<= super #{method.inspect}\n")
ret
end
# Compiles a method call to an object.
# Similar to compile_call but with an additional object parameter
# representing the object to call the method on.
# The object gets passed to the method, which is just another function,
# as the first parameter.
def compile_callm(scope, ob, method, args, block = nil, do_load_super = false)
# FIXME: Shouldn't trigger - probably due to the callm rewrites
return compile_yield(scope, args, block) if method == :yield and ob == :self
return compile_super(scope, args,block) if method == :super and ob == :self
# Special handling for defined?() - don't evaluate arguments, just stub to nil
if method == :defined? && ob == :self
@e.comment("defined?() - stubbed to nil")
return compile_exp(scope, :nil)
end
# Handle visibility methods, attr, and module_function at compile time in class/module bodies
# These are no-ops since visibility isn't enforced and attr_* are stubs
# This handles the case where the call is to self (e.g., "module_function" in module body)
if ob == :self && scope.is_a?(ModuleScope)
if [:private, :protected, :public, :attr, :attr_reader, :attr_writer, :attr_accessor, :module_function].include?(method)
@e.comment("Compile-time: #{method} in class/module body - no-op")
@e.movl("nil", :eax)
return Value.new([:subexpr])
end
end
@e.comment("callm #{ob.inspect}.#{method.inspect}")
trace(nil,"=> callm #{ob.inspect}.#{method.inspect}\n")
stackfence do
args ||= []
# Wrap single argument in array if needed
# Same issue as compile_call - parser generates inconsistent structures with blocks
# Only wrap if it's an AST node (not a symbol/constant name)
if !args.is_a?(Array)
args = [args]
elsif block && args.is_a?(Array) && args[0].is_a?(Symbol) && [:hash, :array, :proc, :block, :lambda].include?(args[0])
# With block, single AST node arg (like [:hash, ...]) needs wrapping
args = [args]
end
if args.last.kind_of?(Array) && args.last[0] == :to_block
block = args.last[1]
args.pop
end
args = [block ? block : 0] + args
off = nil
if method.is_a?(Symbol)
off = @vtableoffsets.get_offset(method)
if !off
# Argh. Ok, then. Lets do send
off = @vtableoffsets.get_offset(:__send__)
args.insert(1,":#{method}".to_sym)
# warning("WARNING: No vtable offset for '#{method}' (with args: #{args.inspect}) -- you're likely to get a method_missing")
#error(err_msg, scope, [:callm, ob, method, args])
m = off
else
m = "__voff__#{clean_method_name(method)}"
end
else
# In this case, the method is provided as an expression
# generating the *address*, which is evaluated beow.
end
compile_callm_args(scope, ob, args) do
if ob != :self
@e.load_indirect(@e.sp, :esi)
else
@e.comment("Reload self?")
reload_self(scope)
end
if do_load_super && do_load_super != :runtime
# do_load_super is the defining class name - load its superclass directly
# This fixes super in deep hierarchies (A < B < C) where self.class.superclass
# would return the wrong class
@e.comment("Load defining class #{do_load_super} for super")
@e.load(:global, do_load_super.to_sym)
load_super(scope) # Load superclass from %eax
elsif do_load_super == :runtime
# Runtime lookup - used for eigenclasses where the class object is
# created at runtime and has no global symbol
load_class(scope) # Load self.class into %eax
load_super(scope) # Load superclass from %eax
else
load_class(scope) # Load self.class into %eax
end
if off
@e.callm(m)
else
# NOTE: The expression in "method" can not
# include a function call, as it'll clobber
# %ebx
@e.call(compile_eval_arg(scope,method))
end
# FIXME: Unsure if the below check is
# inherently unsafe, or currently unsafe
# due to abug elsewhere, but removing it
# solves some register invalidation problems,
# so commenting out for now.
# if ob != :self
@e.comment("Evicting self")
@e.evict_regs_for(:self)
# end
end
end
@e.comment("callm #{ob.to_s}.#{method.to_s} END")
trace(nil,"<= callm #{ob.to_s}.#{method.to_s}\n")
return Value.new([:subexpr], :object)
end
# Compile safe navigation operator: obj&.method
# Returns nil if obj is nil, otherwise calls method
def compile_safe_callm(scope, ob, method, args, block = nil)
@e.comment("safe_callm #{ob.to_s}&.#{method.to_s} START")
# Generate labels
end_label = @e.get_local
nil_label = @e.get_local
# Evaluate the object
ret = compile_eval_arg(scope, ob)
@e.save_result(ret)
# Check if nil (nil is a global label in this compiler)
@e.cmpl("nil", :eax)
@e.je(nil_label)
# Not nil - call the method normally
compile_callm(scope, ob, method, args, block)
@e.jmp(end_label)
# Was nil - return nil
@e.local(nil_label)
@e.movl("nil", :eax)
@e.local(end_label)
@e.comment("safe_callm #{ob.to_s}&.#{method.to_s} END")
return Value.new([:subexpr], :object)
end
end