1 use crate::config::Config;
2 use crate::cranelift_arbitrary::CraneliftArbitrary;
3 use crate::target_isa_extras::TargetIsaExtras;
4 use anyhow::Result;
5 use arbitrary::{Arbitrary, Unstructured};
6 use cranelift::codegen::data_value::DataValue;
7 use cranelift::codegen::ir::immediates::Offset32;
8 use cranelift::codegen::ir::instructions::{InstructionFormat, ResolvedConstraint};
9 use cranelift::codegen::ir::stackslot::StackSize;
10 
11 use cranelift::codegen::ir::{
12     AliasRegion, AtomicRmwOp, Block, BlockArg, ConstantData, Endianness, ExternalName, FuncRef,
13     Function, LibCall, Opcode, SigRef, Signature, StackSlot, UserExternalName, UserFuncName, Value,
14     types::*,
15 };
16 use cranelift::codegen::isa::CallConv;
17 use cranelift::frontend::{FunctionBuilder, FunctionBuilderContext, Switch, Variable};
18 use cranelift::prelude::isa::OwnedTargetIsa;
19 use cranelift::prelude::{
20     ExtFuncData, FloatCC, InstBuilder, IntCC, JumpTableData, MemFlags, StackSlotData, StackSlotKind,
21 };
22 use std::collections::HashMap;
23 use std::ops::RangeInclusive;
24 use std::str::FromStr;
25 use std::sync::LazyLock;
26 use target_lexicon::{Architecture, Triple};
27 
28 type BlockSignature = Vec<Type>;
29 
30 fn insert_opcode(
31     fgen: &mut FunctionGenerator,
32     builder: &mut FunctionBuilder,
33     opcode: Opcode,
34     args: &[Type],
35     rets: &[Type],
36 ) -> Result<()> {
37     let mut vals = Vec::with_capacity(args.len());
38     for &arg in args.into_iter() {
39         let var = fgen.get_variable_of_type(arg)?;
40         let val = builder.use_var(var);
41         vals.push(val);
42     }
43 
44     // Some opcodes require us to look at their input arguments to determine the
45     // controlling type. This is not the general case, but we can neatly check this
46     // using `requires_typevar_operand`.
47     let ctrl_type = if opcode.constraints().requires_typevar_operand() {
48         args.first()
49     } else {
50         rets.first()
51     }
52     .copied()
53     .unwrap_or(INVALID);
54 
55     // Choose the appropriate instruction format for this opcode
56     let (inst, dfg) = match opcode.format() {
57         InstructionFormat::NullAry => builder.ins().NullAry(opcode, ctrl_type),
58         InstructionFormat::Unary => builder.ins().Unary(opcode, ctrl_type, vals[0]),
59         InstructionFormat::Binary => builder.ins().Binary(opcode, ctrl_type, vals[0], vals[1]),
60         InstructionFormat::Ternary => builder
61             .ins()
62             .Ternary(opcode, ctrl_type, vals[0], vals[1], vals[2]),
63         _ => unimplemented!(),
64     };
65     let results = dfg.inst_results(inst).to_vec();
66 
67     for (val, &ty) in results.into_iter().zip(rets) {
68         let var = fgen.get_variable_of_type(ty)?;
69         builder.def_var(var, val);
70     }
71     Ok(())
72 }
73 
74 fn insert_call_to_function(
75     fgen: &mut FunctionGenerator,
76     builder: &mut FunctionBuilder,
77     call_opcode: Opcode,
78     sig: &Signature,
79     sig_ref: SigRef,
80     func_ref: FuncRef,
81 ) -> Result<()> {
82     let actuals = fgen.generate_values_for_signature(
83         builder,
84         sig.params.iter().map(|abi_param| abi_param.value_type),
85     )?;
86 
87     let addr_ty = fgen.isa.pointer_type();
88     let call = match call_opcode {
89         Opcode::Call => builder.ins().call(func_ref, &actuals),
90         Opcode::ReturnCall => builder.ins().return_call(func_ref, &actuals),
91         Opcode::CallIndirect => {
92             let addr = builder.ins().func_addr(addr_ty, func_ref);
93             builder.ins().call_indirect(sig_ref, addr, &actuals)
94         }
95         Opcode::ReturnCallIndirect => {
96             let addr = builder.ins().func_addr(addr_ty, func_ref);
97             builder.ins().return_call_indirect(sig_ref, addr, &actuals)
98         }
99         _ => unreachable!(),
100     };
101 
102     // Assign the return values to random variables
103     let ret_values = builder.inst_results(call).to_vec();
104     let ret_types = sig.returns.iter().map(|p| p.value_type);
105     for (ty, val) in ret_types.zip(ret_values) {
106         let var = fgen.get_variable_of_type(ty)?;
107         builder.def_var(var, val);
108     }
109 
110     Ok(())
111 }
112 
113 fn insert_call(
114     fgen: &mut FunctionGenerator,
115     builder: &mut FunctionBuilder,
116     opcode: Opcode,
117     _args: &[Type],
118     _rets: &[Type],
119 ) -> Result<()> {
120     assert!(matches!(opcode, Opcode::Call | Opcode::CallIndirect));
121     let (sig, sig_ref, func_ref) = fgen.u.choose(&fgen.resources.func_refs)?.clone();
122     insert_call_to_function(fgen, builder, opcode, &sig, sig_ref, func_ref)
123 }
124 
125 fn insert_stack_load(
126     fgen: &mut FunctionGenerator,
127     builder: &mut FunctionBuilder,
128     _opcode: Opcode,
129     _args: &[Type],
130     rets: &[Type],
131 ) -> Result<()> {
132     let typevar = rets[0];
133     let type_size = typevar.bytes();
134     let (slot, slot_size, _align, category) = fgen.stack_slot_with_size(type_size)?;
135 
136     // `stack_load` doesn't support setting MemFlags, and it does not set any
137     // alias analysis bits, so we can only emit it for `Other` slots.
138     if category != AACategory::Other {
139         return Err(arbitrary::Error::IncorrectFormat.into());
140     }
141 
142     let offset = fgen.u.int_in_range(0..=(slot_size - type_size))? as i32;
143 
144     let val = builder.ins().stack_load(typevar, slot, offset);
145     let var = fgen.get_variable_of_type(typevar)?;
146     builder.def_var(var, val);
147 
148     Ok(())
149 }
150 
151 fn insert_stack_store(
152     fgen: &mut FunctionGenerator,
153     builder: &mut FunctionBuilder,
154     _opcode: Opcode,
155     args: &[Type],
156     _rets: &[Type],
157 ) -> Result<()> {
158     let typevar = args[0];
159     let type_size = typevar.bytes();
160 
161     let (slot, slot_size, _align, category) = fgen.stack_slot_with_size(type_size)?;
162 
163     // `stack_store` doesn't support setting MemFlags, and it does not set any
164     // alias analysis bits, so we can only emit it for `Other` slots.
165     if category != AACategory::Other {
166         return Err(arbitrary::Error::IncorrectFormat.into());
167     }
168 
169     let offset = fgen.u.int_in_range(0..=(slot_size - type_size))? as i32;
170 
171     let arg0 = fgen.get_variable_of_type(typevar)?;
172     let arg0 = builder.use_var(arg0);
173 
174     builder.ins().stack_store(arg0, slot, offset);
175     Ok(())
176 }
177 
178 fn insert_cmp(
179     fgen: &mut FunctionGenerator,
180     builder: &mut FunctionBuilder,
181     opcode: Opcode,
182     args: &[Type],
183     rets: &[Type],
184 ) -> Result<()> {
185     let lhs = fgen.get_variable_of_type(args[0])?;
186     let lhs = builder.use_var(lhs);
187 
188     let rhs = fgen.get_variable_of_type(args[1])?;
189     let rhs = builder.use_var(rhs);
190 
191     let res = if opcode == Opcode::Fcmp {
192         let cc = *fgen.u.choose(FloatCC::all())?;
193 
194         // We filter out condition codes that aren't supported by the target at
195         // this point after randomly choosing one, instead of randomly choosing a
196         // supported one, to avoid invalidating the corpus when these get implemented.
197         let unimplemented_cc = match (fgen.isa.triple().architecture, cc) {
198             // Some FloatCC's are not implemented on AArch64, see:
199             // https://github.com/bytecodealliance/wasmtime/issues/4850
200             (Architecture::Aarch64(_), FloatCC::OrderedNotEqual) => true,
201             (Architecture::Aarch64(_), FloatCC::UnorderedOrEqual) => true,
202 
203             // These are not implemented on x86_64, for vectors.
204             (Architecture::X86_64, FloatCC::UnorderedOrEqual | FloatCC::OrderedNotEqual) => {
205                 args[0].is_vector()
206             }
207             _ => false,
208         };
209         if unimplemented_cc {
210             return Err(arbitrary::Error::IncorrectFormat.into());
211         }
212 
213         builder.ins().fcmp(cc, lhs, rhs)
214     } else {
215         let cc = *fgen.u.choose(IntCC::all())?;
216         builder.ins().icmp(cc, lhs, rhs)
217     };
218 
219     let var = fgen.get_variable_of_type(rets[0])?;
220     builder.def_var(var, res);
221 
222     Ok(())
223 }
224 
225 fn insert_const(
226     fgen: &mut FunctionGenerator,
227     builder: &mut FunctionBuilder,
228     _opcode: Opcode,
229     _args: &[Type],
230     rets: &[Type],
231 ) -> Result<()> {
232     let typevar = rets[0];
233     let var = fgen.get_variable_of_type(typevar)?;
234     let val = fgen.generate_const(builder, typevar)?;
235     builder.def_var(var, val);
236     Ok(())
237 }
238 
239 fn insert_bitcast(
240     fgen: &mut FunctionGenerator,
241     builder: &mut FunctionBuilder,
242     args: &[Type],
243     rets: &[Type],
244 ) -> Result<()> {
245     let from_var = fgen.get_variable_of_type(args[0])?;
246     let from_val = builder.use_var(from_var);
247 
248     let to_var = fgen.get_variable_of_type(rets[0])?;
249 
250     // TODO: We can generate little/big endian flags here.
251     let mut memflags = MemFlags::new();
252 
253     // When bitcasting between vectors of different lane counts, we need to
254     // specify the endianness.
255     if args[0].lane_count() != rets[0].lane_count() {
256         memflags.set_endianness(Endianness::Little);
257     }
258 
259     let res = builder.ins().bitcast(rets[0], memflags, from_val);
260     builder.def_var(to_var, res);
261     Ok(())
262 }
263 
264 fn insert_load_store(
265     fgen: &mut FunctionGenerator,
266     builder: &mut FunctionBuilder,
267     opcode: Opcode,
268     args: &[Type],
269     rets: &[Type],
270 ) -> Result<()> {
271     if opcode == Opcode::Bitcast {
272         return insert_bitcast(fgen, builder, args, rets);
273     }
274 
275     let ctrl_type = *rets.first().or(args.first()).unwrap();
276     let type_size = ctrl_type.bytes();
277 
278     let is_atomic = [Opcode::AtomicLoad, Opcode::AtomicStore].contains(&opcode);
279     let (address, flags, offset) =
280         fgen.generate_address_and_memflags(builder, type_size, is_atomic)?;
281 
282     // The variable being loaded or stored into
283     let var = fgen.get_variable_of_type(ctrl_type)?;
284 
285     match opcode.format() {
286         InstructionFormat::LoadNoOffset => {
287             let (inst, dfg) = builder
288                 .ins()
289                 .LoadNoOffset(opcode, ctrl_type, flags, address);
290 
291             let new_val = dfg.first_result(inst);
292             builder.def_var(var, new_val);
293         }
294         InstructionFormat::StoreNoOffset => {
295             let val = builder.use_var(var);
296 
297             builder
298                 .ins()
299                 .StoreNoOffset(opcode, ctrl_type, flags, val, address);
300         }
301         InstructionFormat::Store => {
302             let val = builder.use_var(var);
303 
304             builder
305                 .ins()
306                 .Store(opcode, ctrl_type, flags, offset, val, address);
307         }
308         InstructionFormat::Load => {
309             let (inst, dfg) = builder
310                 .ins()
311                 .Load(opcode, ctrl_type, flags, offset, address);
312 
313             let new_val = dfg.first_result(inst);
314             builder.def_var(var, new_val);
315         }
316         _ => unimplemented!(),
317     }
318 
319     Ok(())
320 }
321 
322 fn insert_atomic_rmw(
323     fgen: &mut FunctionGenerator,
324     builder: &mut FunctionBuilder,
325     _: Opcode,
326     _: &[Type],
327     rets: &[Type],
328 ) -> Result<()> {
329     let ctrl_type = *rets.first().unwrap();
330     let type_size = ctrl_type.bytes();
331 
332     let rmw_op = *fgen.u.choose(AtomicRmwOp::all())?;
333 
334     let (address, flags, offset) = fgen.generate_address_and_memflags(builder, type_size, true)?;
335 
336     // AtomicRMW does not directly support offsets, so add the offset to the address separately.
337     let address = builder.ins().iadd_imm(address, i64::from(offset));
338 
339     // Load and store target variables
340     let source_var = fgen.get_variable_of_type(ctrl_type)?;
341     let target_var = fgen.get_variable_of_type(ctrl_type)?;
342 
343     let source_val = builder.use_var(source_var);
344     let new_val = builder
345         .ins()
346         .atomic_rmw(ctrl_type, flags, rmw_op, address, source_val);
347 
348     builder.def_var(target_var, new_val);
349     Ok(())
350 }
351 
352 fn insert_atomic_cas(
353     fgen: &mut FunctionGenerator,
354     builder: &mut FunctionBuilder,
355     _: Opcode,
356     _: &[Type],
357     rets: &[Type],
358 ) -> Result<()> {
359     let ctrl_type = *rets.first().unwrap();
360     let type_size = ctrl_type.bytes();
361 
362     let (address, flags, offset) = fgen.generate_address_and_memflags(builder, type_size, true)?;
363 
364     // AtomicCas does not directly support offsets, so add the offset to the address separately.
365     let address = builder.ins().iadd_imm(address, i64::from(offset));
366 
367     // Source and Target variables
368     let expected_var = fgen.get_variable_of_type(ctrl_type)?;
369     let store_var = fgen.get_variable_of_type(ctrl_type)?;
370     let loaded_var = fgen.get_variable_of_type(ctrl_type)?;
371 
372     let expected_val = builder.use_var(expected_var);
373     let store_val = builder.use_var(store_var);
374     let new_val = builder
375         .ins()
376         .atomic_cas(flags, address, expected_val, store_val);
377 
378     builder.def_var(loaded_var, new_val);
379     Ok(())
380 }
381 
382 fn insert_shuffle(
383     fgen: &mut FunctionGenerator,
384     builder: &mut FunctionBuilder,
385     opcode: Opcode,
386     _: &[Type],
387     rets: &[Type],
388 ) -> Result<()> {
389     let ctrl_type = *rets.first().unwrap();
390 
391     let lhs = builder.use_var(fgen.get_variable_of_type(ctrl_type)?);
392     let rhs = builder.use_var(fgen.get_variable_of_type(ctrl_type)?);
393 
394     let mask = {
395         let mut lanes = [0u8; 16];
396         for lane in lanes.iter_mut() {
397             *lane = fgen.u.int_in_range(0..=31)?;
398         }
399         let lanes = ConstantData::from(lanes.as_ref());
400         builder.func.dfg.immediates.push(lanes)
401     };
402 
403     // This function is called for any `InstructionFormat::Shuffle`. Which today is just
404     // `shuffle`, but lets assert that, just to be sure we don't accidentally insert
405     // something else.
406     assert_eq!(opcode, Opcode::Shuffle);
407     let res = builder.ins().shuffle(lhs, rhs, mask);
408 
409     let target_var = fgen.get_variable_of_type(ctrl_type)?;
410     builder.def_var(target_var, res);
411 
412     Ok(())
413 }
414 
415 fn insert_ins_ext_lane(
416     fgen: &mut FunctionGenerator,
417     builder: &mut FunctionBuilder,
418     opcode: Opcode,
419     args: &[Type],
420     rets: &[Type],
421 ) -> Result<()> {
422     let vector_type = *args.first().unwrap();
423     let ret_type = *rets.first().unwrap();
424 
425     let lhs = builder.use_var(fgen.get_variable_of_type(vector_type)?);
426     let max_lane = (vector_type.lane_count() as u8) - 1;
427     let lane = fgen.u.int_in_range(0..=max_lane)?;
428 
429     let res = match opcode {
430         Opcode::Insertlane => {
431             let rhs = builder.use_var(fgen.get_variable_of_type(args[1])?);
432             builder.ins().insertlane(lhs, rhs, lane)
433         }
434         Opcode::Extractlane => builder.ins().extractlane(lhs, lane),
435         _ => todo!(),
436     };
437 
438     let target_var = fgen.get_variable_of_type(ret_type)?;
439     builder.def_var(target_var, res);
440 
441     Ok(())
442 }
443 
444 type OpcodeInserter = fn(
445     fgen: &mut FunctionGenerator,
446     builder: &mut FunctionBuilder,
447     Opcode,
448     &[Type],
449     &[Type],
450 ) -> Result<()>;
451 
452 macro_rules! exceptions {
453     ($op:expr, $args:expr, $rets:expr, $(($($cases:pat),*)),* $(,)?) => {
454         match ($op, $args, $rets) {
455             $( ($($cases,)* ..) => return false, )*
456             _ => true,
457         }
458     }
459 }
460 
461 /// Returns true if we believe this `OpcodeSignature` should compile correctly
462 /// for the given target triple. We currently have a range of known issues
463 /// with specific lowerings on specific backends, and we don't want to get
464 /// fuzz bug reports for those. Over time our goal is to eliminate all of these
465 /// exceptions.
466 fn valid_for_target(triple: &Triple, op: Opcode, args: &[Type], rets: &[Type]) -> bool {
467     // Rule out invalid combinations that we don't yet have a good way of rejecting with the
468     // instruction DSL type constraints.
469     match op {
470         Opcode::FcvtToUintSat | Opcode::FcvtToSintSat => {
471             assert_eq!(args.len(), 1);
472             assert_eq!(rets.len(), 1);
473 
474             let arg = args[0];
475             let ret = rets[0];
476 
477             // Vector arguments must produce vector results, and scalar arguments must produce
478             // scalar results.
479             if arg.is_vector() != ret.is_vector() {
480                 return false;
481             }
482 
483             if arg.is_vector() && ret.is_vector() {
484                 // Vector conversions must have the same number of lanes, and the lanes must be the
485                 // same bit-width.
486                 if arg.lane_count() != ret.lane_count() {
487                     return false;
488                 }
489 
490                 if arg.lane_of().bits() != ret.lane_of().bits() {
491                     return false;
492                 }
493             }
494         }
495 
496         Opcode::Bitcast => {
497             assert_eq!(args.len(), 1);
498             assert_eq!(rets.len(), 1);
499 
500             let arg = args[0];
501             let ret = rets[0];
502 
503             // The opcode generator still allows bitcasts between different sized types, but these
504             // are rejected in the verifier.
505             if arg.bits() != ret.bits() {
506                 return false;
507             }
508         }
509 
510         // This requires precise runtime integration so it's not supported at
511         // all in fuzzgen just yet.
512         Opcode::StackSwitch => return false,
513 
514         _ => {}
515     }
516 
517     match triple.architecture {
518         Architecture::X86_64 => {
519             exceptions!(
520                 op,
521                 args,
522                 rets,
523                 (Opcode::UmulOverflow | Opcode::SmulOverflow, &[I128, I128]),
524                 (Opcode::Imul, &[I8X16, I8X16]),
525                 // https://github.com/bytecodealliance/wasmtime/issues/4756
526                 (Opcode::Udiv | Opcode::Sdiv, &[I128, I128]),
527                 // https://github.com/bytecodealliance/wasmtime/issues/5474
528                 (Opcode::Urem | Opcode::Srem, &[I128, I128]),
529                 // https://github.com/bytecodealliance/wasmtime/issues/3370
530                 (
531                     Opcode::Smin | Opcode::Umin | Opcode::Smax | Opcode::Umax,
532                     &[I128, I128]
533                 ),
534                 // https://github.com/bytecodealliance/wasmtime/issues/5107
535                 (Opcode::Cls, &[I8], &[I8]),
536                 (Opcode::Cls, &[I16], &[I16]),
537                 (Opcode::Cls, &[I32], &[I32]),
538                 (Opcode::Cls, &[I64], &[I64]),
539                 (Opcode::Cls, &[I128], &[I128]),
540                 // TODO
541                 (Opcode::Bitselect, &[_, _, _], &[F32 | F64]),
542                 // https://github.com/bytecodealliance/wasmtime/issues/4897
543                 // https://github.com/bytecodealliance/wasmtime/issues/4899
544                 (
545                     Opcode::FcvtToUint
546                         | Opcode::FcvtToUintSat
547                         | Opcode::FcvtToSint
548                         | Opcode::FcvtToSintSat,
549                     &[F32 | F64],
550                     &[I8 | I16 | I128]
551                 ),
552                 (Opcode::FcvtToUint | Opcode::FcvtToSint, &[F32X4], &[I32X4]),
553                 (
554                     Opcode::FcvtToUint
555                         | Opcode::FcvtToUintSat
556                         | Opcode::FcvtToSint
557                         | Opcode::FcvtToSintSat,
558                     &[F64X2],
559                     &[I64X2]
560                 ),
561                 // https://github.com/bytecodealliance/wasmtime/issues/4900
562                 (Opcode::FcvtFromUint, &[I128], &[F32 | F64]),
563                 // This has a lowering, but only when preceded by `uwiden_low`.
564                 (Opcode::FcvtFromUint, &[I64X2], &[F64X2]),
565                 // https://github.com/bytecodealliance/wasmtime/issues/4900
566                 (Opcode::FcvtFromSint, &[I128], &[F32 | F64]),
567                 (Opcode::FcvtFromSint, &[I64X2], &[F64X2]),
568                 (
569                     Opcode::Umulhi | Opcode::Smulhi,
570                     &([I8X16, I8X16] | [I16X8, I16X8] | [I32X4, I32X4] | [I64X2, I64X2])
571                 ),
572                 (
573                     Opcode::UaddSat | Opcode::SaddSat | Opcode::UsubSat | Opcode::SsubSat,
574                     &([I32X4, I32X4] | [I64X2, I64X2])
575                 ),
576                 (Opcode::Fcopysign, &([F32X4, F32X4] | [F64X2, F64X2])),
577                 (Opcode::Popcnt, &([I8X16] | [I16X8] | [I32X4] | [I64X2])),
578                 (
579                     Opcode::Umax | Opcode::Smax | Opcode::Umin | Opcode::Smin,
580                     &[I64X2, I64X2]
581                 ),
582                 // https://github.com/bytecodealliance/wasmtime/issues/6104
583                 (Opcode::Bitcast, &[I128], &[_]),
584                 (Opcode::Bitcast, &[_], &[I128]),
585                 (Opcode::Uunarrow),
586                 (Opcode::Snarrow | Opcode::Unarrow, &[I64X2, I64X2]),
587                 (Opcode::SqmulRoundSat, &[I32X4, I32X4]),
588                 // This Icmp is not implemented: #5529
589                 (Opcode::Icmp, &[I64X2, I64X2]),
590                 // IaddPairwise is implemented, but only for some types, and with some preceding ops.
591                 (Opcode::IaddPairwise),
592                 // Nothing wrong with this select. But we have an isle rule that can optimize it
593                 // into a `min`/`max` instructions, which we don't have implemented yet.
594                 (Opcode::Select, &[_, I128, I128]),
595                 // These stack accesses can cause segfaults if they are merged into an SSE instruction.
596                 // See: #5922
597                 (
598                     Opcode::StackStore,
599                     &[I8X16 | I16X8 | I32X4 | I64X2 | F32X4 | F64X2]
600                 ),
601                 (
602                     Opcode::StackLoad,
603                     &[],
604                     &[I8X16 | I16X8 | I32X4 | I64X2 | F32X4 | F64X2]
605                 ),
606                 // TODO
607                 (
608                     Opcode::Sshr | Opcode::Ushr | Opcode::Ishl,
609                     &[I8X16 | I16X8 | I32X4 | I64X2, I128]
610                 ),
611                 (
612                     Opcode::Rotr | Opcode::Rotl,
613                     &[I8X16 | I16X8 | I32X4 | I64X2, _]
614                 ),
615             )
616         }
617 
618         Architecture::Aarch64(_) => {
619             exceptions!(
620                 op,
621                 args,
622                 rets,
623                 (Opcode::UmulOverflow | Opcode::SmulOverflow, &[I128, I128]),
624                 // https://github.com/bytecodealliance/wasmtime/issues/4864
625                 (Opcode::Udiv | Opcode::Sdiv, &[I128, I128]),
626                 // https://github.com/bytecodealliance/wasmtime/issues/5472
627                 (Opcode::Urem | Opcode::Srem, &[I128, I128]),
628                 // https://github.com/bytecodealliance/wasmtime/issues/4313
629                 (
630                     Opcode::Smin | Opcode::Umin | Opcode::Smax | Opcode::Umax,
631                     &[I128, I128]
632                 ),
633                 // https://github.com/bytecodealliance/wasmtime/issues/4870
634                 (Opcode::Bnot, &[F32 | F64]),
635                 (
636                     Opcode::Band
637                         | Opcode::Bor
638                         | Opcode::Bxor
639                         | Opcode::BandNot
640                         | Opcode::BorNot
641                         | Opcode::BxorNot,
642                     &([F32, F32] | [F64, F64])
643                 ),
644                 // https://github.com/bytecodealliance/wasmtime/issues/5198
645                 (Opcode::Bitselect, &[I128, I128, I128]),
646                 // https://github.com/bytecodealliance/wasmtime/issues/4934
647                 (
648                     Opcode::FcvtToUint
649                         | Opcode::FcvtToUintSat
650                         | Opcode::FcvtToSint
651                         | Opcode::FcvtToSintSat,
652                     &[F32 | F64],
653                     &[I128]
654                 ),
655                 // https://github.com/bytecodealliance/wasmtime/issues/4933
656                 (
657                     Opcode::FcvtFromUint | Opcode::FcvtFromSint,
658                     &[I128],
659                     &[F32 | F64]
660                 ),
661                 (
662                     Opcode::Umulhi | Opcode::Smulhi,
663                     &([I8X16, I8X16] | [I16X8, I16X8] | [I32X4, I32X4] | [I64X2, I64X2])
664                 ),
665                 (Opcode::Popcnt, &[I16X8 | I32X4 | I64X2]),
666                 // Nothing wrong with this select. But we have an isle rule that can optimize it
667                 // into a `min`/`max` instructions, which we don't have implemented yet.
668                 (Opcode::Select, &[I8, I128, I128]),
669                 // https://github.com/bytecodealliance/wasmtime/issues/6104
670                 (Opcode::Bitcast, &[I128], &[_]),
671                 (Opcode::Bitcast, &[_], &[I128]),
672                 // TODO
673                 (
674                     Opcode::Sshr | Opcode::Ushr | Opcode::Ishl,
675                     &[I8X16 | I16X8 | I32X4 | I64X2, I128]
676                 ),
677                 (
678                     Opcode::Rotr | Opcode::Rotl,
679                     &[I8X16 | I16X8 | I32X4 | I64X2, _]
680                 ),
681                 // TODO
682                 (Opcode::Bitselect, &[_, _, _], &[F32 | F64]),
683                 (Opcode::VhighBits, &[F32X4 | F64X2]),
684             )
685         }
686 
687         Architecture::S390x => {
688             exceptions!(
689                 op,
690                 args,
691                 rets,
692                 (Opcode::UaddOverflow | Opcode::SaddOverflow),
693                 (Opcode::UsubOverflow | Opcode::SsubOverflow),
694                 (Opcode::UmulOverflow | Opcode::SmulOverflow),
695                 (
696                     Opcode::Udiv | Opcode::Sdiv | Opcode::Urem | Opcode::Srem,
697                     &[I128, I128]
698                 ),
699                 (Opcode::Bnot, &[F32 | F64]),
700                 (
701                     Opcode::Band
702                         | Opcode::Bor
703                         | Opcode::Bxor
704                         | Opcode::BandNot
705                         | Opcode::BorNot
706                         | Opcode::BxorNot,
707                     &([F32, F32] | [F64, F64])
708                 ),
709                 (
710                     Opcode::FcvtToUint
711                         | Opcode::FcvtToUintSat
712                         | Opcode::FcvtToSint
713                         | Opcode::FcvtToSintSat,
714                     &[F32 | F64],
715                     &[I128]
716                 ),
717                 (
718                     Opcode::FcvtFromUint | Opcode::FcvtFromSint,
719                     &[I128],
720                     &[F32 | F64]
721                 ),
722                 (Opcode::SsubSat | Opcode::SaddSat, &[I64X2, I64X2]),
723                 // https://github.com/bytecodealliance/wasmtime/issues/6104
724                 (Opcode::Bitcast, &[I128], &[_]),
725                 (Opcode::Bitcast, &[_], &[I128]),
726                 // TODO
727                 (Opcode::Bitselect, &[_, _, _], &[F32 | F64]),
728             )
729         }
730 
731         Architecture::Riscv64(_) => {
732             exceptions!(
733                 op,
734                 args,
735                 rets,
736                 // TODO
737                 (Opcode::UaddOverflow | Opcode::SaddOverflow),
738                 (Opcode::UsubOverflow | Opcode::SsubOverflow),
739                 (Opcode::UmulOverflow | Opcode::SmulOverflow),
740                 // TODO
741                 (
742                     Opcode::Udiv | Opcode::Sdiv | Opcode::Urem | Opcode::Srem,
743                     &[I128, I128]
744                 ),
745                 // TODO
746                 (Opcode::Iabs, &[I128]),
747                 // TODO
748                 (Opcode::Bitselect, &[I128, I128, I128]),
749                 // https://github.com/bytecodealliance/wasmtime/issues/5528
750                 (
751                     Opcode::FcvtToUint | Opcode::FcvtToSint,
752                     [F32 | F64],
753                     &[I128]
754                 ),
755                 (
756                     Opcode::FcvtToUintSat | Opcode::FcvtToSintSat,
757                     &[F32 | F64],
758                     &[I128]
759                 ),
760                 // https://github.com/bytecodealliance/wasmtime/issues/5528
761                 (
762                     Opcode::FcvtFromUint | Opcode::FcvtFromSint,
763                     &[I128],
764                     &[F32 | F64]
765                 ),
766                 // TODO
767                 (
768                     Opcode::SelectSpectreGuard,
769                     &[_, _, _],
770                     &[F32 | F64 | I8X16 | I16X8 | I32X4 | I64X2 | F64X2 | F32X4]
771                 ),
772                 // TODO
773                 (Opcode::Bitselect, &[_, _, _], &[F32 | F64]),
774                 (
775                     Opcode::Rotr | Opcode::Rotl,
776                     &[I8X16 | I16X8 | I32X4 | I64X2, _]
777                 ),
778             )
779         }
780 
781         _ => true,
782     }
783 }
784 
785 type OpcodeSignature = (Opcode, Vec<Type>, Vec<Type>);
786 
787 static OPCODE_SIGNATURES: LazyLock<Vec<OpcodeSignature>> = LazyLock::new(|| {
788     let types = &[
789         I8, I16, I32, I64, I128, // Scalar Integers
790         F32, F64, // Scalar Floats
791         I8X16, I16X8, I32X4, I64X2, // SIMD Integers
792         F32X4, F64X2, // SIMD Floats
793     ];
794 
795     // When this env variable is passed, we only generate instructions for the opcodes listed in
796     // the comma-separated list. This is useful for debugging, as it allows us to focus on a few
797     // specific opcodes.
798     let allowed_opcodes = std::env::var("FUZZGEN_ALLOWED_OPS").ok().map(|s| {
799         s.split(',')
800             .map(|s| s.trim())
801             .filter(|s| !s.is_empty())
802             .map(|s| Opcode::from_str(s).expect("Unrecoginzed opcode"))
803             .collect::<Vec<_>>()
804     });
805 
806     Opcode::all()
807         .iter()
808         .filter(|op| {
809             match op {
810                 // Control flow opcodes should not be generated through `generate_instructions`.
811                 Opcode::BrTable
812                 | Opcode::Brif
813                 | Opcode::Jump
814                 | Opcode::Return
815                 | Opcode::ReturnCall
816                 | Opcode::ReturnCallIndirect
817                 | Opcode::TryCall
818                 | Opcode::TryCallIndirect => false,
819 
820                 // Constants are generated outside of `generate_instructions`
821                 Opcode::Iconst => false,
822 
823                 // TODO: extract_vector raises exceptions during return type generation because it
824                 // uses dynamic vectors.
825                 Opcode::ExtractVector => false,
826 
827                 _ => true,
828             }
829         })
830         .flat_map(|op| {
831             let constraints = op.constraints();
832 
833             let ctrl_types = if let Some(ctrls) = constraints.ctrl_typeset() {
834                 Vec::from_iter(types.iter().copied().filter(|ty| ctrls.contains(*ty)))
835             } else {
836                 vec![INVALID]
837             };
838 
839             ctrl_types.into_iter().flat_map(move |ctrl_type| {
840                 let rets = Vec::from_iter(
841                     (0..constraints.num_fixed_results())
842                         .map(|i| constraints.result_type(i, ctrl_type)),
843                 );
844 
845                 // Cols is a vector whose length will match `num_fixed_value_arguments`, and whose
846                 // elements will be vectors of types that are valid for that fixed argument
847                 // position.
848                 let mut cols = vec![];
849 
850                 for i in 0..constraints.num_fixed_value_arguments() {
851                     match constraints.value_argument_constraint(i, ctrl_type) {
852                         ResolvedConstraint::Bound(ty) => cols.push(Vec::from([ty])),
853                         ResolvedConstraint::Free(tys) => cols.push(Vec::from_iter(
854                             types.iter().copied().filter(|ty| tys.contains(*ty)),
855                         )),
856                     }
857                 }
858 
859                 // Generate the cartesian product of cols to produce a vector of argument lists,
860                 // argss. The argss vector is seeded with the empty argument list, so there's an
861                 // initial value to be extended in the loop below.
862                 let mut argss = vec![vec![]];
863                 let mut cols = cols.as_slice();
864                 while let Some((col, rest)) = cols.split_last() {
865                     cols = rest;
866 
867                     let mut next = vec![];
868                     for current in argss.iter() {
869                         // Extend the front of each argument candidate with every type in `col`.
870                         for ty in col {
871                             let mut args = vec![*ty];
872                             args.extend_from_slice(&current);
873                             next.push(args);
874                         }
875                     }
876 
877                     let _ = std::mem::replace(&mut argss, next);
878                 }
879 
880                 argss.into_iter().map(move |args| (*op, args, rets.clone()))
881             })
882         })
883         .filter(|(op, args, rets)| {
884             // These op/signature combinations need to be vetted
885             exceptions!(
886                 op,
887                 args.as_slice(),
888                 rets.as_slice(),
889                 (Opcode::Debugtrap),
890                 (Opcode::Trap),
891                 (Opcode::Trapz),
892                 (Opcode::Trapnz),
893                 (Opcode::CallIndirect, &[I32]),
894                 (Opcode::FuncAddr),
895                 (Opcode::X86Pshufb),
896                 (Opcode::AvgRound),
897                 (Opcode::Uload8x8),
898                 (Opcode::Sload8x8),
899                 (Opcode::Uload16x4),
900                 (Opcode::Sload16x4),
901                 (Opcode::Uload32x2),
902                 (Opcode::Sload32x2),
903                 (Opcode::StackAddr),
904                 (Opcode::DynamicStackLoad),
905                 (Opcode::DynamicStackStore),
906                 (Opcode::DynamicStackAddr),
907                 (Opcode::GlobalValue),
908                 (Opcode::SymbolValue),
909                 (Opcode::TlsValue),
910                 (Opcode::GetPinnedReg),
911                 (Opcode::SetPinnedReg),
912                 (Opcode::GetFramePointer),
913                 (Opcode::GetStackPointer),
914                 (Opcode::GetReturnAddress),
915                 (Opcode::X86Blendv),
916                 (Opcode::IcmpImm),
917                 (Opcode::X86Pmulhrsw),
918                 (Opcode::IaddImm),
919                 (Opcode::ImulImm),
920                 (Opcode::UdivImm),
921                 (Opcode::SdivImm),
922                 (Opcode::UremImm),
923                 (Opcode::SremImm),
924                 (Opcode::IrsubImm),
925                 (Opcode::UaddOverflowCin),
926                 (Opcode::SaddOverflowCin),
927                 (Opcode::UaddOverflowTrap),
928                 (Opcode::UsubOverflowBin),
929                 (Opcode::SsubOverflowBin),
930                 (Opcode::BandImm),
931                 (Opcode::BorImm),
932                 (Opcode::BxorImm),
933                 (Opcode::RotlImm),
934                 (Opcode::RotrImm),
935                 (Opcode::IshlImm),
936                 (Opcode::UshrImm),
937                 (Opcode::SshrImm),
938                 (Opcode::ScalarToVector),
939                 (Opcode::X86Pmaddubsw),
940                 (Opcode::X86Cvtt2dq),
941                 (Opcode::Umulhi, &[I128, I128], &[I128]),
942                 (Opcode::Smulhi, &[I128, I128], &[I128]),
943                 // https://github.com/bytecodealliance/wasmtime/issues/6073
944                 (Opcode::Iconcat, &[I32, I32], &[I64]),
945                 (Opcode::Iconcat, &[I16, I16], &[I32]),
946                 (Opcode::Iconcat, &[I8, I8], &[I16]),
947                 // https://github.com/bytecodealliance/wasmtime/issues/6073
948                 (Opcode::Isplit, &[I64], &[I32, I32]),
949                 (Opcode::Isplit, &[I32], &[I16, I16]),
950                 (Opcode::Isplit, &[I16], &[I8, I8]),
951                 (Opcode::Fmin, &[F32X4, F32X4], &[F32X4]),
952                 (Opcode::Fmin, &[F64X2, F64X2], &[F64X2]),
953                 (Opcode::Fmax, &[F32X4, F32X4], &[F32X4]),
954                 (Opcode::Fmax, &[F64X2, F64X2], &[F64X2]),
955                 (Opcode::FcvtToUintSat, &[F32X4], &[I8]),
956                 (Opcode::FcvtToUintSat, &[F64X2], &[I8]),
957                 (Opcode::FcvtToUintSat, &[F32X4], &[I16]),
958                 (Opcode::FcvtToUintSat, &[F64X2], &[I16]),
959                 (Opcode::FcvtToUintSat, &[F32X4], &[I32]),
960                 (Opcode::FcvtToUintSat, &[F64X2], &[I32]),
961                 (Opcode::FcvtToUintSat, &[F32X4], &[I64]),
962                 (Opcode::FcvtToUintSat, &[F64X2], &[I64]),
963                 (Opcode::FcvtToUintSat, &[F32X4], &[I128]),
964                 (Opcode::FcvtToUintSat, &[F64X2], &[I128]),
965                 (Opcode::FcvtToUintSat, &[F32], &[I8X16]),
966                 (Opcode::FcvtToUintSat, &[F64], &[I8X16]),
967                 (Opcode::FcvtToUintSat, &[F32X4], &[I8X16]),
968                 (Opcode::FcvtToUintSat, &[F64X2], &[I8X16]),
969                 (Opcode::FcvtToUintSat, &[F32], &[I16X8]),
970                 (Opcode::FcvtToUintSat, &[F64], &[I16X8]),
971                 (Opcode::FcvtToUintSat, &[F32X4], &[I16X8]),
972                 (Opcode::FcvtToUintSat, &[F64X2], &[I16X8]),
973                 (Opcode::FcvtToUintSat, &[F32], &[I32X4]),
974                 (Opcode::FcvtToUintSat, &[F64], &[I32X4]),
975                 (Opcode::FcvtToUintSat, &[F64X2], &[I32X4]),
976                 (Opcode::FcvtToUintSat, &[F32], &[I64X2]),
977                 (Opcode::FcvtToUintSat, &[F64], &[I64X2]),
978                 (Opcode::FcvtToUintSat, &[F32X4], &[I64X2]),
979                 (Opcode::FcvtToSintSat, &[F32X4], &[I8]),
980                 (Opcode::FcvtToSintSat, &[F64X2], &[I8]),
981                 (Opcode::FcvtToSintSat, &[F32X4], &[I16]),
982                 (Opcode::FcvtToSintSat, &[F64X2], &[I16]),
983                 (Opcode::FcvtToSintSat, &[F32X4], &[I32]),
984                 (Opcode::FcvtToSintSat, &[F64X2], &[I32]),
985                 (Opcode::FcvtToSintSat, &[F32X4], &[I64]),
986                 (Opcode::FcvtToSintSat, &[F64X2], &[I64]),
987                 (Opcode::FcvtToSintSat, &[F32X4], &[I128]),
988                 (Opcode::FcvtToSintSat, &[F64X2], &[I128]),
989                 (Opcode::FcvtToSintSat, &[F32], &[I8X16]),
990                 (Opcode::FcvtToSintSat, &[F64], &[I8X16]),
991                 (Opcode::FcvtToSintSat, &[F32X4], &[I8X16]),
992                 (Opcode::FcvtToSintSat, &[F64X2], &[I8X16]),
993                 (Opcode::FcvtToSintSat, &[F32], &[I16X8]),
994                 (Opcode::FcvtToSintSat, &[F64], &[I16X8]),
995                 (Opcode::FcvtToSintSat, &[F32X4], &[I16X8]),
996                 (Opcode::FcvtToSintSat, &[F64X2], &[I16X8]),
997                 (Opcode::FcvtToSintSat, &[F32], &[I32X4]),
998                 (Opcode::FcvtToSintSat, &[F64], &[I32X4]),
999                 (Opcode::FcvtToSintSat, &[F64X2], &[I32X4]),
1000                 (Opcode::FcvtToSintSat, &[F32], &[I64X2]),
1001                 (Opcode::FcvtToSintSat, &[F64], &[I64X2]),
1002                 (Opcode::FcvtToSintSat, &[F32X4], &[I64X2]),
1003                 (Opcode::FcvtFromUint, &[I8X16], &[F32]),
1004                 (Opcode::FcvtFromUint, &[I16X8], &[F32]),
1005                 (Opcode::FcvtFromUint, &[I32X4], &[F32]),
1006                 (Opcode::FcvtFromUint, &[I64X2], &[F32]),
1007                 (Opcode::FcvtFromUint, &[I8X16], &[F64]),
1008                 (Opcode::FcvtFromUint, &[I16X8], &[F64]),
1009                 (Opcode::FcvtFromUint, &[I32X4], &[F64]),
1010                 (Opcode::FcvtFromUint, &[I64X2], &[F64]),
1011                 (Opcode::FcvtFromUint, &[I8], &[F32X4]),
1012                 (Opcode::FcvtFromUint, &[I16], &[F32X4]),
1013                 (Opcode::FcvtFromUint, &[I32], &[F32X4]),
1014                 (Opcode::FcvtFromUint, &[I64], &[F32X4]),
1015                 (Opcode::FcvtFromUint, &[I128], &[F32X4]),
1016                 (Opcode::FcvtFromUint, &[I8X16], &[F32X4]),
1017                 (Opcode::FcvtFromUint, &[I16X8], &[F32X4]),
1018                 (Opcode::FcvtFromUint, &[I64X2], &[F32X4]),
1019                 (Opcode::FcvtFromUint, &[I8], &[F64X2]),
1020                 (Opcode::FcvtFromUint, &[I16], &[F64X2]),
1021                 (Opcode::FcvtFromUint, &[I32], &[F64X2]),
1022                 (Opcode::FcvtFromUint, &[I64], &[F64X2]),
1023                 (Opcode::FcvtFromUint, &[I128], &[F64X2]),
1024                 (Opcode::FcvtFromUint, &[I8X16], &[F64X2]),
1025                 (Opcode::FcvtFromUint, &[I16X8], &[F64X2]),
1026                 (Opcode::FcvtFromUint, &[I32X4], &[F64X2]),
1027                 (Opcode::FcvtFromSint, &[I8X16], &[F32]),
1028                 (Opcode::FcvtFromSint, &[I16X8], &[F32]),
1029                 (Opcode::FcvtFromSint, &[I32X4], &[F32]),
1030                 (Opcode::FcvtFromSint, &[I64X2], &[F32]),
1031                 (Opcode::FcvtFromSint, &[I8X16], &[F64]),
1032                 (Opcode::FcvtFromSint, &[I16X8], &[F64]),
1033                 (Opcode::FcvtFromSint, &[I32X4], &[F64]),
1034                 (Opcode::FcvtFromSint, &[I64X2], &[F64]),
1035                 (Opcode::FcvtFromSint, &[I8], &[F32X4]),
1036                 (Opcode::FcvtFromSint, &[I16], &[F32X4]),
1037                 (Opcode::FcvtFromSint, &[I32], &[F32X4]),
1038                 (Opcode::FcvtFromSint, &[I64], &[F32X4]),
1039                 (Opcode::FcvtFromSint, &[I128], &[F32X4]),
1040                 (Opcode::FcvtFromSint, &[I8X16], &[F32X4]),
1041                 (Opcode::FcvtFromSint, &[I16X8], &[F32X4]),
1042                 (Opcode::FcvtFromSint, &[I64X2], &[F32X4]),
1043                 (Opcode::FcvtFromSint, &[I8], &[F64X2]),
1044                 (Opcode::FcvtFromSint, &[I16], &[F64X2]),
1045                 (Opcode::FcvtFromSint, &[I32], &[F64X2]),
1046                 (Opcode::FcvtFromSint, &[I64], &[F64X2]),
1047                 (Opcode::FcvtFromSint, &[I128], &[F64X2]),
1048                 (Opcode::FcvtFromSint, &[I8X16], &[F64X2]),
1049                 (Opcode::FcvtFromSint, &[I16X8], &[F64X2]),
1050                 (Opcode::FcvtFromSint, &[I32X4], &[F64X2]),
1051                 // Only supported on x64 with a feature at this time, so 128-bit
1052                 // atomics are not suitable to fuzz yet.
1053                 (Opcode::AtomicRmw, _, &[I128]),
1054                 (Opcode::AtomicCas, _, &[I128]),
1055                 (Opcode::AtomicLoad, _, &[I128]),
1056                 (Opcode::AtomicStore, &[I128, _], _),
1057                 (Opcode::SequencePoint),
1058             )
1059         })
1060         .filter(|(op, ..)| {
1061             allowed_opcodes
1062                 .as_ref()
1063                 .map_or(true, |opcodes| opcodes.contains(op))
1064         })
1065         .collect()
1066 });
1067 
1068 fn inserter_for_format(fmt: InstructionFormat) -> OpcodeInserter {
1069     match fmt {
1070         InstructionFormat::AtomicCas => insert_atomic_cas,
1071         InstructionFormat::AtomicRmw => insert_atomic_rmw,
1072         InstructionFormat::Binary => insert_opcode,
1073         InstructionFormat::BinaryImm64 => todo!(),
1074         InstructionFormat::BinaryImm8 => insert_ins_ext_lane,
1075         InstructionFormat::Call => insert_call,
1076         InstructionFormat::CallIndirect => insert_call,
1077         InstructionFormat::CondTrap => todo!(),
1078         InstructionFormat::DynamicStackLoad => todo!(),
1079         InstructionFormat::DynamicStackStore => todo!(),
1080         InstructionFormat::FloatCompare => insert_cmp,
1081         InstructionFormat::FuncAddr => todo!(),
1082         InstructionFormat::IntAddTrap => todo!(),
1083         InstructionFormat::IntCompare => insert_cmp,
1084         InstructionFormat::IntCompareImm => todo!(),
1085         InstructionFormat::Load => insert_load_store,
1086         InstructionFormat::LoadNoOffset => insert_load_store,
1087         InstructionFormat::NullAry => insert_opcode,
1088         InstructionFormat::Shuffle => insert_shuffle,
1089         InstructionFormat::StackLoad => insert_stack_load,
1090         InstructionFormat::StackStore => insert_stack_store,
1091         InstructionFormat::Store => insert_load_store,
1092         InstructionFormat::StoreNoOffset => insert_load_store,
1093         InstructionFormat::Ternary => insert_opcode,
1094         InstructionFormat::TernaryImm8 => insert_ins_ext_lane,
1095         InstructionFormat::Trap => todo!(),
1096         InstructionFormat::Unary => insert_opcode,
1097         InstructionFormat::UnaryConst => insert_const,
1098         InstructionFormat::UnaryGlobalValue => todo!(),
1099         InstructionFormat::UnaryIeee16 => insert_const,
1100         InstructionFormat::UnaryIeee32 => insert_const,
1101         InstructionFormat::UnaryIeee64 => insert_const,
1102         InstructionFormat::UnaryImm => insert_const,
1103         InstructionFormat::ExceptionHandlerAddress => insert_const,
1104 
1105         InstructionFormat::BranchTable
1106         | InstructionFormat::Brif
1107         | InstructionFormat::Jump
1108         | InstructionFormat::MultiAry
1109         | InstructionFormat::TryCall
1110         | InstructionFormat::TryCallIndirect => {
1111             panic!("Control-flow instructions should be handled by 'insert_terminator': {fmt:?}")
1112         }
1113     }
1114 }
1115 
1116 pub struct FunctionGenerator<'r, 'data>
1117 where
1118     'data: 'r,
1119 {
1120     u: &'r mut Unstructured<'data>,
1121     config: &'r Config,
1122     resources: Resources,
1123     isa: OwnedTargetIsa,
1124     name: UserFuncName,
1125     signature: Signature,
1126 }
1127 
1128 #[derive(Debug, Clone)]
1129 enum BlockTerminator {
1130     Return,
1131     Jump(Block),
1132     Br(Block, Block),
1133     BrTable(Block, Vec<Block>),
1134     Switch(Type, Block, HashMap<u128, Block>),
1135     TailCall(FuncRef),
1136     TailCallIndirect(FuncRef),
1137 }
1138 
1139 #[derive(Debug, Clone)]
1140 enum BlockTerminatorKind {
1141     Return,
1142     Jump,
1143     Br,
1144     BrTable,
1145     Switch,
1146     TailCall,
1147     TailCallIndirect,
1148 }
1149 
1150 /// Alias Analysis Category
1151 ///
1152 /// Our alias analysis pass supports 4 categories of accesses to distinguish
1153 /// different regions. The "Other" region is the general case, and is the default
1154 /// Although they have highly suggestive names there is no difference between any
1155 /// of the categories.
1156 ///
1157 /// We assign each stack slot a category when we first generate them, and then
1158 /// ensure that all accesses to that stack slot are correctly tagged. We already
1159 /// ensure that memory accesses never cross stack slots, so there is no risk
1160 /// of a memory access being tagged with the wrong category.
1161 #[derive(Debug, PartialEq, Clone, Copy)]
1162 enum AACategory {
1163     Other,
1164     Heap,
1165     Table,
1166     VmCtx,
1167 }
1168 
1169 impl AACategory {
1170     pub fn all() -> &'static [Self] {
1171         &[
1172             AACategory::Other,
1173             AACategory::Heap,
1174             AACategory::Table,
1175             AACategory::VmCtx,
1176         ]
1177     }
1178 
1179     pub fn update_memflags(&self, flags: &mut MemFlags) {
1180         flags.set_alias_region(match self {
1181             AACategory::Other => None,
1182             AACategory::Heap => Some(AliasRegion::Heap),
1183             AACategory::Table => Some(AliasRegion::Table),
1184             AACategory::VmCtx => Some(AliasRegion::Vmctx),
1185         })
1186     }
1187 }
1188 
1189 pub type StackAlignment = StackSize;
1190 
1191 #[derive(Default)]
1192 struct Resources {
1193     vars: HashMap<Type, Vec<Variable>>,
1194     blocks: Vec<(Block, BlockSignature)>,
1195     blocks_without_params: Vec<Block>,
1196     block_terminators: Vec<BlockTerminator>,
1197     func_refs: Vec<(Signature, SigRef, FuncRef)>,
1198     /// This field is required to be sorted by stack slot size at all times.
1199     /// We use this invariant when searching for stack slots with a given size.
1200     /// See [FunctionGenerator::stack_slot_with_size]
1201     stack_slots: Vec<(StackSlot, StackSize, StackAlignment, AACategory)>,
1202     usercalls: Vec<(UserExternalName, Signature)>,
1203     libcalls: Vec<LibCall>,
1204 }
1205 
1206 impl Resources {
1207     /// Partitions blocks at `block`. Only blocks that can be targeted by branches are considered.
1208     ///
1209     /// The first slice includes all blocks up to and including `block`.
1210     /// The second slice includes all remaining blocks.
1211     fn partition_target_blocks(
1212         &self,
1213         block: Block,
1214     ) -> (&[(Block, BlockSignature)], &[(Block, BlockSignature)]) {
1215         // Blocks are stored in-order and have no gaps, this means that we can simply index them by
1216         // their number. We also need to exclude the entry block since it isn't a valid target.
1217         let target_blocks = &self.blocks[1..];
1218         target_blocks.split_at(block.as_u32() as usize)
1219     }
1220 
1221     /// Returns blocks forward of `block`. Only blocks that can be targeted by branches are considered.
1222     fn forward_blocks(&self, block: Block) -> &[(Block, BlockSignature)] {
1223         let (_, forward_blocks) = self.partition_target_blocks(block);
1224         forward_blocks
1225     }
1226 
1227     /// Generates a slice of `blocks_without_params` ahead of `block`
1228     fn forward_blocks_without_params(&self, block: Block) -> &[Block] {
1229         let partition_point = self.blocks_without_params.partition_point(|b| *b <= block);
1230         &self.blocks_without_params[partition_point..]
1231     }
1232 
1233     /// Generates an iterator of all valid tail call targets. This includes all functions with both
1234     ///  the `tail` calling convention and the same return values as the caller.
1235     fn tail_call_targets<'a>(
1236         &'a self,
1237         caller_sig: &'a Signature,
1238     ) -> impl Iterator<Item = &'a (Signature, SigRef, FuncRef)> {
1239         self.func_refs.iter().filter(|(sig, _, _)| {
1240             sig.call_conv == CallConv::Tail && sig.returns == caller_sig.returns
1241         })
1242     }
1243 }
1244 
1245 impl<'r, 'data> FunctionGenerator<'r, 'data>
1246 where
1247     'data: 'r,
1248 {
1249     pub fn new(
1250         u: &'r mut Unstructured<'data>,
1251         config: &'r Config,
1252         isa: OwnedTargetIsa,
1253         name: UserFuncName,
1254         signature: Signature,
1255         usercalls: Vec<(UserExternalName, Signature)>,
1256         libcalls: Vec<LibCall>,
1257     ) -> Self {
1258         Self {
1259             u,
1260             config,
1261             resources: Resources {
1262                 usercalls,
1263                 libcalls,
1264                 ..Resources::default()
1265             },
1266             isa,
1267             name,
1268             signature,
1269         }
1270     }
1271 
1272     /// Generates a random value for config `param`
1273     fn param(&mut self, param: &RangeInclusive<usize>) -> Result<usize> {
1274         Ok(self.u.int_in_range(param.clone())?)
1275     }
1276 
1277     fn system_callconv(&mut self) -> CallConv {
1278         // TODO: This currently only runs on linux, so this is the only choice
1279         // We should improve this once we generate flags and targets
1280         CallConv::SystemV
1281     }
1282 
1283     /// Finds a stack slot with size of at least n bytes
1284     fn stack_slot_with_size(
1285         &mut self,
1286         n: u32,
1287     ) -> Result<(StackSlot, StackSize, StackAlignment, AACategory)> {
1288         let first = self
1289             .resources
1290             .stack_slots
1291             .partition_point(|&(_slot, size, _align, _category)| size < n);
1292         Ok(*self.u.choose(&self.resources.stack_slots[first..])?)
1293     }
1294 
1295     /// Generates an address that should allow for a store or a load.
1296     ///
1297     /// Addresses aren't generated like other values. They are never stored in variables so that
1298     /// we don't run the risk of returning them from a function, which would make the fuzzer
1299     /// complain since they are different from the interpreter to the backend.
1300     ///
1301     /// `min_size`: Controls the amount of space that the address should have.
1302     ///
1303     /// `aligned`: When passed as true, the resulting address is guaranteed to be aligned
1304     /// on an 8 byte boundary.
1305     ///
1306     /// Returns a valid address and the maximum possible offset that still respects `min_size`.
1307     fn generate_load_store_address(
1308         &mut self,
1309         builder: &mut FunctionBuilder,
1310         min_size: u32,
1311         aligned: bool,
1312     ) -> Result<(Value, u32, AACategory)> {
1313         // TODO: Currently our only source of addresses is stack_addr, but we
1314         // should add global_value, symbol_value eventually
1315         let (addr, available_size, category) = {
1316             let (ss, slot_size, _align, category) = self.stack_slot_with_size(min_size)?;
1317 
1318             // stack_slot_with_size guarantees that slot_size >= min_size
1319             let max_offset = slot_size - min_size;
1320             let offset = if aligned {
1321                 self.u.int_in_range(0..=max_offset / min_size)? * min_size
1322             } else {
1323                 self.u.int_in_range(0..=max_offset)?
1324             };
1325 
1326             let base_addr = builder.ins().stack_addr(I64, ss, offset as i32);
1327             let available_size = slot_size.saturating_sub(offset);
1328             (base_addr, available_size, category)
1329         };
1330 
1331         // TODO: Insert a bunch of amode opcodes here to modify the address!
1332 
1333         // Now that we have an address and a size, we just choose a random offset to return to the
1334         // caller. Preserving min_size bytes.
1335         let max_offset = available_size.saturating_sub(min_size);
1336         Ok((addr, max_offset, category))
1337     }
1338 
1339     // Generates an address and memflags for a load or store.
1340     fn generate_address_and_memflags(
1341         &mut self,
1342         builder: &mut FunctionBuilder,
1343         min_size: u32,
1344         is_atomic: bool,
1345     ) -> Result<(Value, MemFlags, Offset32)> {
1346         // Should we generate an aligned address
1347         // Some backends have issues with unaligned atomics.
1348         // AArch64: https://github.com/bytecodealliance/wasmtime/issues/5483
1349         // RISCV: https://github.com/bytecodealliance/wasmtime/issues/5882
1350         let requires_aligned_atomics = matches!(
1351             self.isa.triple().architecture,
1352             Architecture::Aarch64(_) | Architecture::Riscv64(_)
1353         );
1354         let aligned = if is_atomic && requires_aligned_atomics {
1355             true
1356         } else if min_size > 8 {
1357             // TODO: We currently can't guarantee that a stack_slot will be aligned on a 16 byte
1358             // boundary. We don't have a way to specify alignment when creating stack slots, and
1359             // cranelift only guarantees 8 byte alignment between stack slots.
1360             // See: https://github.com/bytecodealliance/wasmtime/issues/5922#issuecomment-1457926624
1361             false
1362         } else {
1363             bool::arbitrary(self.u)?
1364         };
1365 
1366         let mut flags = MemFlags::new();
1367         // Even if we picked an aligned address, we can always generate unaligned memflags
1368         if aligned && bool::arbitrary(self.u)? {
1369             flags.set_aligned();
1370         }
1371         // If the address is aligned, then we know it won't trap
1372         if aligned && bool::arbitrary(self.u)? {
1373             flags.set_notrap();
1374         }
1375 
1376         let (address, max_offset, category) =
1377             self.generate_load_store_address(builder, min_size, aligned)?;
1378 
1379         // Set the Alias Analysis bits on the memflags
1380         category.update_memflags(&mut flags);
1381 
1382         // Pick an offset to pass into the load/store.
1383         let offset = if aligned {
1384             0
1385         } else {
1386             self.u.int_in_range(0..=max_offset)? as i32
1387         }
1388         .into();
1389 
1390         Ok((address, flags, offset))
1391     }
1392 
1393     /// Get a variable of type `ty` from the current function
1394     fn get_variable_of_type(&mut self, ty: Type) -> Result<Variable> {
1395         let opts = self.resources.vars.get(&ty).map_or(&[][..], Vec::as_slice);
1396         let var = self.u.choose(opts)?;
1397         Ok(*var)
1398     }
1399 
1400     /// Generates an instruction(`iconst`/`fconst`/etc...) to introduce a constant value
1401     fn generate_const(&mut self, builder: &mut FunctionBuilder, ty: Type) -> Result<Value> {
1402         Ok(match self.u.datavalue(ty)? {
1403             DataValue::I8(i) => builder.ins().iconst(ty, i as u8 as i64),
1404             DataValue::I16(i) => builder.ins().iconst(ty, i as u16 as i64),
1405             DataValue::I32(i) => builder.ins().iconst(ty, i as u32 as i64),
1406             DataValue::I64(i) => builder.ins().iconst(ty, i),
1407             DataValue::I128(i) => {
1408                 let hi = builder.ins().iconst(I64, (i >> 64) as i64);
1409                 let lo = builder.ins().iconst(I64, i as i64);
1410                 builder.ins().iconcat(lo, hi)
1411             }
1412             DataValue::F16(f) => builder.ins().f16const(f),
1413             DataValue::F32(f) => builder.ins().f32const(f),
1414             DataValue::F64(f) => builder.ins().f64const(f),
1415             DataValue::F128(f) => {
1416                 let handle = builder.func.dfg.constants.insert(f.into());
1417                 builder.ins().f128const(handle)
1418             }
1419             DataValue::V128(bytes) => {
1420                 let data = bytes.to_vec().into();
1421                 let handle = builder.func.dfg.constants.insert(data);
1422                 builder.ins().vconst(ty, handle)
1423             }
1424             _ => unimplemented!(),
1425         })
1426     }
1427 
1428     /// Chooses a random block which can be targeted by a jump / branch.
1429     /// This means any block that is not the first block.
1430     fn generate_target_block(&mut self, source_block: Block) -> Result<Block> {
1431         // We try to mostly generate forward branches to avoid generating an excessive amount of
1432         // infinite loops. But they are still important, so give them a small chance of existing.
1433         let (backwards_blocks, forward_blocks) =
1434             self.resources.partition_target_blocks(source_block);
1435         let ratio = self.config.backwards_branch_ratio;
1436         let block_targets = if !backwards_blocks.is_empty() && self.u.ratio(ratio.0, ratio.1)? {
1437             backwards_blocks
1438         } else {
1439             forward_blocks
1440         };
1441         assert!(!block_targets.is_empty());
1442 
1443         let (block, _) = self.u.choose(block_targets)?.clone();
1444         Ok(block)
1445     }
1446 
1447     fn generate_values_for_block(
1448         &mut self,
1449         builder: &mut FunctionBuilder,
1450         block: Block,
1451     ) -> Result<Vec<BlockArg>> {
1452         let (_, sig) = self.resources.blocks[block.as_u32() as usize].clone();
1453         Ok(self
1454             .generate_values_for_signature(builder, sig.iter().copied())?
1455             .into_iter()
1456             .map(|val| BlockArg::Value(val))
1457             .collect::<Vec<_>>())
1458     }
1459 
1460     fn generate_values_for_signature<I: Iterator<Item = Type>>(
1461         &mut self,
1462         builder: &mut FunctionBuilder,
1463         signature: I,
1464     ) -> Result<Vec<Value>> {
1465         signature
1466             .map(|ty| {
1467                 let var = self.get_variable_of_type(ty)?;
1468                 let val = builder.use_var(var);
1469                 Ok(val)
1470             })
1471             .collect()
1472     }
1473 
1474     /// The terminator that we need to insert has already been picked ahead of time
1475     /// we just need to build the instructions for it
1476     fn insert_terminator(
1477         &mut self,
1478         builder: &mut FunctionBuilder,
1479         source_block: Block,
1480     ) -> Result<()> {
1481         let terminator = self.resources.block_terminators[source_block.as_u32() as usize].clone();
1482 
1483         match terminator {
1484             BlockTerminator::Return => {
1485                 let types: Vec<Type> = {
1486                     let rets = &builder.func.signature.returns;
1487                     rets.iter().map(|p| p.value_type).collect()
1488                 };
1489                 let vals = self.generate_values_for_signature(builder, types.into_iter())?;
1490 
1491                 builder.ins().return_(&vals[..]);
1492             }
1493             BlockTerminator::Jump(target) => {
1494                 let args = self.generate_values_for_block(builder, target)?;
1495                 builder.ins().jump(target, &args[..]);
1496             }
1497             BlockTerminator::Br(left, right) => {
1498                 let left_args = self.generate_values_for_block(builder, left)?;
1499                 let right_args = self.generate_values_for_block(builder, right)?;
1500 
1501                 let condbr_types = [I8, I16, I32, I64, I128];
1502                 let _type = *self.u.choose(&condbr_types[..])?;
1503                 let val = builder.use_var(self.get_variable_of_type(_type)?);
1504                 builder
1505                     .ins()
1506                     .brif(val, left, &left_args[..], right, &right_args[..]);
1507             }
1508             BlockTerminator::BrTable(default, targets) => {
1509                 // Create jump tables on demand
1510                 let mut jt = Vec::with_capacity(targets.len());
1511                 for block in targets {
1512                     let args = self.generate_values_for_block(builder, block)?;
1513                     jt.push(builder.func.dfg.block_call(block, &args))
1514                 }
1515 
1516                 let args = self.generate_values_for_block(builder, default)?;
1517                 let jt_data = JumpTableData::new(builder.func.dfg.block_call(default, &args), &jt);
1518                 let jt = builder.create_jump_table(jt_data);
1519 
1520                 // br_table only supports I32
1521                 let val = builder.use_var(self.get_variable_of_type(I32)?);
1522 
1523                 builder.ins().br_table(val, jt);
1524             }
1525             BlockTerminator::Switch(_type, default, entries) => {
1526                 let mut switch = Switch::new();
1527                 for (&entry, &block) in entries.iter() {
1528                     switch.set_entry(entry, block);
1529                 }
1530 
1531                 let switch_val = builder.use_var(self.get_variable_of_type(_type)?);
1532 
1533                 switch.emit(builder, switch_val, default);
1534             }
1535             BlockTerminator::TailCall(target) | BlockTerminator::TailCallIndirect(target) => {
1536                 let (sig, sig_ref, func_ref) = self
1537                     .resources
1538                     .func_refs
1539                     .iter()
1540                     .find(|(_, _, f)| *f == target)
1541                     .expect("Failed to find previously selected function")
1542                     .clone();
1543 
1544                 let opcode = match terminator {
1545                     BlockTerminator::TailCall(_) => Opcode::ReturnCall,
1546                     BlockTerminator::TailCallIndirect(_) => Opcode::ReturnCallIndirect,
1547                     _ => unreachable!(),
1548                 };
1549 
1550                 insert_call_to_function(self, builder, opcode, &sig, sig_ref, func_ref)?;
1551             }
1552         }
1553 
1554         Ok(())
1555     }
1556 
1557     /// Fills the current block with random instructions
1558     fn generate_instructions(&mut self, builder: &mut FunctionBuilder) -> Result<()> {
1559         for _ in 0..self.param(&self.config.instructions_per_block)? {
1560             let (op, args, rets) = self.u.choose(&OPCODE_SIGNATURES)?;
1561 
1562             // We filter out instructions that aren't supported by the target at this point instead
1563             // of building a single vector of valid instructions at the beginning of function
1564             // generation, to avoid invalidating the corpus when instructions are enabled/disabled.
1565             if !valid_for_target(&self.isa.triple(), *op, &args, &rets) {
1566                 return Err(arbitrary::Error::IncorrectFormat.into());
1567             }
1568 
1569             let inserter = inserter_for_format(op.format());
1570             inserter(self, builder, *op, &args, &rets)?;
1571         }
1572 
1573         Ok(())
1574     }
1575 
1576     fn generate_funcrefs(&mut self, builder: &mut FunctionBuilder) -> Result<()> {
1577         let usercalls: Vec<_> = self
1578             .resources
1579             .usercalls
1580             .iter()
1581             .map(|(name, signature)| {
1582                 let user_func_ref = builder.func.declare_imported_user_function(name.clone());
1583                 let name = ExternalName::User(user_func_ref);
1584                 (name, signature.clone())
1585             })
1586             .collect();
1587 
1588         let lib_callconv = self.system_callconv();
1589         let libcalls: Vec<_> = self
1590             .resources
1591             .libcalls
1592             .iter()
1593             .map(|libcall| {
1594                 let pointer_type = Type::int_with_byte_size(
1595                     self.isa.triple().pointer_width().unwrap().bytes().into(),
1596                 )
1597                 .unwrap();
1598                 let signature = libcall.signature(lib_callconv, pointer_type);
1599                 let name = ExternalName::LibCall(*libcall);
1600                 (name, signature)
1601             })
1602             .collect();
1603 
1604         for (name, signature) in usercalls.into_iter().chain(libcalls) {
1605             let sig_ref = builder.import_signature(signature.clone());
1606             let func_ref = builder.import_function(ExtFuncData {
1607                 name,
1608                 signature: sig_ref,
1609 
1610                 // Libcalls can't be colocated because they can be very far away
1611                 // from allocated memory at runtime, and additionally at this
1612                 // time cranelift-jit puts all functions in their own mmap so
1613                 // they also cannot be colocated.
1614                 colocated: false,
1615                 patchable: false,
1616             });
1617 
1618             self.resources
1619                 .func_refs
1620                 .push((signature, sig_ref, func_ref));
1621         }
1622 
1623         Ok(())
1624     }
1625 
1626     fn generate_stack_slots(&mut self, builder: &mut FunctionBuilder) -> Result<()> {
1627         for _ in 0..self.param(&self.config.static_stack_slots_per_function)? {
1628             let bytes = self.param(&self.config.static_stack_slot_size)? as u32;
1629             let alignment = self.param(&self.config.stack_slot_alignment_log2)? as u8;
1630             let alignment_bytes = 1 << alignment;
1631 
1632             let ss_data = StackSlotData::new(StackSlotKind::ExplicitSlot, bytes, alignment);
1633             let slot = builder.create_sized_stack_slot(ss_data);
1634 
1635             // Generate one Alias Analysis Category for each slot
1636             let category = *self.u.choose(AACategory::all())?;
1637 
1638             self.resources
1639                 .stack_slots
1640                 .push((slot, bytes, alignment_bytes, category));
1641         }
1642 
1643         self.resources
1644             .stack_slots
1645             .sort_unstable_by_key(|&(_slot, bytes, _align, _category)| bytes);
1646 
1647         Ok(())
1648     }
1649 
1650     /// Zero initializes the stack slot by inserting `stack_store`'s.
1651     fn initialize_stack_slots(&mut self, builder: &mut FunctionBuilder) -> Result<()> {
1652         let i8_zero = builder.ins().iconst(I8, 0);
1653         let i16_zero = builder.ins().iconst(I16, 0);
1654         let i32_zero = builder.ins().iconst(I32, 0);
1655         let i64_zero = builder.ins().iconst(I64, 0);
1656         let i128_zero = builder.ins().uextend(I128, i64_zero);
1657 
1658         for &(slot, init_size, _align, category) in self.resources.stack_slots.iter() {
1659             let mut size = init_size;
1660 
1661             // Insert the largest available store for the remaining size.
1662             while size != 0 {
1663                 let offset = (init_size - size) as i32;
1664                 let (val, filled) = match size {
1665                     sz if sz / 16 > 0 => (i128_zero, 16),
1666                     sz if sz / 8 > 0 => (i64_zero, 8),
1667                     sz if sz / 4 > 0 => (i32_zero, 4),
1668                     sz if sz / 2 > 0 => (i16_zero, 2),
1669                     _ => (i8_zero, 1),
1670                 };
1671                 let addr = builder.ins().stack_addr(I64, slot, offset);
1672 
1673                 // Each stack slot has an associated category, that means we have to set the
1674                 // correct memflags for it. So we can't use `stack_store` directly.
1675                 let mut flags = MemFlags::new();
1676                 flags.set_notrap();
1677                 category.update_memflags(&mut flags);
1678 
1679                 builder.ins().store(flags, val, addr, 0);
1680 
1681                 size -= filled;
1682             }
1683         }
1684         Ok(())
1685     }
1686 
1687     /// Creates a random amount of blocks in this function
1688     fn generate_blocks(&mut self, builder: &mut FunctionBuilder) -> Result<()> {
1689         let extra_block_count = self.param(&self.config.blocks_per_function)?;
1690 
1691         // We must always have at least one block, so we generate the "extra" blocks and add 1 for
1692         // the entry block.
1693         let block_count = 1 + extra_block_count;
1694 
1695         // Blocks need to be sorted in ascending order
1696         self.resources.blocks = (0..block_count)
1697             .map(|i| {
1698                 let is_entry = i == 0;
1699                 let block = builder.create_block();
1700 
1701                 // Optionally mark blocks that are not the entry block as cold
1702                 if !is_entry {
1703                     if bool::arbitrary(self.u)? {
1704                         builder.set_cold_block(block);
1705                     }
1706                 }
1707 
1708                 // The first block has to have the function signature, but for the rest of them we generate
1709                 // a random signature;
1710                 if is_entry {
1711                     builder.append_block_params_for_function_params(block);
1712                     Ok((
1713                         block,
1714                         self.signature.params.iter().map(|a| a.value_type).collect(),
1715                     ))
1716                 } else {
1717                     let sig = self.generate_block_signature()?;
1718                     sig.iter().for_each(|ty| {
1719                         builder.append_block_param(block, *ty);
1720                     });
1721                     Ok((block, sig))
1722                 }
1723             })
1724             .collect::<Result<Vec<_>>>()?;
1725 
1726         // Valid blocks for jump tables have to have no parameters in the signature, and must also
1727         // not be the first block.
1728         self.resources.blocks_without_params = self.resources.blocks[1..]
1729             .iter()
1730             .filter(|(_, sig)| sig.len() == 0)
1731             .map(|(b, _)| *b)
1732             .collect();
1733 
1734         // Compute the block CFG
1735         //
1736         // cranelift-frontend requires us to never generate unreachable blocks
1737         // To ensure this property we start by constructing a main "spine" of blocks. So block1 can
1738         // always jump to block2, and block2 can always jump to block3, etc...
1739         //
1740         // That is not a very interesting CFG, so we introduce variations on that, but always
1741         // ensuring that the property of pointing to the next block is maintained whatever the
1742         // branching mechanism we use.
1743         let blocks = self.resources.blocks.clone();
1744         self.resources.block_terminators = blocks
1745             .iter()
1746             .map(|&(block, _)| {
1747                 let next_block = Block::with_number(block.as_u32() + 1).unwrap();
1748                 let forward_blocks = self.resources.forward_blocks(block);
1749                 let paramless_targets = self.resources.forward_blocks_without_params(block);
1750                 let has_paramless_targets = !paramless_targets.is_empty();
1751                 let next_block_is_paramless = paramless_targets.contains(&next_block);
1752 
1753                 let mut valid_terminators = vec![];
1754 
1755                 if forward_blocks.is_empty() {
1756                     // Return is only valid on the last block.
1757                     valid_terminators.push(BlockTerminatorKind::Return);
1758                 } else {
1759                     // If we have more than one block we can allow terminators that target blocks.
1760                     // TODO: We could add some kind of BrReturn here, to explore edges where we
1761                     // exit in the middle of the function
1762                     valid_terminators.extend_from_slice(&[
1763                         BlockTerminatorKind::Jump,
1764                         BlockTerminatorKind::Br,
1765                         BlockTerminatorKind::BrTable,
1766                     ]);
1767                 }
1768 
1769                 // As the Switch interface only allows targeting blocks without params we need
1770                 // to ensure that the next block has no params, since that one is guaranteed to be
1771                 // picked in either case.
1772                 if has_paramless_targets && next_block_is_paramless {
1773                     valid_terminators.push(BlockTerminatorKind::Switch);
1774                 }
1775 
1776                 // Tail Calls are a block terminator, so we should insert them as any other block
1777                 // terminator. We should ensure that we can select at least one target before considering
1778                 // them as candidate instructions.
1779                 let has_tail_callees = self
1780                     .resources
1781                     .tail_call_targets(&self.signature)
1782                     .next()
1783                     .is_some();
1784                 let is_tail_caller = self.signature.call_conv == CallConv::Tail;
1785 
1786                 let supports_tail_calls = match self.isa.triple().architecture {
1787                     Architecture::Aarch64(_) | Architecture::Riscv64(_) => true,
1788                     // TODO: x64 currently requires frame pointers for tail calls.
1789                     Architecture::X86_64 => self.isa.flags().preserve_frame_pointers(),
1790                     // TODO: Other platforms do not support tail calls yet.
1791                     _ => false,
1792                 };
1793 
1794                 if is_tail_caller && has_tail_callees && supports_tail_calls {
1795                     valid_terminators.extend([
1796                         BlockTerminatorKind::TailCall,
1797                         BlockTerminatorKind::TailCallIndirect,
1798                     ]);
1799                 }
1800 
1801                 let terminator = self.u.choose(&valid_terminators)?;
1802 
1803                 // Choose block targets for the terminators that we picked above
1804                 Ok(match terminator {
1805                     BlockTerminatorKind::Return => BlockTerminator::Return,
1806                     BlockTerminatorKind::Jump => BlockTerminator::Jump(next_block),
1807                     BlockTerminatorKind::Br => {
1808                         BlockTerminator::Br(next_block, self.generate_target_block(block)?)
1809                     }
1810                     // TODO: Allow generating backwards branches here
1811                     BlockTerminatorKind::BrTable => {
1812                         // Make the default the next block, and then we don't have to worry
1813                         // that we can reach it via the targets
1814                         let default = next_block;
1815 
1816                         let target_count = self.param(&self.config.jump_table_entries)?;
1817                         let targets = Result::from_iter(
1818                             (0..target_count).map(|_| self.generate_target_block(block)),
1819                         )?;
1820 
1821                         BlockTerminator::BrTable(default, targets)
1822                     }
1823                     BlockTerminatorKind::Switch => {
1824                         // Make the default the next block, and then we don't have to worry
1825                         // that we can reach it via the entries below
1826                         let default_block = next_block;
1827 
1828                         let _type = *self.u.choose(&[I8, I16, I32, I64, I128][..])?;
1829 
1830                         // Build this into a HashMap since we cannot have duplicate entries.
1831                         let mut entries = HashMap::new();
1832                         for _ in 0..self.param(&self.config.switch_cases)? {
1833                             // The Switch API only allows for entries that are addressable by the index type
1834                             // so we need to limit the range of values that we generate.
1835                             let (ty_min, ty_max) = _type.bounds(false);
1836                             let range_start = self.u.int_in_range(ty_min..=ty_max)?;
1837 
1838                             // We can either insert a contiguous range of blocks or a individual block
1839                             // This is done because the Switch API specializes contiguous ranges.
1840                             let range_size = if bool::arbitrary(self.u)? {
1841                                 1
1842                             } else {
1843                                 self.param(&self.config.switch_max_range_size)?
1844                             } as u128;
1845 
1846                             // Build the switch entries
1847                             for i in 0..range_size {
1848                                 let index = range_start.wrapping_add(i) % ty_max;
1849                                 let block = *self
1850                                     .u
1851                                     .choose(self.resources.forward_blocks_without_params(block))?;
1852 
1853                                 entries.insert(index, block);
1854                             }
1855                         }
1856 
1857                         BlockTerminator::Switch(_type, default_block, entries)
1858                     }
1859                     BlockTerminatorKind::TailCall => {
1860                         let targets = self
1861                             .resources
1862                             .tail_call_targets(&self.signature)
1863                             .collect::<Vec<_>>();
1864                         let (_, _, funcref) = *self.u.choose(&targets[..])?;
1865                         BlockTerminator::TailCall(*funcref)
1866                     }
1867                     BlockTerminatorKind::TailCallIndirect => {
1868                         let targets = self
1869                             .resources
1870                             .tail_call_targets(&self.signature)
1871                             .collect::<Vec<_>>();
1872                         let (_, _, funcref) = *self.u.choose(&targets[..])?;
1873                         BlockTerminator::TailCallIndirect(*funcref)
1874                     }
1875                 })
1876             })
1877             .collect::<Result<_>>()?;
1878 
1879         Ok(())
1880     }
1881 
1882     fn generate_block_signature(&mut self) -> Result<BlockSignature> {
1883         let param_count = self.param(&self.config.block_signature_params)?;
1884 
1885         let mut params = Vec::with_capacity(param_count);
1886         for _ in 0..param_count {
1887             params.push(self.u._type((&*self.isa).supports_simd())?);
1888         }
1889         Ok(params)
1890     }
1891 
1892     fn build_variable_pool(&mut self, builder: &mut FunctionBuilder) -> Result<()> {
1893         let block = builder.current_block().unwrap();
1894 
1895         // Define variables for the function signature
1896         let mut vars: Vec<_> = builder
1897             .func
1898             .signature
1899             .params
1900             .iter()
1901             .map(|param| param.value_type)
1902             .zip(builder.block_params(block).iter().copied())
1903             .collect();
1904 
1905         // Create a pool of vars that are going to be used in this function
1906         for _ in 0..self.param(&self.config.vars_per_function)? {
1907             let ty = self.u._type((&*self.isa).supports_simd())?;
1908             let value = self.generate_const(builder, ty)?;
1909             vars.push((ty, value));
1910         }
1911 
1912         for (ty, value) in vars.into_iter() {
1913             let var = builder.declare_var(ty);
1914             builder.def_var(var, value);
1915 
1916             // Randomly declare variables as needing a stack map.
1917             // We limit these to only types that have fewer than 16 bytes
1918             // since the stack map mechanism does not support larger types.
1919             if ty.bytes() <= 16 && self.u.arbitrary()? {
1920                 builder.declare_var_needs_stack_map(var);
1921             }
1922 
1923             self.resources
1924                 .vars
1925                 .entry(ty)
1926                 .or_insert_with(Vec::new)
1927                 .push(var);
1928         }
1929 
1930         Ok(())
1931     }
1932 
1933     /// We generate a function in multiple stages:
1934     ///
1935     /// * First we generate a random number of empty blocks
1936     /// * Then we generate a random pool of variables to be used throughout the function
1937     /// * We then visit each block and generate random instructions
1938     ///
1939     /// Because we generate all blocks and variables up front we already know everything that
1940     /// we need when generating instructions (i.e. jump targets / variables)
1941     pub fn generate(mut self) -> Result<Function> {
1942         let mut fn_builder_ctx = FunctionBuilderContext::new();
1943         let mut func = Function::with_name_signature(self.name.clone(), self.signature.clone());
1944 
1945         let mut builder = FunctionBuilder::new(&mut func, &mut fn_builder_ctx);
1946 
1947         // Build the function references before generating the block CFG since we store
1948         // function references in the CFG.
1949         self.generate_funcrefs(&mut builder)?;
1950         self.generate_blocks(&mut builder)?;
1951 
1952         // Function preamble
1953         self.generate_stack_slots(&mut builder)?;
1954 
1955         // Main instruction generation loop
1956         for (block, block_sig) in self.resources.blocks.clone().into_iter() {
1957             let is_block0 = block.as_u32() == 0;
1958             builder.switch_to_block(block);
1959 
1960             if is_block0 {
1961                 // The first block is special because we must create variables both for the
1962                 // block signature and for the variable pool. Additionally, we must also define
1963                 // initial values for all variables that are not the function signature.
1964                 self.build_variable_pool(&mut builder)?;
1965 
1966                 // Stack slots have random bytes at the beginning of the function
1967                 // initialize them to a constant value so that execution stays predictable.
1968                 self.initialize_stack_slots(&mut builder)?;
1969             } else {
1970                 // Define variables for the block params
1971                 for (i, ty) in block_sig.iter().enumerate() {
1972                     let var = self.get_variable_of_type(*ty)?;
1973                     let block_param = builder.block_params(block)[i];
1974                     builder.def_var(var, block_param);
1975                 }
1976             }
1977 
1978             // Generate block instructions
1979             self.generate_instructions(&mut builder)?;
1980 
1981             // Insert a terminator to safely exit the block
1982             self.insert_terminator(&mut builder, block)?;
1983         }
1984 
1985         builder.seal_all_blocks();
1986         builder.finalize();
1987 
1988         Ok(func)
1989     }
1990 }
1991