-
Notifications
You must be signed in to change notification settings - Fork 287
/
Copy pathargument.rs
279 lines (251 loc) · 8.93 KB
/
argument.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
use super::format::Indentation;
use super::json_parser::ArgPrep;
use super::types::{IntrinsicType, TypeKind};
use crate::common::types::Language;
use serde::Deserialize;
use serde_json::Value;
use std::collections::HashMap;
use std::ops::Range;
/// An argument for the intrinsic.
#[derive(Debug, PartialEq, Clone)]
pub struct Argument {
/// The argument's index in the intrinsic function call.
pub pos: usize,
/// The argument name.
pub name: String,
/// The type of the argument.
pub ty: IntrinsicType,
/// Any constraints that are on this argument
pub constraints: Vec<Constraint>,
}
#[derive(Debug, PartialEq, Clone, Deserialize)]
pub enum Constraint {
Equal(i64),
Range(Range<i64>),
}
/// ARM-specific
impl TryFrom<ArgPrep> for Constraint {
type Error = ();
fn try_from(prep: ArgPrep) -> Result<Self, Self::Error> {
let parsed_ints = match prep {
ArgPrep::Immediate { min, max } => Ok((min, max)),
_ => Err(()),
};
if let Ok((min, max)) = parsed_ints {
if min == max {
Ok(Constraint::Equal(min))
} else {
Ok(Constraint::Range(min..max + 1))
}
} else {
Err(())
}
}
}
impl Constraint {
pub fn to_range(&self) -> Range<i64> {
match self {
Constraint::Equal(eq) => *eq..*eq + 1,
Constraint::Range(range) => range.clone(),
}
}
}
impl Argument {
fn to_c_type(&self) -> String {
self.ty.c_type()
}
fn is_simd(&self) -> bool {
self.ty.is_simd()
}
pub fn is_ptr(&self) -> bool {
self.ty.is_ptr()
}
pub fn has_constraint(&self) -> bool {
!self.constraints.is_empty()
}
pub fn type_and_name_from_c(arg: &str) -> (&str, &str) {
let split_index = arg
.rfind([' ', '*'])
.expect("Couldn't split type and argname");
(arg[..split_index + 1].trim_end(), &arg[split_index + 1..])
}
// ARM-specific
pub fn from_c(
pos: usize,
arg: &str,
target: &String,
metadata: Option<&mut HashMap<String, Value>>,
) -> Argument {
let (ty, var_name) = Self::type_and_name_from_c(arg);
let ty = IntrinsicType::from_c(ty, target)
.unwrap_or_else(|_| panic!("Failed to parse argument '{arg}'"));
let arg_name = Argument::type_and_name_from_c(&arg).1;
let arg = metadata.and_then(|a| a.remove(arg_name));
let arg_prep: Option<ArgPrep> = arg.and_then(|a| {
if let Value::Object(_) = a {
a.try_into().ok()
} else {
None
}
});
let constraint = arg_prep.and_then(|a| a.try_into().ok());
Argument {
pos,
name: String::from(var_name),
ty,
constraints: constraint.map_or(vec![], |r| vec![r]),
}
}
fn is_rust_vals_array_const(&self) -> bool {
use TypeKind::*;
match self.ty {
// Floats have to be loaded at runtime for stable NaN conversion.
IntrinsicType::Type { kind: Float, .. } => false,
IntrinsicType::Type {
kind: Int | UInt | Poly,
..
} => true,
_ => unimplemented!(),
}
}
/// The binding keyword (e.g. "const" or "let") for the array of possible test inputs.
pub fn rust_vals_array_binding(&self) -> impl std::fmt::Display {
if self.is_rust_vals_array_const() {
"const"
} else {
"let"
}
}
/// The name (e.g. "A_VALS" or "a_vals") for the array of possible test inputs.
pub fn rust_vals_array_name(&self) -> impl std::fmt::Display {
if self.is_rust_vals_array_const() {
format!("{}_VALS", self.name.to_uppercase())
} else {
format!("{}_vals", self.name.to_lowercase())
}
}
}
#[derive(Debug, PartialEq, Clone)]
pub struct ArgumentList {
pub args: Vec<Argument>,
}
impl ArgumentList {
/// Converts the argument list into the call parameters for a C function call.
/// e.g. this would generate something like `a, &b, c`
pub fn as_call_param_c(&self) -> String {
self.args
.iter()
.map(|arg| match arg.ty {
IntrinsicType::Ptr { .. } => {
format!("&{}", arg.name)
}
IntrinsicType::Type { .. } => arg.name.clone(),
})
.collect::<Vec<String>>()
.join(", ")
}
/// Converts the argument list into the call parameters for a Rust function.
/// e.g. this would generate something like `a, b, c`
pub fn as_call_param_rust(&self) -> String {
self.args
.iter()
.filter(|a| !a.has_constraint())
.map(|arg| arg.name.clone())
.collect::<Vec<String>>()
.join(", ")
}
pub fn as_constraint_parameters_rust(&self) -> String {
self.args
.iter()
.filter(|a| a.has_constraint())
.map(|arg| arg.name.clone())
.collect::<Vec<String>>()
.join(", ")
}
/// Creates a line for each argument that initializes an array for C from which `loads` argument
/// values can be loaded as a sliding window.
/// e.g `const int32x2_t a_vals = {0x3effffff, 0x3effffff, 0x3f7fffff}`, if loads=2.
pub fn gen_arglists_c(&self, indentation: Indentation, loads: u32) -> String {
self.iter()
.filter_map(|arg| {
(!arg.has_constraint()).then(|| {
format!(
"{indentation}const {ty} {name}_vals[] = {values};",
ty = arg.ty.c_scalar_type(),
name = arg.name,
values = arg.ty.populate_random(indentation, loads, &Language::C)
)
})
})
.collect::<Vec<_>>()
.join("\n")
}
/// Creates a line for each argument that initializes an array for Rust from which `loads` argument
/// values can be loaded as a sliding window, e.g `const A_VALS: [u32; 20] = [...];`
pub fn gen_arglists_rust(&self, indentation: Indentation, loads: u32) -> String {
self.iter()
.filter_map(|arg| {
(!arg.has_constraint()).then(|| {
format!(
"{indentation}{bind} {name}: [{ty}; {load_size}] = {values};",
bind = arg.rust_vals_array_binding(),
name = arg.rust_vals_array_name(),
ty = arg.ty.rust_scalar_type(),
load_size = arg.ty.num_lanes() * arg.ty.num_vectors() + loads - 1,
values = arg.ty.populate_random(indentation, loads, &Language::Rust)
)
})
})
.collect::<Vec<_>>()
.join("\n")
}
/// Creates a line for each argument that initializes the argument from an array `[arg]_vals` at
/// an offset `i` using a load intrinsic, in C.
/// e.g `uint8x8_t a = vld1_u8(&a_vals[i]);`
///
/// ARM-specific
pub fn load_values_c(&self, indentation: Indentation) -> String {
self.iter()
.filter_map(|arg| {
// The ACLE doesn't support 64-bit polynomial loads on Armv7
// This and the cast are a workaround for this
(!arg.has_constraint()).then(|| {
format!(
"{indentation}{ty} {name} = cast<{ty}>({load}(&{name}_vals[i]));\n",
ty = arg.to_c_type(),
name = arg.name,
load = if arg.is_simd() {
arg.ty.get_load_function_c()
} else {
"*".to_string()
}
)
})
})
.collect()
}
/// Creates a line for each argument that initializes the argument from array `[ARG]_VALS` at
/// an offset `i` using a load intrinsic, in Rust.
/// e.g `let a = vld1_u8(A_VALS.as_ptr().offset(i));`
pub fn load_values_rust(&self, indentation: Indentation) -> String {
self.iter()
.filter_map(|arg| {
(!arg.has_constraint()).then(|| {
format!(
"{indentation}let {name} = {load}({vals_name}.as_ptr().offset(i));\n",
name = arg.name,
vals_name = arg.rust_vals_array_name(),
load = if arg.is_simd() {
arg.ty.get_load_function_rust()
} else {
"*".to_string()
},
)
})
})
.collect()
}
pub fn iter(&self) -> std::slice::Iter<'_, Argument> {
self.args.iter()
}
}