forked from rust-lang/stdarch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathintrinsic.rs
1841 lines (1650 loc) · 64.7 KB
/
intrinsic.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use itertools::Itertools;
use proc_macro2::{Delimiter, Group, Punct, Spacing, TokenStream};
use quote::{ToTokens, TokenStreamExt, format_ident, quote};
use serde::{Deserialize, Serialize};
use serde_with::{DeserializeFromStr, SerializeDisplay};
use std::collections::{HashMap, HashSet};
use std::fmt::{self};
use std::num::ParseIntError;
use std::ops::RangeInclusive;
use std::str::FromStr;
use crate::assert_instr::InstructionAssertionsForBaseType;
use crate::big_endian::{
create_assigned_shuffle_call, create_let_variable, create_mut_let_variable,
create_shuffle_call, create_symbol_identifier, make_variable_mutable, type_has_tuple,
};
use crate::context::{GlobalContext, GroupContext};
use crate::input::{InputSet, InputSetEntry};
use crate::predicate_forms::{DontCareMethod, PredicateForm, PredicationMask, ZeroingMethod};
use crate::{
assert_instr::InstructionAssertionMethod,
context::{self, ArchitectureSettings, Context, LocalContext, VariableType},
expression::{Expression, FnCall, IdentifierType},
fn_suffix::{SuffixKind, type_to_size},
input::IntrinsicInput,
matching::{KindMatchable, SizeMatchable},
typekinds::*,
wildcards::Wildcard,
wildstring::WildString,
};
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum SubstitutionType {
MatchSize(SizeMatchable<WildString>),
MatchKind(KindMatchable<WildString>),
}
impl SubstitutionType {
pub fn get(&mut self, ctx: &LocalContext) -> context::Result<WildString> {
match self {
Self::MatchSize(smws) => {
smws.perform_match(ctx)?;
Ok(smws.as_ref().clone())
}
Self::MatchKind(kmws) => {
kmws.perform_match(ctx)?;
Ok(kmws.as_ref().clone())
}
}
}
}
/// Mutability level
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum AccessLevel {
/// Immutable
R,
/// Mutable
RW,
}
/// Function signature argument.
///
/// Prepend the `mut` keyword for a mutable argument. Separate argument name
/// and type with a semicolon `:`. Usage examples:
/// - Mutable argument: `mut arg1: *u64`
/// - Immutable argument: `arg2: u32`
#[derive(Debug, Clone, SerializeDisplay, DeserializeFromStr)]
pub struct Argument {
/// Argument name
pub name: WildString,
/// Mutability level
pub rw: AccessLevel,
/// Argument type
pub kind: TypeKind,
}
impl Argument {
pub fn populate_variables(&self, vars: &mut HashMap<String, (TypeKind, VariableType)>) {
vars.insert(
self.name.to_string(),
(self.kind.clone(), VariableType::Argument),
);
}
}
impl FromStr for Argument {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut it = s.splitn(2, ':').map(<str>::trim);
if let Some(mut lhs) = it.next().map(|s| s.split_whitespace()) {
let lhs_len = lhs.clone().count();
match (lhs_len, lhs.next(), it.next()) {
(2, Some("mut"), Some(kind)) => Ok(Argument {
name: lhs.next().unwrap().parse()?,
rw: AccessLevel::RW,
kind: kind.parse()?,
}),
(2, Some(ident), _) => Err(format!("invalid {ident:#?} keyword")),
(1, Some(name), Some(kind)) => Ok(Argument {
name: name.parse()?,
rw: AccessLevel::R,
kind: kind.parse()?,
}),
_ => Err(format!("invalid argument `{s}` provided")),
}
} else {
Err(format!("invalid argument `{s}` provided"))
}
}
}
impl fmt::Display for Argument {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let AccessLevel::RW = &self.rw {
write!(f, "mut ")?;
}
write!(f, "{}: {}", self.name, self.kind)
}
}
impl ToTokens for Argument {
fn to_tokens(&self, tokens: &mut TokenStream) {
if let AccessLevel::RW = &self.rw {
tokens.append(format_ident!("mut"))
}
let (name, kind) = (format_ident!("{}", self.name.to_string()), &self.kind);
tokens.append_all(quote! { #name: #kind })
}
}
/// Static definition part of the signature. It may evaluate to a constant
/// expression with e.g. `const imm: u64`, or a generic `T: Into<u64>`.
#[derive(Debug, Clone, SerializeDisplay, DeserializeFromStr)]
pub enum StaticDefinition {
/// Constant expression
Constant(Argument),
/// Generic type
Generic(String),
}
impl StaticDefinition {
pub fn as_variable(&self) -> Option<(String, (TypeKind, VariableType))> {
match self {
StaticDefinition::Constant(arg) => Some((
arg.name.to_string(),
(arg.kind.clone(), VariableType::Argument),
)),
StaticDefinition::Generic(..) => None,
}
}
}
impl FromStr for StaticDefinition {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.trim() {
s if s.starts_with("const ") => Ok(StaticDefinition::Constant(s[6..].trim().parse()?)),
s => Ok(StaticDefinition::Generic(s.to_string())),
}
}
}
impl fmt::Display for StaticDefinition {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
StaticDefinition::Constant(arg) => write!(f, "const {arg}"),
StaticDefinition::Generic(generic) => write!(f, "{generic}"),
}
}
}
impl ToTokens for StaticDefinition {
fn to_tokens(&self, tokens: &mut TokenStream) {
tokens.append_all(match self {
StaticDefinition::Constant(arg) => quote! { const #arg },
StaticDefinition::Generic(generic) => {
let generic: TokenStream = generic.parse().expect("invalid Rust code");
quote! { #generic }
}
})
}
}
/// Function constraints
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum Constraint {
/// Asserts that the given variable equals to any of the given integer values
AnyI32 {
variable: String,
any_values: Vec<i32>,
},
/// WildString version of RangeI32. If the string values given for the range
/// are valid, this gets built into a RangeI32.
RangeWildstring {
variable: String,
range: (WildString, WildString),
},
/// Asserts that the given variable's value falls in the specified range
RangeI32 {
variable: String,
range: SizeMatchable<RangeInclusive<i32>>,
},
/// Asserts that the number of elements/lanes does not exceed the 2048-bit SVE constraint
SVEMaxElems {
variable: String,
sve_max_elems_type: TypeKind,
},
/// Asserts that the number of elements/lanes does not exceed the 128-bit register constraint
VecMaxElems {
variable: String,
vec_max_elems_type: TypeKind,
},
}
impl Constraint {
fn variable(&self) -> &str {
match self {
Constraint::AnyI32 { variable, .. }
| Constraint::RangeWildstring { variable, .. }
| Constraint::RangeI32 { variable, .. }
| Constraint::SVEMaxElems { variable, .. }
| Constraint::VecMaxElems { variable, .. } => variable,
}
}
pub fn build(&mut self, ctx: &Context) -> context::Result {
if let Self::RangeWildstring {
variable,
range: (min, max),
} = self
{
min.build_acle(ctx.local)?;
max.build_acle(ctx.local)?;
let min = min.to_string();
let max = max.to_string();
let min: i32 = min
.parse()
.map_err(|_| format!("the minimum value `{min}` is not a valid number"))?;
let max: i32 = max
.parse()
.or_else(|_| Ok(type_to_size(max.as_str())))
.map_err(|_: ParseIntError| {
format!("the maximum value `{max}` is not a valid number")
})?;
*self = Self::RangeI32 {
variable: variable.to_owned(),
range: SizeMatchable::Matched(RangeInclusive::new(min, max)),
}
}
if let Self::SVEMaxElems {
sve_max_elems_type: ty,
..
}
| Self::VecMaxElems {
vec_max_elems_type: ty,
..
} = self
{
if let Some(w) = ty.wildcard() {
ty.populate_wildcard(ctx.local.provide_type_wildcard(w)?)?;
}
}
if let Self::RangeI32 { range, .. } = self {
range.perform_match(ctx.local)?;
}
let variable = self.variable();
ctx.local
.variables
.contains_key(variable)
.then_some(())
.ok_or_else(|| format!("cannot build constraint, could not find variable {variable}"))
}
}
/// Function signature
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Signature {
/// Function name
pub name: WildString,
/// List of function arguments, leave unset or empty for no arguments
pub arguments: Vec<Argument>,
/// Function return type, leave unset for void
pub return_type: Option<TypeKind>,
/// For some neon intrinsics we want to modify the suffix of the function name
pub suffix_type: Option<SuffixKind>,
/// List of static definitions, leave unset of empty if not required
#[serde(default)]
pub static_defs: Vec<StaticDefinition>,
/// **Internal use only.**
/// Condition for which the ultimate function is specific to predicates.
#[serde(skip)]
pub is_predicate_specific: bool,
/// **Internal use only.**
/// Setting this property will trigger the signature builder to convert any `svbool*_t` to `svbool_t` in the input and output.
#[serde(skip)]
pub predicate_needs_conversion: bool,
}
impl Signature {
pub fn drop_argument(&mut self, arg_name: &WildString) -> Result<(), String> {
if let Some(idx) = self
.arguments
.iter()
.position(|arg| arg.name.to_string() == arg_name.to_string())
{
self.arguments.remove(idx);
Ok(())
} else {
Err(format!("no argument {arg_name} found to drop"))
}
}
pub fn build(&mut self, ctx: &LocalContext) -> context::Result {
if self.name_has_neon_suffix() {
self.name.build_neon_intrinsic_signature(ctx)?;
} else {
self.name.build_acle(ctx)?;
}
if let Some(ref mut return_type) = self.return_type {
if let Some(w) = return_type.clone().wildcard() {
return_type.populate_wildcard(ctx.provide_type_wildcard(w)?)?;
}
}
self.arguments
.iter_mut()
.try_for_each(|arg| arg.name.build_acle(ctx))?;
self.arguments
.iter_mut()
.filter_map(|arg| {
arg.kind
.clone()
.wildcard()
.map(|w| (&mut arg.kind, w.clone()))
})
.try_for_each(|(ty, w)| ty.populate_wildcard(ctx.provide_type_wildcard(&w)?))
}
pub fn fn_name(&self) -> WildString {
self.name.replace(['[', ']'], "")
}
pub fn doc_name(&self) -> String {
self.name.to_string()
}
fn name_has_neon_suffix(&self) -> bool {
for part in self.name.wildcards() {
let has_suffix = match part {
Wildcard::NEONType(_, _, suffix_type) => suffix_type.is_some(),
_ => false,
};
if has_suffix {
return true;
}
}
false
}
}
impl ToTokens for Signature {
fn to_tokens(&self, tokens: &mut TokenStream) {
let name_ident = format_ident!("{}", self.fn_name().to_string());
let arguments = self
.arguments
.clone()
.into_iter()
.map(|mut arg| {
if arg
.kind
.vector()
.map_or(false, |ty| ty.base_type().is_bool())
&& self.predicate_needs_conversion
{
arg.kind = TypeKind::Vector(VectorType::make_predicate_from_bitsize(8))
}
arg
})
.collect_vec();
let static_defs = &self.static_defs;
tokens.append_all(quote! { fn #name_ident<#(#static_defs),*>(#(#arguments),*) });
if let Some(ref return_type) = self.return_type {
if return_type
.vector()
.map_or(false, |ty| ty.base_type().is_bool())
&& self.predicate_needs_conversion
{
tokens.append_all(quote! { -> svbool_t })
} else {
tokens.append_all(quote! { -> #return_type })
}
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LLVMLinkAttribute {
/// Either one architecture or a comma separated list of architectures with NO spaces
pub arch: String,
pub link: WildString,
}
impl ToTokens for LLVMLinkAttribute {
fn to_tokens(&self, tokens: &mut TokenStream) {
let LLVMLinkAttribute { arch, link } = self;
let link = link.to_string();
// For example:
//
// #[cfg_attr(target_arch = "arm", link_name = "llvm.ctlz.v4i16")]
//
// #[cfg_attr(
// any(target_arch = "aarch64", target_arch = "arm64ec"),
// link_name = "llvm.aarch64.neon.suqadd.i32"
// )]
let mut cfg_attr_cond = TokenStream::new();
let mut single_arch = true;
for arch in arch.split(',') {
if !cfg_attr_cond.is_empty() {
single_arch = false;
cfg_attr_cond.append(Punct::new(',', Spacing::Alone));
}
cfg_attr_cond.append_all(quote! { target_arch = #arch });
}
assert!(!cfg_attr_cond.is_empty());
if !single_arch {
cfg_attr_cond = quote! { any( #cfg_attr_cond ) };
}
tokens.append_all(quote! {
#[cfg_attr(#cfg_attr_cond, link_name = #link)]
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LLVMLink {
/// LLVM link function name without namespace and types,
/// e.g. `st1` in `llvm.aarch64.sve.st1.nxv4i32`
pub name: WildString,
/// LLVM link signature arguments, leave unset if it inherits from intrinsic's signature
pub arguments: Option<Vec<Argument>>,
/// LLVM link signature return type, leave unset if it inherits from intrinsic's signature
pub return_type: Option<TypeKind>,
/// **This will be set automatically if not set**
/// Attribute LLVM links for the function. First element is the architecture it targets,
/// second element is the LLVM link itself.
pub links: Option<Vec<LLVMLinkAttribute>>,
/// **Internal use only. Do not set.**
/// Generated signature from these `arguments` and/or `return_type` if set, and the intrinsic's signature.
#[serde(skip)]
pub signature: Option<Box<Signature>>,
}
impl LLVMLink {
pub fn resolve(&self, cfg: &ArchitectureSettings) -> String {
self.name
.starts_with("llvm")
.then(|| self.name.to_string())
.unwrap_or_else(|| format!("{}.{}", cfg.llvm_link_prefix, self.name))
}
pub fn build_and_save(&mut self, ctx: &mut Context) -> context::Result {
self.build(ctx)?;
// Save LLVM link to the group context
ctx.global.arch_cfgs.iter().for_each(|cfg| {
ctx.group
.links
.insert(self.resolve(cfg), ctx.local.input.clone());
});
Ok(())
}
pub fn build(&mut self, ctx: &mut Context) -> context::Result {
let mut sig_name = ctx.local.signature.name.clone();
sig_name.prepend_str("_");
let argv = self
.arguments
.clone()
.unwrap_or_else(|| ctx.local.signature.arguments.clone());
let mut sig = Signature {
name: sig_name,
arguments: argv,
return_type: self
.return_type
.clone()
.or_else(|| ctx.local.signature.return_type.clone()),
suffix_type: None,
static_defs: vec![],
is_predicate_specific: ctx.local.signature.is_predicate_specific,
predicate_needs_conversion: false,
};
sig.build(ctx.local)?;
self.name.build(ctx.local, TypeRepr::LLVMMachine)?;
// Add link function name to context
ctx.local
.substitutions
.insert(Wildcard::LLVMLink, sig.fn_name().to_string());
self.signature = Some(Box::new(sig));
if let Some(ref mut links) = self.links {
links.iter_mut().for_each(|ele| {
ele.link
.build(&ctx.local, TypeRepr::LLVMMachine)
.expect("Failed to transform to LLVMMachine representation");
});
} else {
self.links = Some(
ctx.global
.arch_cfgs
.iter()
.map(|cfg| LLVMLinkAttribute {
arch: cfg.arch_name.to_owned(),
link: self.resolve(cfg).into(),
})
.collect_vec(),
);
}
Ok(())
}
/// Alters all the unsigned types from the signature. This is required where
/// a signed and unsigned variant require the same binding to an exposed
/// LLVM instrinsic.
pub fn sanitise_uints(&mut self) {
let transform = |tk: &mut TypeKind| {
if let Some(BaseType::Sized(BaseTypeKind::UInt, size)) = tk.base_type() {
*tk.base_type_mut().unwrap() = BaseType::Sized(BaseTypeKind::Int, *size)
}
};
if let Some(sig) = self.signature.as_mut() {
for arg in sig.arguments.iter_mut() {
transform(&mut arg.kind);
}
sig.return_type.as_mut().map(transform);
}
}
/// Make a function call to the LLVM link
pub fn make_fn_call(&self, intrinsic_sig: &Signature) -> context::Result<Expression> {
let link_sig = self.signature.as_ref().ok_or_else(|| {
"cannot derive the LLVM link call, as it does not hold a valid function signature"
.to_string()
})?;
if intrinsic_sig.arguments.len() != link_sig.arguments.len() {
return Err(
"cannot derive the LLVM link call, the number of arguments does not match"
.to_string(),
);
}
let call_args = intrinsic_sig
.arguments
.iter()
.zip(link_sig.arguments.iter())
.map(|(intrinsic_arg, link_arg)| {
// Could also add a type check...
if intrinsic_arg.name == link_arg.name {
Ok(Expression::Identifier(
intrinsic_arg.name.to_owned(),
IdentifierType::Variable,
))
} else {
Err("cannot derive the LLVM link call, the arguments do not match".to_string())
}
})
.try_collect()?;
Ok(FnCall::new_expression(link_sig.fn_name().into(), call_args))
}
/// Given a FnCall, apply all the predicate and unsigned conversions as required.
pub fn apply_conversions_to_call(
&self,
mut fn_call: FnCall,
ctx: &Context,
) -> context::Result<Expression> {
use BaseType::{Sized, Unsized};
use BaseTypeKind::{Bool, UInt};
use VariableType::Argument;
let convert =
|method: &str, ex| Expression::MethodCall(Box::new(ex), method.to_string(), vec![]);
fn_call.1 = fn_call
.1
.into_iter()
.map(|arg| -> context::Result<Expression> {
if let Expression::Identifier(ref var_name, IdentifierType::Variable) = arg {
let (kind, scope) = ctx
.local
.variables
.get(&var_name.to_string())
.ok_or_else(|| format!("invalid variable {var_name:?} being referenced"))?;
match (scope, kind.base_type()) {
(Argument, Some(Sized(Bool, bitsize))) if *bitsize != 8 => {
Ok(convert("into", arg))
}
(Argument, Some(Sized(UInt, _) | Unsized(UInt))) => {
if ctx.global.auto_llvm_sign_conversion {
Ok(convert("as_signed", arg))
} else {
Ok(arg)
}
}
_ => Ok(arg),
}
} else {
Ok(arg)
}
})
.try_collect()?;
let return_type_conversion = if !ctx.global.auto_llvm_sign_conversion {
None
} else {
self.signature
.as_ref()
.and_then(|sig| sig.return_type.as_ref())
.and_then(|ty| {
if let Some(Sized(Bool, bitsize)) = ty.base_type() {
(*bitsize != 8).then_some(Bool)
} else if let Some(Sized(UInt, _) | Unsized(UInt)) = ty.base_type() {
Some(UInt)
} else {
None
}
})
};
let fn_call = Expression::FnCall(fn_call);
match return_type_conversion {
Some(Bool) => Ok(convert("into", fn_call)),
Some(UInt) => Ok(convert("as_unsigned", fn_call)),
_ => Ok(fn_call),
}
}
}
impl ToTokens for LLVMLink {
fn to_tokens(&self, tokens: &mut TokenStream) {
assert!(
self.signature.is_some() && self.links.is_some(),
"expression {self:#?} was not built before calling to_tokens"
);
let signature = self.signature.as_ref().unwrap();
let links = self.links.as_ref().unwrap();
tokens.append_all(quote! {
unsafe extern "unadjusted" {
#(#links)*
#signature;
}
})
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FunctionVisibility {
#[default]
Public,
Private,
}
/// Whether to generate a load/store test, and which typeset index
/// represents the data type of the load/store target address
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Test {
#[default]
#[serde(skip)]
None, // Covered by `intrinsic-test`
Load(usize),
Store(usize),
}
impl Test {
pub fn get_typeset_index(&self) -> Option<usize> {
match *self {
Test::Load(n) => Some(n),
Test::Store(n) => Some(n),
_ => None,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Safety {
Safe,
Unsafe(Vec<UnsafetyComment>),
}
impl Safety {
/// Return `Ok(Safety::Safe)` if safety appears reasonable for the given `intrinsic`'s name and
/// prototype. Otherwise, return `Err()` with a suitable diagnostic.
fn safe_checked(intrinsic: &Intrinsic) -> Result<Self, String> {
let name = intrinsic.signature.doc_name();
if name.starts_with("sv") {
let handles_pointers = intrinsic
.signature
.arguments
.iter()
.any(|arg| matches!(arg.kind, TypeKind::Pointer(..)));
if name.starts_with("svld")
|| name.starts_with("svst")
|| name.starts_with("svprf")
|| name.starts_with("svundef")
|| handles_pointers
{
let doc = intrinsic.doc.as_ref().map(|s| s.to_string());
let doc = doc.as_deref().unwrap_or("...");
Err(format!(
"`{name}` has no safety specification, but it looks like it should be unsafe. \
Consider specifying (un)safety explicitly:
- name: {name}
doc: {doc}
safety:
unsafe:
- ...
...
"
))
} else {
Ok(Self::Safe)
}
} else {
Err(format!(
"Safety::safe_checked() for non-SVE intrinsic: {name}"
))
}
}
fn is_safe(&self) -> bool {
match self {
Self::Safe => true,
Self::Unsafe(..) => false,
}
}
fn is_unsafe(&self) -> bool {
!self.is_safe()
}
fn has_doc_comments(&self) -> bool {
match self {
Self::Safe => false,
Self::Unsafe(v) => !v.is_empty(),
}
}
fn doc_comments(&self) -> &[UnsafetyComment] {
match self {
Self::Safe => &[],
Self::Unsafe(v) => v.as_slice(),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum UnsafetyComment {
Custom(String),
Uninitialized,
PointerOffset(GovernedBy),
PointerOffsetVnum(GovernedBy),
Dereference(GovernedBy),
UnpredictableOnFault,
NonTemporal,
Neon,
NoProvenance(String),
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GovernedBy {
#[default]
Predicated,
PredicatedNonFaulting,
PredicatedFirstFaulting,
}
impl fmt::Display for GovernedBy {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Predicated => write!(f, " (governed by `pg`)"),
Self::PredicatedNonFaulting => write!(
f,
" (governed by `pg`, the first-fault register (`FFR`) \
and non-faulting behaviour)"
),
Self::PredicatedFirstFaulting => write!(
f,
" (governed by `pg`, the first-fault register (`FFR`) \
and first-faulting behaviour)"
),
}
}
}
impl fmt::Display for UnsafetyComment {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Custom(s) => s.fmt(f),
Self::Neon => write!(f, "Neon instrinsic unsafe"),
Self::Uninitialized => write!(
f,
"This creates an uninitialized value, and may be unsound (like \
[`core::mem::uninitialized`])."
),
Self::PointerOffset(gov) => write!(
f,
"[`pointer::offset`](pointer#method.offset) safety constraints must \
be met for the address calculation for each active element{gov}."
),
Self::PointerOffsetVnum(gov) => write!(
f,
"[`pointer::offset`](pointer#method.offset) safety constraints must \
be met for the address calculation for each active element{gov}. \
In particular, note that `vnum` is scaled by the vector \
length, `VL`, which is not known at compile time."
),
Self::Dereference(gov) => write!(
f,
"This dereferences and accesses the calculated address for each \
active element{gov}."
),
Self::NonTemporal => write!(
f,
"Non-temporal accesses have special memory ordering rules, and \
[explicit barriers may be required for some applications]\
(https://developer.arm.com/documentation/den0024/a/Memory-Ordering/Barriers/Non-temporal-load-and-store-pair?lang=en)."
),
Self::NoProvenance(arg) => write!(
f,
"Addresses passed in `{arg}` lack provenance, so this is similar to using a \
`usize as ptr` cast (or [`core::ptr::from_exposed_addr`]) on each lane before \
using it."
),
Self::UnpredictableOnFault => write!(
f,
"Result lanes corresponding to inactive FFR lanes (either before or as a result \
of this intrinsic) have \"CONSTRAINED UNPREDICTABLE\" values, irrespective of \
predication. Refer to architectural documentation for details."
),
}
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Intrinsic {
#[serde(default)]
pub visibility: FunctionVisibility,
#[serde(default)]
pub doc: Option<WildString>,
#[serde(flatten)]
pub signature: Signature,
/// Function sequential composition
pub compose: Vec<Expression>,
/// Input to generate the intrinsic against. Leave empty if the intrinsic
/// does not have any variants.
/// Specific variants contain one InputSet
#[serde(flatten, default)]
pub input: IntrinsicInput,
#[serde(default)]
pub constraints: Vec<Constraint>,
/// Additional target features to add to the global settings
#[serde(default)]
pub target_features: Vec<String>,
/// Should the intrinsic be `unsafe`? By default, the generator will try to guess from the
/// prototype, but it errs on the side of `unsafe`, and prints a warning in that case.
#[serde(default)]
pub safety: Option<Safety>,
#[serde(default)]
pub substitutions: HashMap<String, SubstitutionType>,
/// List of the only indices in a typeset that require conversion to signed
/// when deferring unsigned intrinsics to signed. (optional, default
/// behaviour is all unsigned types are converted to signed)
#[serde(default)]
pub defer_to_signed_only_indices: HashSet<usize>,
pub assert_instr: Option<Vec<InstructionAssertionMethod>>,
/// Whether we should generate a test for this intrinsic
#[serde(default)]
pub test: Test,
/// Primary base type, used for instruction assertion.
#[serde(skip)]
pub base_type: Option<BaseType>,
/// Attributes for the function
pub attr: Option<Vec<Expression>>,
/// Big endian variant for composing, this gets populated internally
#[serde(skip)]
pub big_endian_compose: Vec<Expression>,
/// Big endian sometimes needs the bits inverted in a way that cannot be
/// automatically detected
#[serde(default)]
pub big_endian_inverse: Option<bool>,
}
impl Intrinsic {
pub fn llvm_link(&self) -> Option<&LLVMLink> {
self.compose.iter().find_map(|ex| {
if let Expression::LLVMLink(llvm_link) = ex {
Some(llvm_link)
} else {
None
}
})
}
pub fn llvm_link_mut(&mut self) -> Option<&mut LLVMLink> {
self.compose.iter_mut().find_map(|ex| {
if let Expression::LLVMLink(llvm_link) = ex {
Some(llvm_link)
} else {
None
}
})
}
pub fn generate_variants(&self, global_ctx: &GlobalContext) -> context::Result<Vec<Intrinsic>> {
let wrap_err = |err| format!("{}: {err}", self.signature.name);
let mut group_ctx = GroupContext::default();
self.input
.variants(self)
.map_err(wrap_err)?
.map(|input| {
self.generate_variant(input.clone(), &mut group_ctx, global_ctx)
.map_err(wrap_err)
.map(|variant| (variant, input))
})
.collect::<context::Result<Vec<_>>>()
.and_then(|mut variants| {
variants.sort_by_cached_key(|(_, input)| input.to_owned());
if variants.is_empty() {
let standalone_variant = self
.generate_variant(InputSet::default(), &mut group_ctx, global_ctx)
.map_err(wrap_err)?;
Ok(vec![standalone_variant])
} else {
Ok(variants
.into_iter()
.map(|(variant, _)| variant)
.collect_vec())
}
})
}
pub fn generate_variant(
&self,
input: InputSet,
group_ctx: &mut GroupContext,
global_ctx: &GlobalContext,
) -> context::Result<Intrinsic> {
let mut variant = self.clone();
variant.input.types = vec![InputSetEntry::new(vec![input.clone()])];
let mut local_ctx = LocalContext::new(input, self);
let mut ctx = Context {
local: &mut local_ctx,
group: group_ctx,
global: global_ctx,