xdy 0.14.0

Complex RPG dice expression evaluator with probability distribution support.
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
//! # Dead code elimination
//!
//! Dead code elimination is the process of removing code that does not
//! contribute to the final output of a program. Dead code can only be the
//! result of previous optimizations. The dead code eliminator requires the
//! function to be in static single assignment (SSA) form.

use std::collections::HashMap;

use crate::{
	Add, AddressingMode, CanAllocate, CanVisitInstructions as _,
	DependencyAnalyzer, Div, DropHighest, DropLowest, Exp, Function,
	Instruction, InstructionVisitor, Max, Mod, Mul, Neg, Optimizer,
	RegisterIndex, Return, RollCustomDice, RollRange, RollStandardDice,
	RollingRecordIndex, Sub, SumRollingRecord
};

////////////////////////////////////////////////////////////////////////////////
//                           Dead code elimination.                           //
////////////////////////////////////////////////////////////////////////////////

/// A dead code eliminator removes instructions that do not contribute to the
/// final output of a function.
#[derive(Debug, Clone, Default)]
pub struct DeadCodeEliminator
{
	/// Replacements for registers, due to renumbering, as a map from originals
	/// to replacements. The keys are relative to the original function, and
	/// the values are relative to the optimized function.
	replacements: HashMap<AddressingMode, AddressingMode>,

	/// The next register index to allocate.
	next_register: RegisterIndex,

	/// The next rolling record index to allocate.
	next_rolling_record: RollingRecordIndex,

	/// The replacement instructions.
	instructions: Vec<Instruction>
}

impl Optimizer<()> for DeadCodeEliminator
{
	fn optimize(mut self, mut function: Function) -> Result<Function, ()>
	{
		// Skip over the parameters and externals when initializing the register
		// allocator. Don't bother to install them in the replacement map, as
		// they cannot be altered.
		let start_register =
			function.parameters.len() + function.externals.len();
		loop
		{
			// Reset the optimizer state.
			self.replacements.clear();
			self.next_register = RegisterIndex(start_register);
			self.next_rolling_record = RollingRecordIndex::default();
			self.instructions.clear();
			// Visit each instruction in the function body.
			let analyzer = DependencyAnalyzer::analyze(&function.instructions);
			for instruction in &function.instructions
			{
				instruction
					.visit(&mut AnalyticalVisitor(&analyzer, &mut self))
					.unwrap();
			}
			// Compare the old and new instructions. If they are the same, we
			// have reached a fixed point and can return the optimized function.
			if function.instructions == self.instructions
			{
				return Ok(function)
			}
			// Update the function to reflect the new instructions.
			function.register_count = self.next_register.0;
			function.rolling_record_count = self.next_rolling_record.0;
			function.instructions = self.instructions.clone();
			// Reset the optimizer state.
			self.replacements.clear();
			self.next_register = RegisterIndex(start_register);
			self.next_rolling_record = RollingRecordIndex::default();
			self.instructions.clear();
		}
	}
}

/// A visitor that performs the analysis necessary for dead code elimination.
struct AnalyticalVisitor<'inst>(
	&'inst DependencyAnalyzer<'inst>,
	&'inst mut DeadCodeEliminator
);

impl InstructionVisitor<()> for AnalyticalVisitor<'_>
{
	fn visit_roll_range(&mut self, range: &RollRange) -> Result<(), ()>
	{
		if self.is_rolling_record_live(range.dest)
		{
			let dest = self.next_rolling_record();
			self.replace(range.dest, dest);
			self.emit(RollRange {
				dest,
				start: self.replacement(range.start),
				end: self.replacement(range.end)
			});
		}
		Ok(())
	}

	fn visit_roll_standard_dice(
		&mut self,
		roll: &RollStandardDice
	) -> Result<(), ()>
	{
		if self.is_rolling_record_live(roll.dest)
		{
			let dest = self.next_rolling_record();
			self.replace(roll.dest, dest);
			self.emit(RollStandardDice {
				dest,
				count: self.replacement(roll.count),
				faces: self.replacement(roll.faces)
			});
		}
		Ok(())
	}

	fn visit_roll_custom_dice(
		&mut self,
		roll: &RollCustomDice
	) -> Result<(), ()>
	{
		if self.is_rolling_record_live(roll.dest)
		{
			let dest = self.next_rolling_record();
			self.replace(roll.dest, dest);
			self.emit(RollCustomDice {
				dest,
				count: self.replacement(roll.count),
				faces: roll.faces.clone()
			});
		}
		Ok(())
	}

	fn visit_drop_lowest(&mut self, drop: &DropLowest) -> Result<(), ()>
	{
		if self.is_rolling_record_live(drop.dest)
		{
			self.emit(DropLowest {
				dest: self.replacement(drop.dest).try_into().unwrap(),
				count: self.replacement(drop.count)
			});
		}
		Ok(())
	}

	fn visit_drop_highest(&mut self, drop: &DropHighest) -> Result<(), ()>
	{
		if self.is_rolling_record_live(drop.dest)
		{
			self.emit(DropHighest {
				dest: self.replacement(drop.dest).try_into().unwrap(),
				count: self.replacement(drop.count)
			});
		}
		Ok(())
	}

	fn visit_sum_rolling_record(
		&mut self,
		sum: &SumRollingRecord
	) -> Result<(), ()>
	{
		if self.has_readers(*sum)
		{
			let dest = self.next_register();
			self.replace(sum.dest, dest);
			self.emit(SumRollingRecord {
				dest,
				src: self.replacement(sum.src).try_into().unwrap()
			});
		}
		Ok(())
	}

	fn visit_add(&mut self, inst: &Add) -> Result<(), ()>
	{
		if self.has_readers(*inst)
		{
			let dest = self.next_register();
			self.replace(inst.dest, dest);
			self.emit(Add {
				dest,
				op1: self.replacement(inst.op1),
				op2: self.replacement(inst.op2)
			});
		}
		Ok(())
	}

	fn visit_sub(&mut self, inst: &Sub) -> Result<(), ()>
	{
		if self.has_readers(*inst)
		{
			let dest = self.next_register();
			self.replace(inst.dest, dest);
			self.emit(Sub {
				dest,
				op1: self.replacement(inst.op1),
				op2: self.replacement(inst.op2)
			});
		}
		Ok(())
	}

	fn visit_mul(&mut self, inst: &Mul) -> Result<(), ()>
	{
		if self.has_readers(*inst)
		{
			let dest = self.next_register();
			self.replace(inst.dest, dest);
			self.emit(Mul {
				dest,
				op1: self.replacement(inst.op1),
				op2: self.replacement(inst.op2)
			});
		}
		Ok(())
	}

	fn visit_div(&mut self, inst: &Div) -> Result<(), ()>
	{
		if self.has_readers(*inst)
		{
			let dest = self.next_register();
			self.replace(inst.dest, dest);
			self.emit(Div {
				dest,
				op1: self.replacement(inst.op1),
				op2: self.replacement(inst.op2)
			});
		}
		Ok(())
	}

	fn visit_mod(&mut self, inst: &Mod) -> Result<(), ()>
	{
		if self.has_readers(*inst)
		{
			let dest = self.next_register();
			self.replace(inst.dest, dest);
			self.emit(Mod {
				dest,
				op1: self.replacement(inst.op1),
				op2: self.replacement(inst.op2)
			});
		}
		Ok(())
	}

	fn visit_exp(&mut self, inst: &Exp) -> Result<(), ()>
	{
		if self.has_readers(*inst)
		{
			let dest = self.next_register();
			self.replace(inst.dest, dest);
			self.emit(Exp {
				dest,
				op1: self.replacement(inst.op1),
				op2: self.replacement(inst.op2)
			});
		}
		Ok(())
	}

	fn visit_max(&mut self, inst: &Max) -> Result<(), ()>
	{
		if self.has_readers(*inst)
		{
			let dest = self.next_register();
			self.replace(inst.dest, dest);
			self.emit(Max {
				dest,
				op1: self.replacement(inst.op1),
				op2: self.replacement(inst.op2)
			});
		}
		Ok(())
	}

	fn visit_neg(&mut self, inst: &Neg) -> Result<(), ()>
	{
		if self.has_readers(*inst)
		{
			let dest = self.next_register();
			self.replace(inst.dest, dest);
			self.emit(Neg {
				dest,
				op: self.replacement(inst.op)
			});
		}
		Ok(())
	}

	fn visit_return(&mut self, inst: &Return) -> Result<(), ()>
	{
		self.emit(Return {
			src: self.replacement(inst.src)
		});
		Ok(())
	}
}

impl AnalyticalVisitor<'_>
{
	/// Answer the next available register index.
	///
	/// # Returns
	/// The next available register index.
	fn next_register(&mut self) -> RegisterIndex
	{
		self.1.next_register.allocate()
	}

	/// Answer the next available rolling record index.
	///
	/// # Returns
	/// The next available rolling record index.
	fn next_rolling_record(&mut self) -> RollingRecordIndex
	{
		self.1.next_rolling_record.allocate()
	}

	/// Set the replacement for the specified operand.
	///
	/// # Parameters
	/// - `old`: The operand to replace.
	/// - `new`: The replacement operand.
	fn replace(
		&mut self,
		old: impl Into<AddressingMode>,
		new: impl Into<AddressingMode>
	)
	{
		self.1.replacements.insert(old.into(), new.into());
	}

	/// Determine whether the specified instruction has downstream readers. If
	/// it does not, then the instruction is dead. Should only be used with
	/// instructions that have a destination.
	///
	/// # Parameters
	/// - `inst`: The instruction to check.
	///
	/// # Returns
	/// `true` if the instruction has downstream readers, `false` otherwise.
	fn has_readers(&self, inst: impl Into<Instruction>) -> bool
	{
		self.0
			.readers()
			.get(&inst.into().destination().unwrap())
			.map(|readers| !readers.is_empty())
			.unwrap_or(false)
	}

	/// Determine whether the specified rolling record is live, i.e., whether
	/// any instruction consumes it, rather than merely modifying it in place.
	/// Drops both read and write the rolling record that they modify, so a
	/// rolling record with no readers besides its own drops never contributes
	/// to the result, and neither its roll nor its drops need to survive.
	///
	/// # Parameters
	/// - `record`: The rolling record to check.
	///
	/// # Returns
	/// `true` if the rolling record has a reader other than an instruction that
	/// modifies it in place, `false` otherwise.
	fn is_rolling_record_live(&self, record: RollingRecordIndex) -> bool
	{
		let record = AddressingMode::from(record);
		let instructions = self.0.instructions();
		self.0
			.readers()
			.get(&record)
			.map(|readers| {
				readers
					.iter()
					.any(|pc| instructions[pc.0].destination() != Some(record))
			})
			.unwrap_or(false)
	}

	/// Look up the replacement of the specified operand, falling back to the
	/// operand itself if no replacement is found.
	///
	/// # Parameters
	/// - `op`: The operand to look up.
	///
	/// # Returns
	/// The replacement for the operand.
	#[inline]
	fn replacement(&self, op: impl Into<AddressingMode>) -> AddressingMode
	{
		let op: AddressingMode = op.into();
		*self.1.replacements.get(&op).unwrap_or(&op)
	}

	/// Emit the specified instruction.
	///
	/// # Parameters
	/// - `inst`: The instruction to emit.
	#[inline]
	fn emit(&mut self, inst: impl Into<Instruction>)
	{
		self.1.instructions.push(inst.into());
	}
}