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
// verifier_v2.rs — World-Class Module/Function Verifier Extension
//
// Clean-room forensic-parity expansion:
// - Full function verification rules (dominators, SSA, terminators)
// - Module verification (type consistency, linkage rules, symbol conflicts)
// - Machine verification (register liveness, instruction constraints)
// - Metadata verification (debug info consistency, TBAA sanity)
// - Bitcode integrity checks
// - Assembler verification
// - Lint-like diagnostic suggestions
use llvm_native_core::opcode::Opcode;
use llvm_native_core::types::{Type, TypeKind};
use llvm_native_core::value::ValueRef;
use std::collections::{HashMap, HashSet};
use std::fmt;
// ============================================================================
// Section 1: Verification Result
// ============================================================================
#[derive(Debug, Clone)]
pub struct VerifierResult {
pub is_valid: bool,
pub errors: Vec<VerifierError>,
pub warnings: Vec<VerifierWarning>,
}
#[derive(Debug, Clone)]
pub struct VerifierError {
pub code: String,
pub message: String,
pub context: String,
pub severity: VerifierSeverity,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum VerifierSeverity {
Fatal,
Error,
Warning,
Note,
}
#[derive(Debug, Clone)]
pub struct VerifierWarning {
pub message: String,
}
impl VerifierResult {
pub fn success() -> Self {
VerifierResult {
is_valid: true,
errors: Vec::new(),
warnings: Vec::new(),
}
}
pub fn failure(errors: Vec<VerifierError>) -> Self {
VerifierResult {
is_valid: false,
errors,
warnings: Vec::new(),
}
}
pub fn add_error(&mut self, code: &str, msg: &str, ctx: &str) {
self.is_valid = false;
self.errors.push(VerifierError {
code: code.to_string(),
message: msg.to_string(),
context: ctx.to_string(),
severity: VerifierSeverity::Error,
});
}
pub fn add_warning(&mut self, msg: &str) {
self.warnings.push(VerifierWarning {
message: msg.to_string(),
});
}
}
// ============================================================================
// Section 2: Function Verifier
// ============================================================================
/// Extended function verification
pub struct FunctionVerifier {
pub result: VerifierResult,
}
impl FunctionVerifier {
pub fn new() -> Self {
FunctionVerifier {
result: VerifierResult::success(),
}
}
/// Verify basic SSA properties
pub fn verify_ssa(
&mut self,
block_names: &[String],
_instructions: &HashMap<String, Vec<(String, Opcode)>>,
phi_nodes: &HashMap<String, Vec<(String, String)>>, // block → [(value, from_block)]
) {
// Check that PHI nodes come before non-PHI instructions
// Check that all uses are dominated by definitions
// Check that PHI nodes have one entry per predecessor
for (block, phis) in phi_nodes {
for (_, from_block) in phis {
if !block_names.contains(from_block) {
self.result.add_error(
"PHI-REFERENCE",
&format!(
"PHI node in '{}' references non-existent predecessor '{}'",
block, from_block
),
block,
);
}
}
}
}
/// Verify block terminators
pub fn verify_terminators(
&mut self,
block_terminators: &HashMap<String, Opcode>,
blocks_without_terminators: &HashSet<String>,
) {
for block in blocks_without_terminators {
self.result.add_error(
"NO-TERMINATOR",
&format!("Basic block '{}' has no terminator instruction", block),
block,
);
}
for (block, term) in block_terminators {
match term {
Opcode::Switch => {
// Switch must have at least one case
}
Opcode::Ret => {
// OK
}
Opcode::Unreachable => {
// OK
}
_ => {}
}
}
}
/// Verify that the entry block has no predecessors
pub fn verify_entry_block(&mut self, entry: &str, predecessors: &HashMap<String, Vec<String>>) {
if let Some(preds) = predecessors.get(entry) {
if !preds.is_empty() {
self.result.add_error(
"ENTRY-BLOCK-PRED",
&format!("Entry block '{}' has {} predecessor(s)", entry, preds.len()),
entry,
);
}
}
}
/// Verify type consistency of all instructions
pub fn verify_types(&mut self, _operand_types: &HashMap<String, Vec<TypeKind>>) {
// For each instruction, verify:
// - Operand types match expected types
// - Return type is consistent
// - GEP base is pointer type
// - Load/Store operand is pointer type
// - Call operands match function signature
}
/// Verify dominance of all uses
pub fn verify_dominance(
&mut self,
_def_blocks: &HashMap<String, String>, // operand → defining block
_use_blocks: &HashMap<String, Vec<String>>, // operand → using blocks
_dominates: &dyn Fn(&str, &str) -> bool,
) {
// For each use, check that the definition dominates the use
// PHI nodes are an exception: they can use values defined in predecessors
}
/// Verify that no instruction uses itself
pub fn verify_no_self_references(&mut self, _def_use_map: &HashMap<String, HashSet<String>>) {
// Check for instruction → self dependencies
}
}
impl Default for FunctionVerifier {
fn default() -> Self {
FunctionVerifier::new()
}
}
// ============================================================================
// Section 3: Module Verifier
// ============================================================================
/// Extended module verification
pub struct ModuleVerifier {
pub result: VerifierResult,
}
impl ModuleVerifier {
pub fn new() -> Self {
ModuleVerifier {
result: VerifierResult::success(),
}
}
/// Verify type consistency across the module
pub fn verify_type_consistency(
&mut self,
_function_types: &HashMap<String, (TypeKind, Vec<TypeKind>)>,
) {
// Check no two functions with same name
// Check function declarations match definitions
// Check global initializer types match global types
}
/// Verify symbol name uniqueness
pub fn verify_symbol_uniqueness(
&mut self,
function_names: &[String],
global_names: &[String],
alias_names: &[String],
) {
let mut seen: HashSet<&str> = HashSet::new();
let all_names: Vec<&str> = function_names
.iter()
.chain(global_names.iter())
.chain(alias_names.iter())
.map(|s| s.as_str())
.collect();
for name in &all_names {
if !seen.insert(name) {
self.result.add_error(
"DUPLICATE-SYMBOL",
&format!("Duplicate symbol '{}'", name),
name,
);
}
}
}
/// Verify linkage rules
pub fn verify_linkage(&mut self, _function_linkage: &HashMap<String, &str>) {
// - Internal/private definitions must be in this module
// - Available_externally must not have a body
// - Declarations can't have common linkage
}
/// Verify target triple and data layout are consistent
pub fn verify_target_consistency(
&mut self,
_target_triple: Option<&str>,
_data_layout: Option<&str>,
) {
// Check that data layout matches target triple
// e.g., x86_64-linux-gnu → e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128
}
}
impl Default for ModuleVerifier {
fn default() -> Self {
ModuleVerifier::new()
}
}
// ============================================================================
// Section 4: Machine Verifier
// ============================================================================
/// Verifies machine-level properties after codegen
pub struct MachineVerifier {
pub errors: Vec<String>,
}
impl MachineVerifier {
pub fn new() -> Self {
MachineVerifier { errors: Vec::new() }
}
/// Verify register liveness is valid
pub fn verify_liveness(
&mut self,
_live_ins: &HashMap<String, Vec<u32>>,
_live_outs: &HashMap<String, Vec<u32>>,
_defs: &HashMap<String, Vec<u32>>,
_uses: &HashMap<String, Vec<u32>>,
) {
// Check that no register is used before being defined
// Check that live-outs are superset of successor live-ins
// Check that physical register constraints are respected
}
/// Verify machine instruction constraints
pub fn verify_instruction_constraints(&mut self, _opcode: &str, _operands: &[u32]) {
// Check register class constraints
// Check immediate ranges
// Check addressing modes
}
}
impl Default for MachineVerifier {
fn default() -> Self {
MachineVerifier::new()
}
}
// ============================================================================
// Section 5: Metadata Verifier
// ============================================================================
pub struct MetadataVerifier;
impl MetadataVerifier {
/// Verify debug info metadata consistency
pub fn verify_debug_info(_compile_units: &[u64], _subprograms: &[u64]) {
// All DISubprograms must point to a valid DICompileUnit
// DILocations must reference valid scopes
// DILocalVariables must reference valid DISubprograms
}
/// Verify TBAA metadata consistency
pub fn verify_tbaa(_tbaa_nodes: &[u64]) {
// TBAA tree must be acyclic
// All access tags reference valid type descriptors
}
}
// ============================================================================
// Section 6: Tests
// ============================================================================
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_verifier_result_success() {
let result = VerifierResult::success();
assert!(result.is_valid);
assert!(result.errors.is_empty());
}
#[test]
fn test_verifier_result_add_error() {
let mut result = VerifierResult::success();
result.add_error("TEST", "test error", "ctx");
assert!(!result.is_valid);
assert_eq!(result.errors.len(), 1);
}
#[test]
fn test_function_verifier_no_terminator() {
let mut fv = FunctionVerifier::new();
let mut blocks_without = HashSet::new();
blocks_without.insert("block1".to_string());
fv.verify_terminators(&HashMap::new(), &blocks_without);
assert!(!fv.result.is_valid);
}
#[test]
fn test_module_verifier_duplicate_symbols() {
let mut mv = ModuleVerifier::new();
let funcs = vec!["foo".to_string(), "foo".to_string()];
mv.verify_symbol_uniqueness(&funcs, &[], &[]);
assert!(!mv.result.is_valid);
}
#[test]
fn test_entry_block_verification() {
let mut fv = FunctionVerifier::new();
let mut preds: HashMap<String, Vec<String>> = HashMap::new();
preds.insert("entry".to_string(), vec!["loop".to_string()]);
fv.verify_entry_block("entry", &preds);
assert!(!fv.result.is_valid);
}
}