1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
|
use itertools::Itertools;
use regex::Regex;
use serde::Deserialize;
use crate::argument::{Argument, ArgumentList, Constraint};
use crate::intrinsic::Intrinsic;
use crate::types::{IntrinsicType, TypeKind};
pub struct CsvMetadata {
notices: String,
spdx_lic: String,
}
impl CsvMetadata {
fn new<'a>(header: impl Iterator<Item = &'a str>) -> Self {
lazy_static! {
static ref SPDX_LICENSE_IDENTIFIER: Regex =
Regex::new(r#"SPDX-License-Identifier:(.*)"#).unwrap();
}
let notices = header.map(|line| format!("{line}\n")).collect::<String>();
let spdx_lic = match SPDX_LICENSE_IDENTIFIER
.captures_iter(¬ices)
.exactly_one()
{
Ok(caps) => {
let cap = caps.get(1).unwrap().as_str().trim();
// Ensure that (unlikely) ACLE licence changes don't go unnoticed.
assert_eq!(cap, "Apache-2.0");
cap.to_string()
}
Err(caps_iter) => panic!(
"Expected exactly one SPDX-License-Identifier, found {}.",
caps_iter.count()
),
};
Self { notices, spdx_lic }
}
pub fn spdx_license_identifier(&self) -> &str {
self.spdx_lic.as_str()
}
pub fn notices_lines(&self) -> impl Iterator<Item = &str> {
self.notices.lines()
}
}
pub fn get_acle_intrinsics(filename: &str) -> (CsvMetadata, Vec<Intrinsic>) {
let data = std::fs::read_to_string(filename).expect("Failed to open ACLE intrinsics file");
let comment_header = data.lines().map_while(|l| l.strip_prefix("<COMMENT>\t"));
let meta = CsvMetadata::new(comment_header);
let data = data
.lines()
.filter_map(|l| {
(!(l.starts_with("<COMMENT>") || l.is_empty() || l.starts_with("<SECTION>")))
.then(|| l.replace("<HEADER>\t", ""))
})
.join("\n");
let mut csv_reader = csv::ReaderBuilder::new()
.delimiter(b'\t')
.from_reader(data.as_bytes());
let mut intrinsics: Vec<Intrinsic> = csv_reader
.deserialize()
.filter_map(|x: Result<ACLEIntrinsicLine, _>| x.ok().map(|i| i.into()))
.collect::<Vec<_>>();
// Intrinsics such as vshll_n_s8 exist twice in the ACLE with different constraints.
intrinsics.sort_by(|a, b| a.name.cmp(&b.name));
let (intrinsics, duplicates) = intrinsics.partition_dedup_by(|a, b| a.name == b.name);
for duplicate in duplicates {
let name = &duplicate.name;
let constraints = duplicate
.arguments
.args
.drain(..)
.filter(|a| a.has_constraint());
let intrinsic = intrinsics.iter_mut().find(|i| &i.name == name).unwrap();
for mut constraint in constraints {
let real_constraint = intrinsic
.arguments
.args
.iter_mut()
.find(|a| a.name == constraint.name)
.unwrap();
real_constraint
.constraints
.push(constraint.constraints.pop().unwrap());
}
}
(meta, intrinsics.to_vec())
}
impl Into<Intrinsic> for ACLEIntrinsicLine {
fn into(self) -> Intrinsic {
let signature = self.intrinsic;
let (ret_ty, remaining) = signature.split_once(' ').unwrap();
let results =
type_from_c(ret_ty).unwrap_or_else(|_| panic!("Failed to parse return type: {ret_ty}"));
let (name, args) = remaining.split_once('(').unwrap();
let args = args.trim_end_matches(')');
// Typo in ACLE data
let args = args.replace("int16x8q_t", "int16x8_t");
let arg_prep = self.argument_preparation.as_str();
let args = args
.split(',')
.enumerate()
.map(move |(idx, arg)| {
let arg = arg.trim();
if arg.starts_with("__builtin_constant_p") {
handle_constraint(idx, arg, arg_prep)
} else {
from_c(idx, arg)
}
})
.collect();
let arguments = ArgumentList { args };
let a64_only = match &*self.supported_architectures {
"A64" => true,
"v7/A32/A64" | "A32/A64" => false,
_ => panic!("Invalid supported architectures"),
};
Intrinsic {
name: name.to_string(),
arguments,
results,
a64_only,
}
}
}
fn handle_constraint(idx: usize, arg: &str, prep: &str) -> Argument {
let prep = prep.replace(' ', "");
let name = arg
.trim_start_matches("__builtin_constant_p")
.trim_start_matches(|ref c| c == &' ' || c == &'(')
.trim_end_matches(')')
.to_string();
let ty = IntrinsicType::Type {
constant: true,
kind: TypeKind::Int,
bit_len: Some(32),
simd_len: None,
vec_len: None,
};
let constraints = prep
.split(';')
.find_map(|p| handle_range_constraint(&name, p).or_else(|| handle_eq_constraint(&name, p)))
.map(|c| vec![c])
.unwrap_or_default();
Argument {
pos: idx,
name,
ty,
constraints,
}
}
fn handle_range_constraint(name: &str, data: &str) -> Option<Constraint> {
lazy_static! {
static ref RANGE_CONSTRAINT: Regex =
Regex::new(r#"([0-9]+)<=([[:alnum:]]+)<=([0-9]+)"#).unwrap();
}
let captures = RANGE_CONSTRAINT.captures(data)?;
if captures.get(2).map(|c| c.as_str() == name).unwrap_or(false) {
match (captures.get(1), captures.get(3)) {
(Some(start), Some(end)) => {
let start = start.as_str().parse::<i64>().unwrap();
let end = end.as_str().parse::<i64>().unwrap() + 1;
Some(Constraint::Range(start..end))
}
_ => panic!("Invalid constraint"),
}
} else {
None
}
}
fn handle_eq_constraint(name: &str, data: &str) -> Option<Constraint> {
lazy_static! {
static ref EQ_CONSTRAINT: Regex = Regex::new(r#"([[:alnum:]]+)==([0-9]+)"#).unwrap();
}
let captures = EQ_CONSTRAINT.captures(data)?;
if captures.get(1).map(|c| c.as_str() == name).unwrap_or(false) {
captures
.get(2)
.map(|c| Constraint::Equal(c.as_str().parse::<i64>().unwrap()))
} else {
None
}
}
fn from_c(pos: usize, s: &str) -> Argument {
let name_index = s
.chars()
.rev()
.take_while(|c| c != &'*' && c != &' ')
.count();
let name_start = s.len() - name_index;
let name = s[name_start..].to_string();
let s = s[..name_start].trim();
Argument {
pos,
name,
ty: type_from_c(s).unwrap_or_else(|_| panic!("Failed to parse type: {s}")),
constraints: vec![],
}
}
fn type_from_c(s: &str) -> Result<IntrinsicType, String> {
const CONST_STR: &str = "const ";
if let Some(s) = s.strip_suffix('*') {
let (s, constant) = if s.ends_with(CONST_STR) {
(&s[..s.len() - (CONST_STR.len() + 1)], true)
} else {
(s, false)
};
let s = s.trim_end();
Ok(IntrinsicType::Ptr {
constant,
child: Box::new(type_from_c(s)?),
})
} else {
// [const ]TYPE[{bitlen}[x{simdlen}[x{vec_len}]]][_t]
let (mut s, constant) = if let Some(s) = s.strip_prefix(CONST_STR) {
(s, true)
} else {
(s, false)
};
s = s.strip_suffix("_t").unwrap_or(s);
let mut parts = s.split('x'); // [[{bitlen}], [{simdlen}], [{vec_len}] ]
let start = parts.next().ok_or("Impossible to parse type")?;
if let Some(digit_start) = start.find(|c: char| c.is_ascii_digit()) {
let (arg_kind, bit_len) = start.split_at(digit_start);
let arg_kind = arg_kind.parse::<TypeKind>()?;
let bit_len = bit_len.parse::<u32>().map_err(|err| err.to_string())?;
let simd_len = parts.next().map(|part| part.parse::<u32>().ok()).flatten();
let vec_len = parts.next().map(|part| part.parse::<u32>().ok()).flatten();
Ok(IntrinsicType::Type {
constant,
kind: arg_kind,
bit_len: Some(bit_len),
simd_len,
vec_len,
})
} else {
Ok(IntrinsicType::Type {
constant,
kind: start.parse::<TypeKind>()?,
bit_len: None,
simd_len: None,
vec_len: None,
})
}
}
}
#[derive(Deserialize, Debug, PartialEq, Clone)]
struct ACLEIntrinsicLine {
#[serde(rename = "Intrinsic")]
intrinsic: String,
#[serde(rename = "Argument preparation")]
argument_preparation: String,
#[serde(rename = "AArch64 Instruction")]
aarch64_instruction: String,
#[serde(rename = "Result")]
result: String,
#[serde(rename = "Supported architectures")]
supported_architectures: String,
}
#[cfg(test)]
mod test {
use super::*;
use crate::argument::Argument;
use crate::types::{IntrinsicType, TypeKind};
#[test]
fn parse_simd() {
let expected = Argument {
pos: 0,
name: "a".into(),
ty: IntrinsicType::Type {
constant: false,
kind: TypeKind::Int,
bit_len: Some(32),
simd_len: Some(4),
vec_len: None,
},
constraints: vec![],
};
let actual = from_c(0, "int32x4_t a");
assert_eq!(expected, actual);
}
#[test]
fn parse_simd_with_vec() {
let expected = Argument {
pos: 0,
name: "a".into(),
ty: IntrinsicType::Type {
constant: false,
kind: TypeKind::Int,
bit_len: Some(32),
simd_len: Some(4),
vec_len: Some(2),
},
constraints: vec![],
};
let actual = from_c(0, "int32x4x2_t a");
assert_eq!(expected, actual);
}
#[test]
fn test_ptr() {
let expected = Argument {
pos: 0,
name: "ptr".into(),
ty: crate::types::IntrinsicType::Ptr {
constant: true,
child: Box::new(IntrinsicType::Type {
constant: false,
kind: TypeKind::Int,
bit_len: Some(8),
simd_len: None,
vec_len: None,
}),
},
constraints: vec![],
};
let actual = from_c(0, "int8_t const *ptr");
assert_eq!(expected, actual);
}
}
|