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
use std::convert::{TryFrom, TryInto};
use hashbrown::HashMap;
use llvm_constants::{AttributeCode, IrBlockId};
use llvm_support::{Align, AttributeId, AttributeKind};
use num_enum::{TryFromPrimitive, TryFromPrimitiveError};
use thiserror::Error;
use crate::block::{BlockMapError, IrBlock};
use crate::map::MapCtx;
use crate::record::RecordMapError;
use crate::unroll::{UnrolledBlock, UnrolledRecord};
#[derive(Debug, Error)]
pub enum AttributeError {
#[error("unknown attribute code")]
UnknownAttributeCode(#[from] TryFromPrimitiveError<AttributeCode>),
#[error("unknown attribute kind")]
UnknownAttributeKind(#[from] TryFromPrimitiveError<AttributeKind>),
#[error("wrong block for code: {0:?}")]
WrongBlock(AttributeCode),
#[error("attribute structure too short")]
TooShort,
#[error("bad attribute string")]
BadString,
#[error("unknown attribute ID")]
UnknownAttributeId(#[from] TryFromPrimitiveError<AttributeId>),
#[error("malformed attribute (format doesn't match ID): {0}: {1:?}")]
AttributeMalformed(&'static str, AttributeId),
#[error("FIXME: unsupported integer attribute: {0:?}")]
IntAttributeUnsupported(AttributeId),
#[error("nonexistent attribute group: {0}")]
BadAttributeGroup(u32),
}
#[non_exhaustive]
#[derive(Copy, Clone, Debug, PartialEq, TryFromPrimitive)]
#[repr(u64)]
pub enum EnumAttribute {
AlwaysInline = AttributeId::AlwaysInline as u64,
ByVal = AttributeId::ByVal as u64,
InlineHint = AttributeId::InlineHint as u64,
InReg = AttributeId::InReg as u64,
MinSize = AttributeId::MinSize as u64,
Naked = AttributeId::Naked as u64,
Nest = AttributeId::Nest as u64,
NoAlias = AttributeId::NoAlias as u64,
NoBuiltin = AttributeId::NoBuiltin as u64,
NoCapture = AttributeId::NoCapture as u64,
NoDuplicate = AttributeId::NoDuplicate as u64,
NoImplicitFloat = AttributeId::NoImplicitFloat as u64,
NoInline = AttributeId::NoInline as u64,
NonLazyBind = AttributeId::NonLazyBind as u64,
NoRedZone = AttributeId::NoRedZone as u64,
NoReturn = AttributeId::NoReturn as u64,
NoUnwind = AttributeId::NoUnwind as u64,
OptimizeForSize = AttributeId::OptimizeForSize as u64,
ReadNone = AttributeId::ReadNone as u64,
ReadOnly = AttributeId::ReadOnly as u64,
Returned = AttributeId::Returned as u64,
ReturnsTwice = AttributeId::ReturnsTwice as u64,
SExt = AttributeId::SExt as u64,
StackProtect = AttributeId::StackProtect as u64,
StackProtectReq = AttributeId::StackProtectReq as u64,
StackProtectStrong = AttributeId::StackProtectStrong as u64,
StructRet = AttributeId::StructRet as u64,
SanitizeAddress = AttributeId::SanitizeAddress as u64,
SanitizeThread = AttributeId::SanitizeThread as u64,
SanitizeMemory = AttributeId::SanitizeMemory as u64,
UwTable = AttributeId::UwTable as u64,
ZExt = AttributeId::ZExt as u64,
Builtin = AttributeId::Builtin as u64,
Cold = AttributeId::Cold as u64,
OptimizeNone = AttributeId::OptimizeNone as u64,
InAlloca = AttributeId::InAlloca as u64,
NonNull = AttributeId::NonNull as u64,
JumpTable = AttributeId::JumpTable as u64,
Convergent = AttributeId::Convergent as u64,
SafeStack = AttributeId::SafeStack as u64,
ArgMemOnly = AttributeId::ArgMemOnly as u64,
SwiftSelf = AttributeId::SwiftSelf as u64,
SwiftError = AttributeId::SwiftError as u64,
NoRecurse = AttributeId::NoRecurse as u64,
InaccessiblememOnly = AttributeId::InaccessiblememOnly as u64,
InaccessiblememOrArgmemonly = AttributeId::InaccessiblememOrArgmemonly as u64,
WriteOnly = AttributeId::WriteOnly as u64,
Speculatable = AttributeId::Speculatable as u64,
StrictFp = AttributeId::StrictFp as u64,
SanitizeHwAddress = AttributeId::SanitizeHwAddress as u64,
NoCfCheck = AttributeId::NoCfCheck as u64,
OptForFuzzing = AttributeId::OptForFuzzing as u64,
Shadowcallstack = AttributeId::Shadowcallstack as u64,
SpeculativeLoadHardening = AttributeId::SpeculativeLoadHardening as u64,
ImmArg = AttributeId::ImmArg as u64,
WillReturn = AttributeId::WillReturn as u64,
NoFree = AttributeId::NoFree as u64,
NoSync = AttributeId::NoSync as u64,
SanitizeMemtag = AttributeId::SanitizeMemtag as u64,
Preallocated = AttributeId::Preallocated as u64,
NoMerge = AttributeId::NoMerge as u64,
NullPointerIsValid = AttributeId::NullPointerIsValid as u64,
NoUndef = AttributeId::NoUndef as u64,
ByRef = AttributeId::ByRef as u64,
MustProgress = AttributeId::MustProgress as u64,
NoCallback = AttributeId::NoCallback as u64,
Hot = AttributeId::Hot as u64,
NoProfile = AttributeId::NoProfile as u64,
SwiftAsync = AttributeId::SwiftAsync as u64,
NoSanitizeCoverage = AttributeId::NoSanitizeCoverage as u64,
ElementType = AttributeId::ElementType as u64,
DisableSanitizerInstrumentation = AttributeId::DisableSanitizerInstrumentation as u64,
}
impl TryFrom<AttributeId> for EnumAttribute {
type Error = AttributeError;
fn try_from(value: AttributeId) -> Result<Self, Self::Error> {
(value as u64)
.try_into()
.map_err(|_| AttributeError::AttributeMalformed("non-enum attribute ID given", value))
}
}
#[non_exhaustive]
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum IntAttribute {
Alignment(Align),
StackAlignment(Align),
Dereferenceable(u64),
DereferenceableOrNull(u64),
AllocSize(u32, Option<u32>),
VScaleRange(u32, u32),
}
impl TryFrom<(AttributeId, u64)> for IntAttribute {
type Error = AttributeError;
fn try_from((key, value): (AttributeId, u64)) -> Result<Self, Self::Error> {
if EnumAttribute::try_from(key).is_err() {
return Err(AttributeError::AttributeMalformed(
"expected int attribute, but given enum ID",
key,
));
}
Ok(match key {
AttributeId::Alignment => {
let value = u8::try_from(value).map_err(|_| {
AttributeError::AttributeMalformed(
"attribute value too large (invalid alignment)",
key,
)
})?;
IntAttribute::Alignment(
Align::from_shift(value).map_err(|_| {
AttributeError::AttributeMalformed("invalid alignment", key)
})?,
)
}
AttributeId::StackAlignment => {
let value = u8::try_from(value).map_err(|_| {
AttributeError::AttributeMalformed(
"attribute value too large (invalid alignment)",
key,
)
})?;
IntAttribute::StackAlignment(
Align::from_shift(value).map_err(|_| {
AttributeError::AttributeMalformed("invalid alignment", key)
})?,
)
}
AttributeId::Dereferenceable => IntAttribute::Dereferenceable(value),
AttributeId::DereferenceableOrNull => IntAttribute::DereferenceableOrNull(value),
AttributeId::AllocSize => {
if value == 0 {
return Err(AttributeError::AttributeMalformed(
"allocasize argument invalid: cannot be (0, 0)",
key,
));
}
let elt_size = (value >> 32) as u32;
let num_elts = match value as u32 {
u32::MAX => None,
num_elts => Some(num_elts),
};
IntAttribute::AllocSize(elt_size, num_elts)
}
AttributeId::VScaleRange => {
let min = (value >> 32) as u32;
let max = match value as u32 {
0 => min,
max => max,
};
IntAttribute::VScaleRange(max, min)
}
o => return Err(AttributeError::IntAttributeUnsupported(o)),
})
}
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq)]
pub enum Attribute {
Enum(EnumAttribute),
Int(IntAttribute),
Str(String),
StrKeyValue(String, String),
}
impl Attribute {
fn from_record(start: usize, record: &UnrolledRecord) -> Result<(usize, Self), AttributeError> {
let mut fieldcount = 0;
macro_rules! next {
() => {
if let Some(field) = record.fields().get(start + fieldcount) {
fieldcount += 1;
Ok(*field)
} else {
Err(AttributeError::TooShort)
}
};
}
macro_rules! take_string {
() => {{
let str_bytes = record.fields()[start + fieldcount..]
.iter()
.take_while(|f| **f != 0)
.map(|f| u8::try_from(*f))
.collect::<Result<Vec<_>, _>>()
.map_err(|_| AttributeError::BadString)?;
if str_bytes.is_empty() {
Err(AttributeError::BadString)
} else {
let result =
String::from_utf8(str_bytes).map_err(|_| AttributeError::BadString)?;
fieldcount += result.as_bytes().len() + 1;
Ok(result)
}
}};
}
let kind = AttributeKind::try_from(next!()?)?;
match kind {
AttributeKind::Enum => {
let key = AttributeId::try_from(next!()?)?;
Ok((fieldcount, Attribute::Enum(key.try_into()?)))
}
AttributeKind::IntKeyValue => {
let key = AttributeId::try_from(next!()?)?;
let value = next!()?;
Ok((fieldcount, Attribute::Int(TryInto::try_into((key, value))?)))
}
AttributeKind::StrKey => {
let key = take_string!()?;
Ok((fieldcount, Attribute::Str(key)))
}
AttributeKind::StrKeyValue => {
let key = take_string!()?;
let value = take_string!()?;
Ok((fieldcount, Attribute::StrKeyValue(key, value)))
}
}
}
}
#[derive(Debug)]
pub struct AttributeEntry(Vec<AttributeGroup>);
#[derive(Debug)]
pub struct Attributes(Vec<AttributeEntry>);
impl IrBlock for Attributes {
const BLOCK_ID: IrBlockId = IrBlockId::ParamAttr;
fn try_map_inner(block: &UnrolledBlock, ctx: &mut MapCtx) -> Result<Self, BlockMapError> {
let mut entries = vec![];
for record in block.all_records() {
let code = AttributeCode::try_from(record.code()).map_err(AttributeError::from)?;
match code {
AttributeCode::Entry => {
let mut groups = vec![];
for group_id in record.fields() {
let group_id = *group_id as u32;
log::debug!("group id: {}", group_id);
groups.push(
ctx.attribute_groups()?
.get(group_id)
.ok_or(AttributeError::BadAttributeGroup(group_id))?
.clone(),
);
}
entries.push(AttributeEntry(groups));
}
AttributeCode::GroupCodeEntry => {
return Err(AttributeError::WrongBlock(code).into());
}
_ => {
return Err(BlockMapError::Unsupported(format!(
"unsupported attribute block code: {:?}",
code,
)))
}
}
}
Ok(Attributes(entries))
}
}
#[derive(Clone, Copy, Debug)]
pub enum AttributeGroupDisposition {
Return,
Parameter(u32),
Function,
}
impl From<u32> for AttributeGroupDisposition {
fn from(value: u32) -> Self {
match value {
u32::MAX => Self::Function,
0 => Self::Return,
_ => Self::Parameter(value),
}
}
}
#[derive(Clone, Debug)]
pub struct AttributeGroup {
disposition: AttributeGroupDisposition,
attributes: Vec<Attribute>,
}
#[derive(Debug)]
pub struct AttributeGroups(HashMap<u32, AttributeGroup>);
impl AttributeGroups {
fn get(&self, group_id: u32) -> Option<&AttributeGroup> {
self.0.get(&group_id)
}
}
impl IrBlock for AttributeGroups {
const BLOCK_ID: IrBlockId = IrBlockId::ParamAttrGroup;
fn try_map_inner(block: &UnrolledBlock, _ctx: &mut MapCtx) -> Result<Self, BlockMapError> {
let mut groups = HashMap::new();
for record in block.all_records() {
let code = AttributeCode::try_from(record.code()).map_err(AttributeError::from)?;
if code != AttributeCode::GroupCodeEntry {
return Err(AttributeError::WrongBlock(code).into());
}
if record.fields().len() < 3 {
return Err(RecordMapError::BadRecordLayout(format!(
"too few fields in {:?}, expected {} >= 3",
code,
record.fields().len()
))
.into());
}
let group_id = record.fields()[0] as u32;
let disposition: AttributeGroupDisposition = (record.fields()[1] as u32).into();
let mut fieldidx = 2;
let mut attributes = vec![];
while fieldidx < record.fields().len() {
let (count, attr) = Attribute::from_record(fieldidx, record)?;
attributes.push(attr);
fieldidx += count;
}
if fieldidx != record.fields().len() {
return Err(RecordMapError::BadRecordLayout(format!(
"under/overconsumed fields in attribute group record ({} fields, {} consumed)",
fieldidx,
record.fields().len(),
))
.into());
}
groups.insert(
group_id,
AttributeGroup {
disposition,
attributes,
},
);
}
Ok(AttributeGroups(groups))
}
}