-
Notifications
You must be signed in to change notification settings - Fork 250
/
Copy pathinline.rs
569 lines (534 loc) · 20.4 KB
/
inline.rs
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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
//! This algorithm is not intended to be an optimization, it is rather for legalization.
//! Specifically, spir-v disallows things like a `StorageClass::Function` pointer to a
//! `StorageClass::Input` pointer. Our frontend definitely allows it, though, this is like taking a
//! `&Input<T>` in a function! So, we inline all functions that take these "illegal" pointers, then
//! run mem2reg (see mem2reg.rs) on the result to "unwrap" the Function pointer.
use super::apply_rewrite_rules;
use super::simple_passes::outgoing_edges;
use super::{get_name, get_names};
use rspirv::dr::{Block, Function, Instruction, Module, ModuleHeader, Operand};
use rspirv::spirv::{FunctionControl, Op, StorageClass, Word};
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_errors::ErrorGuaranteed;
use rustc_session::Session;
use std::mem::take;
type FunctionMap = FxHashMap<Word, Function>;
pub fn inline(sess: &Session, module: &mut Module) -> super::Result<()> {
// This algorithm gets real sad if there's recursion - but, good news, SPIR-V bans recursion
deny_recursion_in_module(sess, module)?;
let functions = module
.functions
.iter()
.map(|f| (f.def_id().unwrap(), f.clone()))
.collect();
let (disallowed_argument_types, disallowed_return_types) =
compute_disallowed_argument_and_return_types(module);
let void = module
.types_global_values
.iter()
.find(|inst| inst.class.opcode == Op::TypeVoid)
.map_or(0, |inst| inst.result_id.unwrap());
// Drop all the functions we'll be inlining. (This also means we won't waste time processing
// inlines in functions that will get inlined)
let mut dropped_ids = FxHashSet::default();
let mut inlined_dont_inlines = Vec::new();
module.functions.retain(|f| {
if should_inline(&disallowed_argument_types, &disallowed_return_types, f) {
if has_dont_inline(f) {
inlined_dont_inlines.push(f.def_id().unwrap());
}
// TODO: We should insert all defined IDs in this function.
dropped_ids.insert(f.def_id().unwrap());
false
} else {
true
}
});
if !inlined_dont_inlines.is_empty() {
let names = get_names(module);
for f in inlined_dont_inlines {
sess.warn(&format!(
"function `{}` has `dont_inline` attribute, but need to be inlined because it has illegal argument or return types",
get_name(&names, f)
));
}
}
// Drop OpName etc. for inlined functions
module.debug_names.retain(|inst| {
!inst.operands.iter().any(|op| {
op.id_ref_any()
.map_or(false, |id| dropped_ids.contains(&id))
})
});
let mut inliner = Inliner {
header: module.header.as_mut().unwrap(),
types_global_values: &mut module.types_global_values,
void,
functions: &functions,
disallowed_argument_types: &disallowed_argument_types,
disallowed_return_types: &disallowed_return_types,
};
for function in &mut module.functions {
inliner.inline_fn(function);
fuse_trivial_branches(function);
}
Ok(())
}
// https://stackoverflow.com/a/53995651
fn deny_recursion_in_module(sess: &Session, module: &Module) -> super::Result<()> {
let func_to_index: FxHashMap<Word, usize> = module
.functions
.iter()
.enumerate()
.map(|(index, func)| (func.def_id().unwrap(), index))
.collect();
let mut discovered = vec![false; module.functions.len()];
let mut finished = vec![false; module.functions.len()];
let mut has_recursion = None;
for index in 0..module.functions.len() {
if !discovered[index] && !finished[index] {
visit(
sess,
module,
index,
&mut discovered,
&mut finished,
&mut has_recursion,
&func_to_index,
);
}
}
fn visit(
sess: &Session,
module: &Module,
current: usize,
discovered: &mut Vec<bool>,
finished: &mut Vec<bool>,
has_recursion: &mut Option<ErrorGuaranteed>,
func_to_index: &FxHashMap<Word, usize>,
) {
discovered[current] = true;
for next in calls(&module.functions[current], func_to_index) {
if discovered[next] {
let names = get_names(module);
let current_name = get_name(&names, module.functions[current].def_id().unwrap());
let next_name = get_name(&names, module.functions[next].def_id().unwrap());
*has_recursion = Some(sess.err(&format!(
"module has recursion, which is not allowed: `{}` calls `{}`",
current_name, next_name
)));
break;
}
if !finished[next] {
visit(
sess,
module,
next,
discovered,
finished,
has_recursion,
func_to_index,
);
}
}
discovered[current] = false;
finished[current] = true;
}
fn calls<'a>(
func: &'a Function,
func_to_index: &'a FxHashMap<Word, usize>,
) -> impl Iterator<Item = usize> + 'a {
func.all_inst_iter()
.filter(|inst| inst.class.opcode == Op::FunctionCall)
.map(move |inst| {
*func_to_index
.get(&inst.operands[0].id_ref_any().unwrap())
.unwrap()
})
}
match has_recursion {
Some(err) => Err(err),
None => Ok(()),
}
}
fn compute_disallowed_argument_and_return_types(
module: &Module,
) -> (FxHashSet<Word>, FxHashSet<Word>) {
let allowed_argument_storage_classes = &[
StorageClass::UniformConstant,
StorageClass::Function,
StorageClass::Private,
StorageClass::Workgroup,
StorageClass::AtomicCounter,
];
let mut disallowed_argument_types = FxHashSet::default();
let mut disallowed_pointees = FxHashSet::default();
let mut disallowed_return_types = FxHashSet::default();
for inst in &module.types_global_values {
match inst.class.opcode {
Op::TypePointer => {
let storage_class = inst.operands[0].unwrap_storage_class();
let pointee = inst.operands[1].unwrap_id_ref();
if !allowed_argument_storage_classes.contains(&storage_class)
|| disallowed_pointees.contains(&pointee)
|| disallowed_argument_types.contains(&pointee)
{
disallowed_argument_types.insert(inst.result_id.unwrap());
}
disallowed_pointees.insert(inst.result_id.unwrap());
disallowed_return_types.insert(inst.result_id.unwrap());
}
Op::TypeStruct => {
let fields = || inst.operands.iter().map(|op| op.id_ref_any().unwrap());
if fields().any(|id| disallowed_argument_types.contains(&id)) {
disallowed_argument_types.insert(inst.result_id.unwrap());
}
if fields().any(|id| disallowed_pointees.contains(&id)) {
disallowed_pointees.insert(inst.result_id.unwrap());
}
if fields().any(|id| disallowed_return_types.contains(&id)) {
disallowed_return_types.insert(inst.result_id.unwrap());
}
}
Op::TypeArray | Op::TypeRuntimeArray | Op::TypeVector => {
let id = inst.operands[0].id_ref_any().unwrap();
if disallowed_argument_types.contains(&id) {
disallowed_argument_types.insert(inst.result_id.unwrap());
}
if disallowed_pointees.contains(&id) {
disallowed_pointees.insert(inst.result_id.unwrap());
}
}
_ => {}
}
}
(disallowed_argument_types, disallowed_return_types)
}
fn has_dont_inline(function: &Function) -> bool {
let def = function.def.as_ref().unwrap();
let control = def.operands[0].unwrap_function_control();
control.contains(FunctionControl::DONT_INLINE)
}
fn should_inline(
disallowed_argument_types: &FxHashSet<Word>,
disallowed_return_types: &FxHashSet<Word>,
function: &Function,
) -> bool {
let def = function.def.as_ref().unwrap();
let control = def.operands[0].unwrap_function_control();
control.contains(FunctionControl::INLINE)
|| function
.parameters
.iter()
.any(|inst| disallowed_argument_types.contains(inst.result_type.as_ref().unwrap()))
|| disallowed_return_types.contains(&function.def.as_ref().unwrap().result_type.unwrap())
}
// This should be more general, but a very common problem is passing an OpAccessChain to an
// OpFunctionCall (i.e. `f(&s.x)`, or more commonly, `s.x.f()` where `f` takes `&self`), so detect
// that case and inline the call.
fn args_invalid(function: &Function, call: &Instruction) -> bool {
for inst in function.all_inst_iter() {
if inst.class.opcode == Op::AccessChain {
let inst_result = inst.result_id.unwrap();
if call
.operands
.iter()
.any(|op| *op == Operand::IdRef(inst_result))
{
return true;
}
}
}
false
}
// Steps:
// Move OpVariable decls
// Rewrite return
// Renumber IDs
// Insert blocks
struct Inliner<'m, 'map> {
header: &'m mut ModuleHeader,
types_global_values: &'m mut Vec<Instruction>,
void: Word,
functions: &'map FunctionMap,
disallowed_argument_types: &'map FxHashSet<Word>,
disallowed_return_types: &'map FxHashSet<Word>,
// rewrite_rules: FxHashMap<Word, Word>,
}
impl Inliner<'_, '_> {
fn id(&mut self) -> Word {
let result = self.header.bound;
self.header.bound += 1;
result
}
fn ptr_ty(&mut self, pointee: Word) -> Word {
// TODO: This is horribly slow, fix this
let existing = self.types_global_values.iter().find(|inst| {
inst.class.opcode == Op::TypePointer
&& inst.operands[0].unwrap_storage_class() == StorageClass::Function
&& inst.operands[1].unwrap_id_ref() == pointee
});
if let Some(existing) = existing {
return existing.result_id.unwrap();
}
let inst_id = self.id();
self.types_global_values.push(Instruction::new(
Op::TypePointer,
None,
Some(inst_id),
vec![
Operand::StorageClass(StorageClass::Function),
Operand::IdRef(pointee),
],
));
inst_id
}
fn inline_fn(&mut self, function: &mut Function) {
let mut block_idx = 0;
while block_idx < function.blocks.len() {
// If we successfully inlined a block, then repeat processing on the same block, in
// case the newly inlined block has more inlined calls.
// TODO: This is quadratic
if !self.inline_block(function, block_idx) {
block_idx += 1;
}
}
}
fn inline_block(&mut self, caller: &mut Function, block_idx: usize) -> bool {
// Find the first inlined OpFunctionCall
let call = caller.blocks[block_idx]
.instructions
.iter()
.enumerate()
.filter(|(_, inst)| inst.class.opcode == Op::FunctionCall)
.map(|(index, inst)| {
(
index,
inst,
self.functions
.get(&inst.operands[0].id_ref_any().unwrap())
.unwrap(),
)
})
.find(|(_, inst, f)| {
should_inline(
self.disallowed_argument_types,
self.disallowed_return_types,
f,
) || args_invalid(caller, inst)
});
let (call_index, call_inst, callee) = match call {
None => return false,
Some(call) => call,
};
let call_result_type = {
let ty = call_inst.result_type.unwrap();
if ty == self.void {
None
} else {
Some(ty)
}
};
let call_result_id = call_inst.result_id.unwrap();
// Rewrite parameters to arguments
let call_arguments = call_inst
.operands
.iter()
.skip(1)
.map(|op| op.id_ref_any().unwrap());
let callee_parameters = callee.parameters.iter().map(|inst| {
assert!(inst.class.opcode == Op::FunctionParameter);
inst.result_id.unwrap()
});
let mut rewrite_rules = callee_parameters.zip(call_arguments).collect();
let return_variable = if call_result_type.is_some() {
Some(self.id())
} else {
None
};
let return_jump = self.id();
// Rewrite OpReturns of the callee.
let mut inlined_blocks = get_inlined_blocks(callee, return_variable, return_jump);
// Clone the IDs of the callee, because otherwise they'd be defined multiple times if the
// fn is inlined multiple times.
self.add_clone_id_rules(&mut rewrite_rules, &inlined_blocks);
apply_rewrite_rules(&rewrite_rules, &mut inlined_blocks);
// Split the block containing the OpFunctionCall into two, around the call.
let mut post_call_block_insts = caller.blocks[block_idx]
.instructions
.split_off(call_index + 1);
// pop off OpFunctionCall
let call = caller.blocks[block_idx].instructions.pop().unwrap();
assert!(call.class.opcode == Op::FunctionCall);
if let Some(call_result_type) = call_result_type {
// Generate the storage space for the return value: Do this *after* the split above,
// because if block_idx=0, inserting a variable here shifts call_index.
insert_opvariable(
&mut caller.blocks[0],
self.ptr_ty(call_result_type),
return_variable.unwrap(),
);
}
// Fuse the first block of the callee into the block of the caller. This is okay because
// it's illegal to branch to the first BB in a function.
let mut callee_header = inlined_blocks.remove(0).instructions;
// TODO: OpLine handling
let num_variables = callee_header
.iter()
.position(|inst| inst.class.opcode != Op::Variable)
.unwrap_or(callee_header.len());
caller.blocks[block_idx]
.instructions
.append(&mut callee_header.split_off(num_variables));
// Move the OpVariables of the callee to the caller.
insert_opvariables(&mut caller.blocks[0], callee_header);
if let Some(call_result_type) = call_result_type {
// Add the load of the result value after the inlined function. Note there's guaranteed no
// OpPhi instructions since we just split this block.
post_call_block_insts.insert(
0,
Instruction::new(
Op::Load,
Some(call_result_type),
Some(call_result_id),
vec![Operand::IdRef(return_variable.unwrap())],
),
);
}
// Insert the second half of the split block.
let continue_block = Block {
label: Some(Instruction::new(Op::Label, None, Some(return_jump), vec![])),
instructions: post_call_block_insts,
};
caller.blocks.insert(block_idx + 1, continue_block);
// Insert the rest of the blocks (i.e. not the first) between the original block that was
// split.
caller
.blocks
.splice((block_idx + 1)..(block_idx + 1), inlined_blocks);
true
}
fn add_clone_id_rules(&mut self, rewrite_rules: &mut FxHashMap<Word, Word>, blocks: &[Block]) {
for block in blocks {
for inst in block.label.iter().chain(&block.instructions) {
if let Some(result_id) = inst.result_id {
let new_id = self.id();
let old = rewrite_rules.insert(result_id, new_id);
assert!(old.is_none());
}
}
}
}
}
fn get_inlined_blocks(
function: &Function,
return_variable: Option<Word>,
return_jump: Word,
) -> Vec<Block> {
let mut blocks = function.blocks.clone();
for block in &mut blocks {
let last = block.instructions.last().unwrap();
if let Op::Return | Op::ReturnValue = last.class.opcode {
if Op::ReturnValue == last.class.opcode {
let return_value = last.operands[0].id_ref_any().unwrap();
block.instructions.insert(
block.instructions.len() - 1,
Instruction::new(
Op::Store,
None,
None,
vec![
Operand::IdRef(return_variable.unwrap()),
Operand::IdRef(return_value),
],
),
);
} else {
assert!(return_variable.is_none());
}
*block.instructions.last_mut().unwrap() =
Instruction::new(Op::Branch, None, None, vec![Operand::IdRef(return_jump)]);
}
}
blocks
}
fn insert_opvariable(block: &mut Block, ptr_ty: Word, result_id: Word) {
let index = block
.instructions
.iter()
.enumerate()
.find_map(|(index, inst)| {
if inst.class.opcode != Op::Variable {
Some(index)
} else {
None
}
});
let inst = Instruction::new(
Op::Variable,
Some(ptr_ty),
Some(result_id),
vec![Operand::StorageClass(StorageClass::Function)],
);
match index {
Some(index) => block.instructions.insert(index, inst),
None => block.instructions.push(inst),
}
}
fn insert_opvariables(block: &mut Block, mut insts: Vec<Instruction>) {
let index = block
.instructions
.iter()
.enumerate()
.find_map(|(index, inst)| {
if inst.class.opcode != Op::Variable {
Some(index)
} else {
None
}
});
match index {
Some(index) => {
block.instructions.splice(index..index, insts);
}
None => block.instructions.append(&mut insts),
}
}
fn fuse_trivial_branches(function: &mut Function) {
let all_preds = compute_preds(&function.blocks);
'outer: for (dest_block, mut preds) in all_preds.iter().enumerate() {
// if there's two trivial branches in a row, the middle one might get inlined before the
// last one, so when processing the last one, skip through to the first one.
let pred = loop {
if preds.len() != 1 || preds[0] == dest_block {
continue 'outer;
}
let pred = preds[0];
if !function.blocks[pred].instructions.is_empty() {
break pred;
}
preds = &all_preds[pred];
};
let pred_insts = &function.blocks[pred].instructions;
if pred_insts.last().unwrap().class.opcode == Op::Branch {
let mut dest_insts = take(&mut function.blocks[dest_block].instructions);
let pred_insts = &mut function.blocks[pred].instructions;
pred_insts.pop(); // pop the branch
pred_insts.append(&mut dest_insts);
}
}
function.blocks.retain(|b| !b.instructions.is_empty());
}
fn compute_preds(blocks: &[Block]) -> Vec<Vec<usize>> {
let mut result = vec![vec![]; blocks.len()];
for (source_idx, source) in blocks.iter().enumerate() {
for dest_id in outgoing_edges(source) {
let dest_idx = blocks
.iter()
.position(|b| b.label_id().unwrap() == dest_id)
.unwrap();
result[dest_idx].push(source_idx);
}
}
result
}