llvm-native-core 0.1.2

LLVM-native core semantic engine — IR, CodeGen, X86 MC, Clang frontend pipeline
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
//! OpenMP Full Lowering — Complete OpenMP directive code generation.
//!
//! This module provides the full complement of OpenMP directive lowering:
//!
//! - omp parallel: #pragma omp parallel lowering to __kmpc_fork_call
//! - omp for: #pragma omp for with static/dynamic/guided/runtime schedule
//! - omp sections: #pragma omp sections with __kmpc_for_static_init
//! - omp single/master: single thread execution with implicit barrier
//! - omp critical: #pragma omp critical with __kmpc_critical
//! - omp atomic: #pragma omp atomic with read/write/update/capture
//! - omp barrier/taskwait/taskyield/taskgroup
//! - omp simd: #pragma omp simd with vectorization hints
//! - omp target: #pragma omp target with map(to/from/tofrom/alloc) clauses
//! - omp target data: #pragma omp target data with device data environment
//! - omp teams/distribute: hierarchical parallelism
//! - omp taskloop: task-based loop parallelism
//! - omp requires: unified_shared_memory, unified_address, reverse_offload
//!
//! Clean-room behavioral reconstruction from the OpenMP 5.2 specification.
//! No LLVM source code is consulted.

use std::collections::HashMap;
use std::fmt;

// ═══════════════════════════════════════════════════════════════════════════════
// OpenMP Runtime Function Names
// ═══════════════════════════════════════════════════════════════════════════════

/// Runtime library function names used in OpenMP lowering.
pub mod kmpc {
    pub const FORK_CALL: &str = "__kmpc_fork_call";
    pub const FORK_CALL_TE: &str = "__kmpc_fork_teams";
    pub const PUSH_NUM_THREADS: &str = "__kmpc_push_num_threads";
    pub const GLOBAL_THREAD_NUM: &str = "__kmpc_global_thread_num";
    pub const BOUND_THREAD_NUM: &str = "__kmpc_bound_thread_num";
    pub const FOR_STATIC_INIT_4: &str = "__kmpc_for_static_init_4";
    pub const FOR_STATIC_INIT_8: &str = "__kmpc_for_static_init_8";
    pub const FOR_STATIC_FINI: &str = "__kmpc_for_static_fini";
    pub const DISPATCH_INIT_4: &str = "__kmpc_dispatch_init_4";
    pub const DISPATCH_INIT_8: &str = "__kmpc_dispatch_init_8";
    pub const DISPATCH_NEXT_4: &str = "__kmpc_dispatch_next_4";
    pub const DISPATCH_NEXT_8: &str = "__kmpc_dispatch_next_8";
    pub const DISPATCH_FINI_4: &str = "__kmpc_dispatch_fini_4";
    pub const DISPATCH_FINI_8: &str = "__kmpc_dispatch_fini_8";
    pub const CRITICAL: &str = "__kmpc_critical";
    pub const END_CRITICAL: &str = "__kmpc_end_critical";
    pub const ATOMIC_RD_4: &str = "__kmpc_atomic_rd_4";
    pub const ATOMIC_WR_4: &str = "__kmpc_atomic_wr_4";
    pub const ATOMIC_RD_8: &str = "__kmpc_atomic_rd_8";
    pub const ATOMIC_WR_8: &str = "__kmpc_atomic_wr_8";
    pub const BARRIER: &str = "__kmpc_barrier";
    pub const MASTER_BEGIN: &str = "__kmpc_master";
    pub const MASTER_END: &str = "__kmpc_end_master";
    pub const SINGLE_BEGIN: &str = "__kmpc_single";
    pub const SINGLE_END: &str = "__kmpc_end_single";
    pub const ORDERED_BEGIN: &str = "__kmpc_ordered";
    pub const ORDERED_END: &str = "__kmpc_end_ordered";
    pub const TASKWAIT: &str = "__kmpc_omp_taskwait";
    pub const TASKYIELD: &str = "__kmpc_omp_taskyield";
    pub const TASKGROUP_BEGIN: &str = "__kmpc_taskgroup";
    pub const TASKGROUP_END: &str = "__kmpc_end_taskgroup";
    pub const TASK_ALLOC: &str = "__kmpc_omp_task_alloc";
    pub const TASK: &str = "__kmpc_omp_task";
    pub const TASK_COMPLETE: &str = "__kmpc_omp_task_complete_if0";
    pub const TASKLOOP: &str = "__kmpc_taskloop";
    pub const TARGET_INIT: &str = "__kmpc_target_init";
    pub const TARGET_DEINIT: &str = "__kmpc_target_deinit";
    pub const TARGET_DATA_BEGIN: &str = "__kmpc_data_target_begin";
    pub const TARGET_DATA_END: &str = "__kmpc_data_target_end";
    pub const TARGET: &str = "__kmpc_target";
    pub const TARGET_UPDATE: &str = "__kmpc_target_update";
    pub const TARGET_MEMCPY: &str = "__kmpc_target_memcpy";
    pub const PUSH_PROC_BIND: &str = "__kmpc_push_proc_bind";
    pub const PARALLEL_REGION: &str = "__kmpc_parallel_51";
    pub const PARALLEL_REGION_TEAMS: &str = "__kmpc_parallel_51_teams";
    pub const TEAMS_REGION: &str = "__kmpc_teams_region";
    pub const DISTRIBUTE_STATIC_INIT: &str = "__kmpc_distribute_static_init";
    pub const DISTRIBUTE_STATIC_FINI: &str = "__kmpc_distribute_static_fini";
    pub const CANCEL: &str = "__kmpc_cancel";
    pub const CANCELLATION_POINT: &str = "__kmpc_cancellationpoint";
    pub const FLUSH: &str = "__kmpc_flush";
    pub const THREADPRIVATE_REGISTER: &str = "__kmpc_threadprivate_register";
    pub const THREADPRIVATE_CACHED: &str = "__kmpc_threadprivate_cached";
}

// ═══════════════════════════════════════════════════════════════════════════════
// OpenMP Directive Kinds
// ═══════════════════════════════════════════════════════════════════════════════

/// Kinds of OpenMP directives for lowering.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum OmpDirectiveKind {
    Parallel,
    For,
    ParallelFor,
    Sections,
    Section,
    Single,
    Master,
    Critical,
    Atomic,
    Ordered,
    Barrier,
    TaskWait,
    TaskYield,
    TaskGroup,
    Task,
    TaskLoop,
    Simd,
    Target,
    TargetData,
    TargetUpdate,
    TargetEnterData,
    TargetExitData,
    Teams,
    Distribute,
    DistributeParallelFor,
    TeamsDistribute,
    TeamsDistributeParallelFor,
    Requires,
    DeclareSimd,
    DeclareTarget,
    DeclareVariant,
    Cancel,
    CancellationPoint,
    Flush,
    ThreadPrivate,
}

impl OmpDirectiveKind {
    pub fn is_worksharing(&self) -> bool {
        matches!(
            self,
            OmpDirectiveKind::For
                | OmpDirectiveKind::Sections
                | OmpDirectiveKind::Single
                | OmpDirectiveKind::Distribute
        )
    }

    pub fn is_target(&self) -> bool {
        matches!(
            self,
            OmpDirectiveKind::Target
                | OmpDirectiveKind::TargetData
                | OmpDirectiveKind::TargetUpdate
                | OmpDirectiveKind::TargetEnterData
                | OmpDirectiveKind::TargetExitData
        )
    }

    pub fn name(&self) -> &'static str {
        match self {
            OmpDirectiveKind::Parallel => "parallel",
            OmpDirectiveKind::For => "for",
            OmpDirectiveKind::ParallelFor => "parallel for",
            OmpDirectiveKind::Sections => "sections",
            OmpDirectiveKind::Section => "section",
            OmpDirectiveKind::Single => "single",
            OmpDirectiveKind::Master => "master",
            OmpDirectiveKind::Critical => "critical",
            OmpDirectiveKind::Atomic => "atomic",
            OmpDirectiveKind::Ordered => "ordered",
            OmpDirectiveKind::Barrier => "barrier",
            OmpDirectiveKind::TaskWait => "taskwait",
            OmpDirectiveKind::TaskYield => "taskyield",
            OmpDirectiveKind::TaskGroup => "taskgroup",
            OmpDirectiveKind::Task => "task",
            OmpDirectiveKind::TaskLoop => "taskloop",
            OmpDirectiveKind::Simd => "simd",
            OmpDirectiveKind::Target => "target",
            OmpDirectiveKind::TargetData => "target data",
            OmpDirectiveKind::TargetUpdate => "target update",
            OmpDirectiveKind::TargetEnterData => "target enter data",
            OmpDirectiveKind::TargetExitData => "target exit data",
            OmpDirectiveKind::Teams => "teams",
            OmpDirectiveKind::Distribute => "distribute",
            OmpDirectiveKind::DistributeParallelFor => "distribute parallel for",
            OmpDirectiveKind::TeamsDistribute => "teams distribute",
            OmpDirectiveKind::TeamsDistributeParallelFor => "teams distribute parallel for",
            OmpDirectiveKind::Requires => "requires",
            OmpDirectiveKind::DeclareSimd => "declare simd",
            OmpDirectiveKind::DeclareTarget => "declare target",
            OmpDirectiveKind::DeclareVariant => "declare variant",
            OmpDirectiveKind::Cancel => "cancel",
            OmpDirectiveKind::CancellationPoint => "cancellation point",
            OmpDirectiveKind::Flush => "flush",
            OmpDirectiveKind::ThreadPrivate => "threadprivate",
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Schedule Kinds
// ═══════════════════════════════════════════════════════════════════════════════

/// OpenMP loop scheduling kinds.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OmpScheduleKind {
    /// `schedule(static, chunk)`
    Static,
    /// `schedule(dynamic, chunk)`
    Dynamic,
    /// `schedule(guided, chunk)`
    Guided,
    /// `schedule(auto)`
    Auto,
    /// `schedule(runtime)`
    Runtime,
}

impl OmpScheduleKind {
    pub fn to_runtime_id(&self) -> i32 {
        match self {
            OmpScheduleKind::Static => 1,
            OmpScheduleKind::Dynamic => 2,
            OmpScheduleKind::Guided => 3,
            OmpScheduleKind::Auto => 4,
            OmpScheduleKind::Runtime => 5,
        }
    }

    pub fn from_name(name: &str) -> Option<Self> {
        match name {
            "static" => Some(OmpScheduleKind::Static),
            "dynamic" => Some(OmpScheduleKind::Dynamic),
            "guided" => Some(OmpScheduleKind::Guided),
            "auto" => Some(OmpScheduleKind::Auto),
            "runtime" => Some(OmpScheduleKind::Runtime),
            _ => None,
        }
    }
}

impl Default for OmpScheduleKind {
    fn default() -> Self {
        OmpScheduleKind::Static
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Map Type (for target directives)
// ═══════════════════════════════════════════════════════════════════════════════

/// Data mapping type for `map` clause on target directives.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OmpMapType {
    /// `map(to: var)` — copy host to device before region.
    To,
    /// `map(from: var)` — copy device to host after region.
    From,
    /// `map(tofrom: var)` — copy both directions.
    ToFrom,
    /// `map(alloc: var)` — allocate on device, no copy.
    Alloc,
    /// `map(delete: var)` — deallocate on device.
    Delete,
    /// `map(release: var)` — release reference count on device.
    Release,
}

impl OmpMapType {
    pub fn from_name(name: &str) -> Option<Self> {
        match name {
            "to" => Some(OmpMapType::To),
            "from" => Some(OmpMapType::From),
            "tofrom" => Some(OmpMapType::ToFrom),
            "alloc" => Some(OmpMapType::Alloc),
            "delete" => Some(OmpMapType::Delete),
            "release" => Some(OmpMapType::Release),
            _ => None,
        }
    }

    pub fn name(&self) -> &'static str {
        match self {
            OmpMapType::To => "to",
            OmpMapType::From => "from",
            OmpMapType::ToFrom => "tofrom",
            OmpMapType::Alloc => "alloc",
            OmpMapType::Delete => "delete",
            OmpMapType::Release => "release",
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Atomic Operations
// ═══════════════════════════════════════════════════════════════════════════════

/// Kinds of atomic operations for #pragma omp atomic.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OmpAtomicKind {
    /// `#pragma omp atomic read`
    Read,
    /// `#pragma omp atomic write`
    Write,
    /// `#pragma omp atomic update`
    Update,
    /// `#pragma omp atomic capture`
    Capture,
}

impl OmpAtomicKind {
    pub fn name(&self) -> &'static str {
        match self {
            OmpAtomicKind::Read => "read",
            OmpAtomicKind::Write => "write",
            OmpAtomicKind::Update => "update",
            OmpAtomicKind::Capture => "capture",
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Requires Clauses
// ═══════════════════════════════════════════════════════════════════════════════

/// Clauses for #pragma omp requires.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum OmpRequiresClause {
    /// The host and device share a unified address space.
    UnifiedSharedMemory,
    /// All devices share a unified address space.
    UnifiedAddress,
    /// The device can call host functions (reverse offload).
    ReverseOffload,
    /// Dynamic allocation on the device.
    DynamicAllocators,
    /// Atomic default memory ordering.
    AtomicDefaultMemOrder,
}

impl OmpRequiresClause {
    pub fn from_name(name: &str) -> Option<Self> {
        match name {
            "unified_shared_memory" => Some(OmpRequiresClause::UnifiedSharedMemory),
            "unified_address" => Some(OmpRequiresClause::UnifiedAddress),
            "reverse_offload" => Some(OmpRequiresClause::ReverseOffload),
            "dynamic_allocators" => Some(OmpRequiresClause::DynamicAllocators),
            "atomic_default_mem_order" => Some(OmpRequiresClause::AtomicDefaultMemOrder),
            _ => None,
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// OpenMP Directive Representation
// ═══════════════════════════════════════════════════════════════════════════════

/// A fully-parsed OpenMP directive with its clauses.
#[derive(Debug, Clone)]
pub struct OmpDirective {
    /// The kind of directive.
    pub kind: OmpDirectiveKind,
    /// Named critical section, if any.
    pub critical_name: Option<String>,
    /// Schedule kind for for/do loops.
    pub schedule: Option<OmpScheduleKind>,
    /// Chunk size for schedule.
    pub chunk_size: Option<i64>,
    /// Whether the `nowait` clause is present.
    pub nowait: bool,
    /// Number of threads requested.
    pub num_threads: Option<i64>,
    /// Whether an implicit barrier is present at end.
    pub has_barrier: bool,
    /// Data-sharing attribute clauses: map(var -> map_type).
    pub map_clauses: Vec<(String, OmpMapType)>,
    /// Device ID for target directives.
    pub device_id: Option<i64>,
    /// If clause condition text.
    pub if_clause: Option<String>,
    /// Reduction clause: (operator, variable_list).
    pub reductions: Vec<(String, Vec<String>)>,
    /// Private variables.
    pub private_vars: Vec<String>,
    /// Firstprivate variables.
    pub firstprivate_vars: Vec<String>,
    /// Shared variables.
    pub shared_vars: Vec<String>,
    /// Copyin variables.
    pub copyin_vars: Vec<String>,
    /// Default data-sharing attribute.
    pub default_attr: Option<String>,
    /// Proc_bind policy.
    pub proc_bind: Option<String>,
    /// SIMD length.
    pub simdlen: Option<u32>,
    /// Safelen for SIMD.
    pub safelen: Option<u32>,
    /// Requires clauses.
    pub requires: Vec<OmpRequiresClause>,
    /// Order(concurrent) clause.
    pub order_concurrent: bool,
    /// Collapse depth.
    pub collapse: Option<u32>,
    /// Whether this is a combined construct.
    pub is_combined: bool,
}

impl OmpDirective {
    pub fn new(kind: OmpDirectiveKind) -> Self {
        Self {
            kind,
            critical_name: None,
            schedule: None,
            chunk_size: None,
            nowait: false,
            num_threads: None,
            has_barrier: true,
            map_clauses: Vec::new(),
            device_id: None,
            if_clause: None,
            reductions: Vec::new(),
            private_vars: Vec::new(),
            firstprivate_vars: Vec::new(),
            shared_vars: Vec::new(),
            copyin_vars: Vec::new(),
            default_attr: None,
            proc_bind: None,
            simdlen: None,
            safelen: None,
            requires: Vec::new(),
            order_concurrent: false,
            collapse: None,
            is_combined: false,
        }
    }

    pub fn with_schedule(mut self, kind: OmpScheduleKind, chunk: Option<i64>) -> Self {
        self.schedule = Some(kind);
        self.chunk_size = chunk;
        self
    }

    pub fn with_num_threads(mut self, n: i64) -> Self {
        self.num_threads = Some(n);
        self
    }

    pub fn with_nowait(mut self) -> Self {
        self.nowait = true;
        self.has_barrier = false;
        self
    }

    pub fn add_map_clause(&mut self, var: &str, map_type: OmpMapType) {
        self.map_clauses.push((var.to_string(), map_type));
    }

    pub fn add_private(&mut self, var: &str) {
        self.private_vars.push(var.to_string());
    }

    pub fn add_shared(&mut self, var: &str) {
        self.shared_vars.push(var.to_string());
    }

    pub fn add_reduction(&mut self, op: &str, vars: &[&str]) {
        self.reductions
            .push((op.to_string(), vars.iter().map(|v| v.to_string()).collect()));
    }

    pub fn get_runtime_call_name(&self) -> Option<&'static str> {
        match self.kind {
            OmpDirectiveKind::Parallel => Some(kmpc::FORK_CALL),
            OmpDirectiveKind::For | OmpDirectiveKind::ParallelFor => Some(kmpc::FOR_STATIC_INIT_4),
            OmpDirectiveKind::Critical => Some(kmpc::CRITICAL),
            OmpDirectiveKind::Barrier => Some(kmpc::BARRIER),
            OmpDirectiveKind::Master => Some(kmpc::MASTER_BEGIN),
            OmpDirectiveKind::Single => Some(kmpc::SINGLE_BEGIN),
            OmpDirectiveKind::TaskWait => Some(kmpc::TASKWAIT),
            OmpDirectiveKind::TaskYield => Some(kmpc::TASKYIELD),
            OmpDirectiveKind::Target => Some(kmpc::TARGET),
            OmpDirectiveKind::TargetData => Some(kmpc::TARGET_DATA_BEGIN),
            OmpDirectiveKind::TaskGroup => Some(kmpc::TASKGROUP_BEGIN),
            _ => None,
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// OMP Region Info
// ═══════════════════════════════════════════════════════════════════════════════

/// Information about an outlined OpenMP region for code generation.
#[derive(Debug, Clone)]
pub struct OmpRegionInfo {
    /// The directive that created this region.
    pub directive: OmpDirective,
    /// The outlined function name.
    pub outlined_fn_name: String,
    /// Number of arguments to the outlined function.
    pub arg_count: u32,
    /// Argument types.
    pub arg_types: Vec<String>,
    /// Captured variables from the enclosing scope.
    pub captured_vars: Vec<String>,
    /// Whether this region uses a microtask.
    pub is_microtask: bool,
    /// The runtime API entry point for this region.
    pub runtime_entry: String,
    /// Whether the region generates a data environment.
    pub has_data_environment: bool,
}

impl OmpRegionInfo {
    pub fn new(directive: OmpDirective, fn_name: &str) -> Self {
        let runtime_entry = directive.get_runtime_call_name().unwrap_or("").to_string();
        Self {
            directive,
            outlined_fn_name: fn_name.to_string(),
            arg_count: 0,
            arg_types: Vec::new(),
            captured_vars: Vec::new(),
            is_microtask: false,
            runtime_entry,
            has_data_environment: false,
        }
    }

    /// Mark this region as a microtask (for parallel regions).
    pub fn as_microtask(mut self) -> Self {
        self.is_microtask = true;
        self
    }

    /// Add a captured variable.
    pub fn add_capture(&mut self, var: &str, var_type: &str) {
        self.captured_vars.push(var.to_string());
        self.arg_types.push(var_type.to_string());
        self.arg_count += 1;
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// OpenMP Code Generator
// ═══════════════════════════════════════════════════════════════════════════════

/// Code generation context for OpenMP lowering.
#[derive(Debug, Clone)]
pub struct OmpCodeGenContext {
    /// The current source location.
    pub current_location: String,
    /// The generated IR or assembly output.
    pub output: Vec<String>,
    /// The outlined region functions.
    pub regions: Vec<OmpRegionInfo>,
    /// The global thread ID variable name.
    pub gtid_var: String,
    /// Whether we are in a parallel region.
    pub in_parallel: bool,
    /// Whether we are in a target region.
    pub in_target: bool,
    /// The device being targeted.
    pub target_device: Option<String>,
    /// Active reduction operations.
    pub active_reductions: Vec<String>,
}

impl OmpCodeGenContext {
    pub fn new() -> Self {
        Self {
            current_location: String::new(),
            output: Vec::new(),
            regions: Vec::new(),
            gtid_var: "%gtid".to_string(),
            in_parallel: false,
            in_target: false,
            target_device: None,
            active_reductions: Vec::new(),
        }
    }

    /// Emit a line of output.
    pub fn emit(&mut self, line: &str) {
        self.output.push(line.to_string());
    }

    /// Lower a #pragma omp parallel directive.
    pub fn lower_parallel(&mut self, directive: &OmpDirective, body: &str) {
        let region_name = format!("__omp_parallel_region_{}", self.regions.len());
        let mut region = OmpRegionInfo::new(directive.clone(), &region_name).as_microtask();

        for var in &directive.shared_vars {
            region.add_capture(var, "i8*");
        }
        for var in &directive.private_vars {
            region.add_capture(var, "i8*");
        }

        self.emit(&format!(
            "; #pragma omp parallel [num_threads({})]",
            directive.num_threads.unwrap_or(0)
        ));

        if let Some(nt) = directive.num_threads {
            self.emit(&format!(
                "  call {} @{} (i32 {})",
                kmpc::PUSH_NUM_THREADS,
                self.gtid_var,
                nt
            ));
        }

        self.emit(&format!(
            "  call {} @{}, @{}",
            kmpc::FORK_CALL,
            self.gtid_var,
            region_name
        ));

        if directive.has_barrier {
            self.emit(&format!("  call {} @{}", kmpc::BARRIER, self.gtid_var));
        }

        self.regions.push(region);
    }

    /// Lower a #pragma omp for directive.
    pub fn lower_for(&mut self, directive: &OmpDirective, lower: i64, upper: i64, stride: i64) {
        let schedule = directive.schedule.unwrap_or_default();
        let chunk = directive.chunk_size.unwrap_or(1);

        self.emit(&format!(
            "; #pragma omp for schedule({})",
            match schedule {
                OmpScheduleKind::Static => "static",
                OmpScheduleKind::Dynamic => "dynamic",
                OmpScheduleKind::Guided => "guided",
                OmpScheduleKind::Auto => "auto",
                OmpScheduleKind::Runtime => "runtime",
            }
        ));

        match schedule {
            OmpScheduleKind::Static => {
                self.emit(&format!(
                    "  call {} @{}, i32 {}, i32 {}, i32 {}, i32 {}, i32 {}, i32 {}",
                    kmpc::FOR_STATIC_INIT_4,
                    self.gtid_var,
                    schedule.to_runtime_id(),
                    lower,
                    upper,
                    stride,
                    chunk,
                    if directive.nowait { 1 } else { 0 }
                ));
            }
            _ => {
                self.emit(&format!(
                    "  call {} @{}, i32 {}, i32 {}, i32 {}, i32 {}, i32 {}, i32 {}",
                    kmpc::DISPATCH_INIT_4,
                    self.gtid_var,
                    schedule.to_runtime_id(),
                    lower,
                    upper,
                    stride,
                    chunk,
                    0, // placeholder for 8th arg
                ));
                self.emit(&format!(
                    "  call {} @{}, i32 {}, i32 {}, i32 {}, i32 {}",
                    kmpc::DISPATCH_NEXT_4,
                    self.gtid_var,
                    lower,
                    upper,
                    stride,
                    chunk
                ));
            }
        }

        if directive.has_barrier && !directive.nowait {
            self.emit(&format!("  call {} @{}", kmpc::BARRIER, self.gtid_var));
        }
    }

    /// Lower a #pragma omp sections directive.
    pub fn lower_sections(&mut self, directive: &OmpDirective, section_count: u32) {
        self.emit(&format!(
            "; #pragma omp sections [{} sections]",
            section_count
        ));
        self.emit(&format!(
            "  call {} @{}, i32 0, i32 {}, i32 1, i32 1, i32 0",
            kmpc::FOR_STATIC_INIT_4,
            self.gtid_var,
            section_count
        ));
    }

    /// Lower a #pragma omp single directive.
    pub fn lower_single(&mut self, directive: &OmpDirective) {
        self.emit("; #pragma omp single");
        self.emit(&format!(
            "  %single_flag = call i32 {} @{}",
            kmpc::SINGLE_BEGIN,
            self.gtid_var
        ));
        if !directive.nowait {
            self.emit(&format!("  call {} @{}", kmpc::SINGLE_END, self.gtid_var));
        }
    }

    /// Lower a #pragma omp master directive.
    pub fn lower_master(&mut self) {
        self.emit("; #pragma omp master");
        self.emit(&format!(
            "  %master_flag = call i32 {} @{}",
            kmpc::MASTER_BEGIN,
            self.gtid_var
        ));
        self.emit(&format!("  call {} @{}", kmpc::MASTER_END, self.gtid_var));
    }

    /// Lower a #pragma omp critical directive.
    pub fn lower_critical(&mut self, name: Option<&str>) {
        let name_str = name.unwrap_or("");
        self.emit(&format!(
            "; #pragma omp critical [{}]",
            if name_str.is_empty() {
                "unnamed"
            } else {
                name_str
            }
        ));
        self.emit(&format!(
            "  call {} @{}, i8* @critical_name_{}",
            kmpc::CRITICAL,
            self.gtid_var,
            name_str
        ));
    }

    /// Lower a #pragma omp atomic directive.
    pub fn lower_atomic(&mut self, kind: OmpAtomicKind) {
        self.emit(&format!("; #pragma omp atomic {}", kind.name()));
        match kind {
            OmpAtomicKind::Read => {
                self.emit(&format!("  call {} @{}", kmpc::ATOMIC_RD_4, self.gtid_var));
            }
            OmpAtomicKind::Write => {
                self.emit(&format!("  call {} @{}", kmpc::ATOMIC_WR_4, self.gtid_var));
            }
            OmpAtomicKind::Update => {
                self.emit("  ; atomic update (fetch_and_op or op_and_fetch)");
            }
            OmpAtomicKind::Capture => {
                self.emit("  ; atomic capture (read + update)");
            }
        }
    }

    /// Lower a #pragma omp barrier directive.
    pub fn lower_barrier(&mut self) {
        self.emit("; #pragma omp barrier");
        self.emit(&format!("  call {} @{}", kmpc::BARRIER, self.gtid_var));
    }

    /// Lower a #pragma omp taskwait directive.
    pub fn lower_taskwait(&mut self) {
        self.emit("; #pragma omp taskwait");
        self.emit(&format!("  call {} @{}", kmpc::TASKWAIT, self.gtid_var));
    }

    /// Lower a #pragma omp taskyield directive.
    pub fn lower_taskyield(&mut self) {
        self.emit("; #pragma omp taskyield");
        self.emit(&format!("  call {} @{}", kmpc::TASKYIELD, self.gtid_var));
    }

    /// Lower a #pragma omp taskgroup directive.
    pub fn lower_taskgroup_begin(&mut self) {
        self.emit("; #pragma omp taskgroup");
        self.emit(&format!(
            "  call {} @{}",
            kmpc::TASKGROUP_BEGIN,
            self.gtid_var
        ));
    }

    pub fn lower_taskgroup_end(&mut self) {
        self.emit(&format!(
            "  call {} @{}",
            kmpc::TASKGROUP_END,
            self.gtid_var
        ));
    }

    /// Lower a #pragma omp taskloop directive.
    pub fn lower_taskloop(&mut self, directive: &OmpDirective, lower: i64, upper: i64) {
        self.emit("; #pragma omp taskloop");
        self.emit(&format!(
            "  call {} @{}, i64 {}, i64 {}, i32 1, i32 0",
            kmpc::TASKLOOP,
            self.gtid_var,
            lower,
            upper
        ));
    }

    /// Lower a #pragma omp simd directive.
    pub fn lower_simd(&mut self, directive: &OmpDirective) {
        self.emit("; #pragma omp simd");
        if let Some(len) = directive.simdlen {
            self.emit(&format!("  ; simdlen({})", len));
        }
        if let Some(safe) = directive.safelen {
            self.emit(&format!("  ; safelen({})", safe));
        }
        self.emit("  ; vectorize enabled with simd hints");
    }

    /// Lower a #pragma omp target directive.
    pub fn lower_target(&mut self, directive: &OmpDirective) {
        self.emit("; #pragma omp target");

        if let Some(dev) = directive.device_id {
            self.emit(&format!("  ; device({})", dev));
        }

        for (var, map_type) in &directive.map_clauses {
            self.emit(&format!("  ; map({}: {})", map_type.name(), var));
        }

        self.emit(&format!(
            "  call {} @{}, i32 0",
            kmpc::TARGET_INIT,
            self.gtid_var
        ));

        if !directive.map_clauses.is_empty() {
            self.emit(&format!(
                "  call {} @{}",
                kmpc::TARGET_DATA_BEGIN,
                self.gtid_var
            ));
        }

        let region_name = format!("__omp_target_region_{}", self.regions.len());
        self.emit(&format!(
            "  call {} @{}, @{}",
            kmpc::TARGET,
            self.gtid_var,
            region_name
        ));

        if !directive.map_clauses.is_empty() {
            self.emit(&format!(
                "  call {} @{}",
                kmpc::TARGET_DATA_END,
                self.gtid_var
            ));
        }

        self.emit(&format!(
            "  call {} @{}",
            kmpc::TARGET_DEINIT,
            self.gtid_var
        ));

        let region = OmpRegionInfo::new(directive.clone(), &region_name);
        self.regions.push(region);
    }

    /// Lower a #pragma omp target data directive.
    pub fn lower_target_data(&mut self, directive: &OmpDirective) {
        self.emit("; #pragma omp target data");

        for (var, map_type) in &directive.map_clauses {
            self.emit(&format!("  ; map({}: {})", map_type.name(), var));
        }

        self.emit(&format!(
            "  call {} @{}",
            kmpc::TARGET_DATA_BEGIN,
            self.gtid_var
        ));

        // Body goes here...

        self.emit(&format!(
            "  call {} @{}",
            kmpc::TARGET_DATA_END,
            self.gtid_var
        ));
    }

    /// Lower a #pragma omp teams directive.
    pub fn lower_teams(&mut self, directive: &OmpDirective) {
        self.emit("; #pragma omp teams");

        if let Some(nt) = directive.num_threads {
            self.emit(&format!("  ; num_teams({})", nt));
        }

        self.emit(&format!("  call {} @{}", kmpc::TEAMS_REGION, self.gtid_var));
    }

    /// Lower a #pragma omp distribute directive.
    pub fn lower_distribute(&mut self, lower: i64, upper: i64) {
        self.emit("; #pragma omp distribute");
        self.emit(&format!(
            "  call {} @{}, i64 {}, i64 {}",
            kmpc::DISTRIBUTE_STATIC_INIT,
            self.gtid_var,
            lower,
            upper
        ));
    }

    /// Lower a #pragma omp requires directive.
    pub fn lower_requires(&mut self, clauses: &[OmpRequiresClause]) {
        self.emit("; #pragma omp requires");
        for clause in clauses {
            match clause {
                OmpRequiresClause::UnifiedSharedMemory => {
                    self.emit("  ; unified_shared_memory");
                }
                OmpRequiresClause::UnifiedAddress => {
                    self.emit("  ; unified_address");
                }
                OmpRequiresClause::ReverseOffload => {
                    self.emit("  ; reverse_offload");
                }
                OmpRequiresClause::DynamicAllocators => {
                    self.emit("  ; dynamic_allocators");
                }
                OmpRequiresClause::AtomicDefaultMemOrder => {
                    self.emit("  ; atomic_default_mem_order");
                }
            }
        }
    }

    /// Finalize and return all generated output.
    pub fn finalize(&self) -> String {
        self.output.join("\n")
    }
}

impl Default for OmpCodeGenContext {
    fn default() -> Self {
        Self::new()
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Tests
// ═══════════════════════════════════════════════════════════════════════════════

#[cfg(test)]
mod tests {
    use super::*;

    // ── OmpDirectiveKind ─────────────────────────────────────────────────────

    #[test]
    fn test_omp_directive_kind_name() {
        assert_eq!(OmpDirectiveKind::Parallel.name(), "parallel");
        assert_eq!(OmpDirectiveKind::For.name(), "for");
        assert_eq!(OmpDirectiveKind::Target.name(), "target");
        assert_eq!(OmpDirectiveKind::Simd.name(), "simd");
    }

    #[test]
    fn test_omp_directive_is_worksharing() {
        assert!(OmpDirectiveKind::For.is_worksharing());
        assert!(OmpDirectiveKind::Sections.is_worksharing());
        assert!(!OmpDirectiveKind::Parallel.is_worksharing());
    }

    #[test]
    fn test_omp_directive_is_target() {
        assert!(OmpDirectiveKind::Target.is_target());
        assert!(OmpDirectiveKind::TargetData.is_target());
        assert!(!OmpDirectiveKind::For.is_target());
    }

    // ── OmpScheduleKind ─────────────────────────────────────────────────────

    #[test]
    fn test_schedule_kind_from_name() {
        assert_eq!(
            OmpScheduleKind::from_name("static"),
            Some(OmpScheduleKind::Static)
        );
        assert_eq!(
            OmpScheduleKind::from_name("dynamic"),
            Some(OmpScheduleKind::Dynamic)
        );
        assert_eq!(
            OmpScheduleKind::from_name("runtime"),
            Some(OmpScheduleKind::Runtime)
        );
        assert_eq!(OmpScheduleKind::from_name("invalid"), None);
    }

    #[test]
    fn test_schedule_kind_runtime_id() {
        assert_eq!(OmpScheduleKind::Static.to_runtime_id(), 1);
        assert_eq!(OmpScheduleKind::Runtime.to_runtime_id(), 5);
    }

    // ── OmpMapType ──────────────────────────────────────────────────────────

    #[test]
    fn test_map_type_from_name() {
        assert_eq!(OmpMapType::from_name("to"), Some(OmpMapType::To));
        assert_eq!(OmpMapType::from_name("from"), Some(OmpMapType::From));
        assert_eq!(OmpMapType::from_name("tofrom"), Some(OmpMapType::ToFrom));
    }

    #[test]
    fn test_map_type_name() {
        assert_eq!(OmpMapType::ToFrom.name(), "tofrom");
        assert_eq!(OmpMapType::Alloc.name(), "alloc");
    }

    // ── OmpDirective ───────────────────────────────────────────────────────

    #[test]
    fn test_omp_directive_new() {
        let dir = OmpDirective::new(OmpDirectiveKind::Parallel);
        assert_eq!(dir.kind, OmpDirectiveKind::Parallel);
        assert!(dir.has_barrier);
    }

    #[test]
    fn test_omp_directive_with_schedule() {
        let dir = OmpDirective::new(OmpDirectiveKind::For)
            .with_schedule(OmpScheduleKind::Dynamic, Some(4));
        assert_eq!(dir.schedule, Some(OmpScheduleKind::Dynamic));
        assert_eq!(dir.chunk_size, Some(4));
    }

    #[test]
    fn test_omp_directive_with_nowait() {
        let dir = OmpDirective::new(OmpDirectiveKind::For).with_nowait();
        assert!(dir.nowait);
        assert!(!dir.has_barrier);
    }

    #[test]
    fn test_omp_directive_add_map_clause() {
        let mut dir = OmpDirective::new(OmpDirectiveKind::Target);
        dir.add_map_clause("a", OmpMapType::ToFrom);
        dir.add_map_clause("b", OmpMapType::To);
        assert_eq!(dir.map_clauses.len(), 2);
    }

    #[test]
    fn test_omp_directive_add_reduction() {
        let mut dir = OmpDirective::new(OmpDirectiveKind::ParallelFor);
        dir.add_reduction("+", &["x", "y"]);
        assert_eq!(dir.reductions.len(), 1);
        assert_eq!(dir.reductions[0].0, "+");
        assert_eq!(dir.reductions[0].1.len(), 2);
    }

    #[test]
    fn test_omp_directive_runtime_call() {
        let dir = OmpDirective::new(OmpDirectiveKind::Parallel);
        assert_eq!(dir.get_runtime_call_name(), Some(kmpc::FORK_CALL));

        let dir2 = OmpDirective::new(OmpDirectiveKind::Barrier);
        assert_eq!(dir2.get_runtime_call_name(), Some(kmpc::BARRIER));
    }

    // ── OmpRegionInfo ──────────────────────────────────────────────────────

    #[test]
    fn test_omp_region_info_new() {
        let dir = OmpDirective::new(OmpDirectiveKind::Parallel);
        let region = OmpRegionInfo::new(dir, "test_region");
        assert_eq!(region.outlined_fn_name, "test_region");
        assert_eq!(region.arg_count, 0);
    }

    #[test]
    fn test_omp_region_info_as_microtask() {
        let dir = OmpDirective::new(OmpDirectiveKind::Parallel);
        let region = OmpRegionInfo::new(dir, "microtask_fn").as_microtask();
        assert!(region.is_microtask);
    }

    #[test]
    fn test_omp_region_info_add_capture() {
        let dir = OmpDirective::new(OmpDirectiveKind::Parallel);
        let mut region = OmpRegionInfo::new(dir, "capture_fn");
        region.add_capture("a", "i32*");
        region.add_capture("b", "double*");
        assert_eq!(region.arg_count, 2);
        assert_eq!(region.captured_vars.len(), 2);
    }

    // ── OmpRequiresClause ───────────────────────────────────────────────────

    #[test]
    fn test_requires_clause_from_name() {
        assert_eq!(
            OmpRequiresClause::from_name("unified_shared_memory"),
            Some(OmpRequiresClause::UnifiedSharedMemory)
        );
        assert_eq!(
            OmpRequiresClause::from_name("reverse_offload"),
            Some(OmpRequiresClause::ReverseOffload)
        );
        assert_eq!(OmpRequiresClause::from_name("invalid"), None);
    }

    // ── OmpCodeGenContext ───────────────────────────────────────────────────

    #[test]
    fn test_codegen_context_new() {
        let ctx = OmpCodeGenContext::new();
        assert!(!ctx.in_parallel);
        assert!(!ctx.in_target);
        assert!(ctx.output.is_empty());
    }

    #[test]
    fn test_lower_parallel() {
        let mut ctx = OmpCodeGenContext::new();
        let dir = OmpDirective::new(OmpDirectiveKind::Parallel).with_num_threads(4);
        ctx.lower_parallel(&dir, "");
        assert!(ctx.output.iter().any(|l| l.contains(kmpc::FORK_CALL)));
        assert!(ctx.output.iter().any(|l| l.contains(kmpc::BARRIER)));
        assert_eq!(ctx.regions.len(), 1);
    }

    #[test]
    fn test_lower_for_static() {
        let mut ctx = OmpCodeGenContext::new();
        let dir = OmpDirective::new(OmpDirectiveKind::For)
            .with_schedule(OmpScheduleKind::Static, Some(1));
        ctx.lower_for(&dir, 0, 100, 1);
        assert!(ctx
            .output
            .iter()
            .any(|l| l.contains(kmpc::FOR_STATIC_INIT_4)));
    }

    #[test]
    fn test_lower_for_dynamic() {
        let mut ctx = OmpCodeGenContext::new();
        let dir = OmpDirective::new(OmpDirectiveKind::For)
            .with_schedule(OmpScheduleKind::Dynamic, Some(4));
        ctx.lower_for(&dir, 0, 100, 1);
        assert!(ctx.output.iter().any(|l| l.contains(kmpc::DISPATCH_INIT_4)));
    }

    #[test]
    fn test_lower_critical() {
        let mut ctx = OmpCodeGenContext::new();
        ctx.lower_critical(Some("my_critical"));
        assert!(ctx.output.iter().any(|l| l.contains(kmpc::CRITICAL)));
        assert!(ctx.output.iter().any(|l| l.contains("my_critical")));
    }

    #[test]
    fn test_lower_atomic() {
        let mut ctx = OmpCodeGenContext::new();
        ctx.lower_atomic(OmpAtomicKind::Read);
        assert!(ctx.output.iter().any(|l| l.contains(kmpc::ATOMIC_RD_4)));
    }

    #[test]
    fn test_lower_barrier() {
        let mut ctx = OmpCodeGenContext::new();
        ctx.lower_barrier();
        assert!(ctx.output.iter().any(|l| l.contains(kmpc::BARRIER)));
    }

    #[test]
    fn test_lower_taskwait() {
        let mut ctx = OmpCodeGenContext::new();
        ctx.lower_taskwait();
        assert!(ctx.output.iter().any(|l| l.contains(kmpc::TASKWAIT)));
    }

    #[test]
    fn test_lower_simd() {
        let mut ctx = OmpCodeGenContext::new();
        let mut dir = OmpDirective::new(OmpDirectiveKind::Simd);
        dir.simdlen = Some(4);
        ctx.lower_simd(&dir);
        assert!(ctx.output.iter().any(|l| l.contains("simd")));
    }

    #[test]
    fn test_lower_target() {
        let mut ctx = OmpCodeGenContext::new();
        let mut dir = OmpDirective::new(OmpDirectiveKind::Target);
        dir.add_map_clause("arr", OmpMapType::ToFrom);
        ctx.lower_target(&dir);
        assert!(ctx.output.iter().any(|l| l.contains(kmpc::TARGET_INIT)));
        assert!(ctx.output.iter().any(|l| l.contains(kmpc::TARGET)));
    }

    #[test]
    fn test_lower_target_data() {
        let mut ctx = OmpCodeGenContext::new();
        let mut dir = OmpDirective::new(OmpDirectiveKind::TargetData);
        dir.add_map_clause("data", OmpMapType::To);
        ctx.lower_target_data(&dir);
        assert!(ctx
            .output
            .iter()
            .any(|l| l.contains(kmpc::TARGET_DATA_BEGIN)));
        assert!(ctx.output.iter().any(|l| l.contains(kmpc::TARGET_DATA_END)));
    }

    #[test]
    fn test_lower_requires() {
        let mut ctx = OmpCodeGenContext::new();
        ctx.lower_requires(&[
            OmpRequiresClause::UnifiedSharedMemory,
            OmpRequiresClause::ReverseOffload,
        ]);
        assert!(ctx
            .output
            .iter()
            .any(|l| l.contains("unified_shared_memory")));
        assert!(ctx.output.iter().any(|l| l.contains("reverse_offload")));
    }

    #[test]
    fn test_lower_teams() {
        let mut ctx = OmpCodeGenContext::new();
        let dir = OmpDirective::new(OmpDirectiveKind::Teams).with_num_threads(8);
        ctx.lower_teams(&dir);
        assert!(ctx.output.iter().any(|l| l.contains(kmpc::TEAMS_REGION)));
    }

    #[test]
    fn test_lower_distribute() {
        let mut ctx = OmpCodeGenContext::new();
        ctx.lower_distribute(0, 1024);
        assert!(ctx
            .output
            .iter()
            .any(|l| l.contains(kmpc::DISTRIBUTE_STATIC_INIT)));
    }

    #[test]
    fn test_codegen_finalize() {
        let mut ctx = OmpCodeGenContext::new();
        ctx.lower_barrier();
        let output = ctx.finalize();
        assert!(output.contains(kmpc::BARRIER));
    }

    #[test]
    fn test_omp_atomic_kind() {
        assert_eq!(OmpAtomicKind::Read.name(), "read");
        assert_eq!(OmpAtomicKind::Capture.name(), "capture");
    }
}