-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCompiler_Dataflow.H
More file actions
1662 lines (1475 loc) · 68.2 KB
/
Copy pathCompiler_Dataflow.H
File metadata and controls
1662 lines (1475 loc) · 68.2 KB
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
/*
Aleph_w
Data structures & Algorithms
version 2.0.0b
https://github.com/lrleon/Aleph-w
This file is part of Aleph-w library
Copyright (c) 2002-2026 Leandro Rabindranath Leon
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/** @file Compiler_Dataflow.H
* @brief Reusable dataflow analyses and dead-code elimination over `Compiler_IR_Model.H`.
*
* This header adds the first optimization-oriented layer on top of the
* reusable non-SSA IR. The current scope remains intentionally conservative:
*
* - block reachability
* - local-slot liveness
* - definite assignment / initialization for parameters and locals
* - local constant propagation with a small constant lattice
* - dead-code elimination of unreachable blocks, dead pure values, dead local stores,
* and branches proven constant
* - invariant validators for analysis and DCE results
*
* The analyses operate per `Compiler_IR_Function`, including the lowered
* top-level body when represented as `<top-level>`.
*
* @ingroup Utilities
*/
#ifndef COMPILER_DATAFLOW_H
#define COMPILER_DATAFLOW_H
#include <cerrno>
#include <climits>
#include <cstdlib>
#include <sstream>
#include <string>
#include <utility>
#include <Compiler_IR_Model.H>
#include <ah-errors.H>
#include <tpl_dynArray.H>
namespace Aleph
{
/**
* @brief Small reusable bit-set for slot-domain dataflow analyses.
*
* Each element is stored as one byte so per-element access is O(1)
* without bit-shifting. Not thread-safe.
*/
struct Compiler_Dataflow_Bit_Set
{
DynArray<unsigned char> bits; ///< One byte per tracked element.
/**
* @brief Clears all existing bits and resizes the set to `count` elements.
* @param count Number of bits to track after the call.
* @param value Initial value for every bit (default: false / 0).
* @note Previous contents are discarded. Complexity: O(count).
* @note Not thread-safe.
*/
void resize(const size_t count, const bool value = false)
{
bits.clear();
for (size_t i = 0; i < count; ++i)
bits.append(value ? 1u : 0u);
}
/**
* @brief Returns the number of tracked bits.
* @return Total number of bits in the set.
* @note Complexity: O(1). Not thread-safe.
*/
size_t size() const noexcept
{
return bits.size();
}
/**
* @brief Returns whether bit `index` is set.
* @param index Zero-based bit index.
* @return true if the bit is set; false if it is clear or `index` is
* out of range.
* @note Complexity: O(1). Not thread-safe.
*/
bool test(const size_t index) const noexcept
{
return index < bits.size() and bits.access(index) != 0;
}
/**
* @brief Sets or clears bit `index`.
* @param index Zero-based bit index; must be less than size().
* @param value New value for the bit (default: true / set).
* @return true if the bit changed; false if it already had the requested value.
* @throws Aleph runtime error if `index >= size()`.
* @note Complexity: O(1). Not thread-safe.
*/
bool set(const size_t index, const bool value = true)
{
ah_runtime_error_unless(index < bits.size())
<< "Compiler_Dataflow_Bit_Set::set(): index out of bounds";
const auto encoded = static_cast<unsigned char>(value ? 1u : 0u);
if (bits.access(index) == encoded)
return false;
bits.access(index) = encoded;
return true;
}
};
/** @brief Constant-lattice states used by local constant propagation. */
enum class Compiler_Dataflow_Constant_Kind
{
Unknown, ///< A value exists but is not known to be constant.
Undefined, ///< A slot has not been definitely initialized yet.
Integer, ///< Integer constant.
Boolean, ///< Boolean constant.
Unit ///< Unit constant.
};
/** @brief Returns a stable debug name for one constant-lattice kind. */
inline const char *
compiler_dataflow_constant_kind_name(const Compiler_Dataflow_Constant_Kind kind) noexcept
{
switch (kind)
{
case Compiler_Dataflow_Constant_Kind::Unknown:
return "Unknown";
case Compiler_Dataflow_Constant_Kind::Undefined:
return "Undefined";
case Compiler_Dataflow_Constant_Kind::Integer:
return "Integer";
case Compiler_Dataflow_Constant_Kind::Boolean:
return "Boolean";
case Compiler_Dataflow_Constant_Kind::Unit:
return "Unit";
}
return "Unknown";
}
/** @brief One propagated constant value in the local-slot lattice. */
struct Compiler_Dataflow_Constant
{
Compiler_Dataflow_Constant_Kind kind = Compiler_Dataflow_Constant_Kind::Unknown; ///< Lattice kind.
long long integer_value = 0; ///< Integer payload when `kind == Integer`.
bool bool_value = false; ///< Boolean payload when `kind == Boolean`.
std::string text; ///< Stable textual spelling for deterministic dumps.
/** @brief Returns whether the lattice state represents a known constant. */
bool is_known() const noexcept
{
return kind == Compiler_Dataflow_Constant_Kind::Integer
or kind == Compiler_Dataflow_Constant_Kind::Boolean
or kind == Compiler_Dataflow_Constant_Kind::Unit;
}
};
/** @brief One definite-assignment finding for an uninitialized local read. */
struct Compiler_Dataflow_Uninitialized_Read
{
Compiler_IR_Block_Id block_id = compiler_ir_invalid_id(); ///< Block containing the read.
size_t instruction_index = 0; ///< Zero-based instruction index inside the block.
Compiler_IR_Local_Slot_Id slot_id = compiler_ir_invalid_id(); ///< Read local slot.
Source_Span span; ///< Source span associated with the load.
};
/** @brief Full dataflow result for one IR function or top-level body. */
struct Compiler_Dataflow_Function_Analysis
{
size_t local_slot_count = 0; ///< Number of tracked local slots.
DynArray<bool> reachable_blocks; ///< Reachability from entry for each block id.
DynArray<Compiler_Dataflow_Bit_Set> live_in_slots; ///< Local slots live at block entry.
DynArray<Compiler_Dataflow_Bit_Set> live_out_slots; ///< Local slots live at block exit.
DynArray<Compiler_Dataflow_Bit_Set> assigned_in_slots; ///< Local slots definitely assigned at block entry.
DynArray<Compiler_Dataflow_Bit_Set> assigned_out_slots; ///< Local slots definitely assigned at block exit.
DynArray<DynArray<Compiler_Dataflow_Constant>> constant_in_slots; ///< Per-block constant state at entry.
DynArray<DynArray<Compiler_Dataflow_Constant>> constant_out_slots; ///< Per-block constant state at exit.
DynArray<Compiler_Dataflow_Uninitialized_Read> uninitialized_reads; ///< Local reads that are not definitely assigned.
size_t foldable_branch_count = 0; ///< Reachable branches whose condition is statically known.
};
/** @brief Validation report for analysis and optimization passes. */
struct Compiler_Dataflow_Validation_Report
{
bool valid = true; ///< Whether the checked invariants hold.
DynArray<std::string> errors; ///< Hard invariant violations.
DynArray<std::string> warnings; ///< Non-fatal observations.
};
/** @brief Result of applying dead-code elimination to one IR function. */
struct Compiler_Dead_Code_Elimination_Result
{
Compiler_IR_Function function; ///< Optimized function copy.
size_t removed_blocks = 0; ///< Number of removed blocks.
size_t removed_instructions = 0; ///< Number of removed instructions.
size_t folded_branches = 0; ///< Number of branches folded to jumps.
};
namespace Compiler_Dataflow_Detail
{
inline Compiler_Dataflow_Constant
unknown_constant()
{
return {};
}
inline Compiler_Dataflow_Constant
undefined_constant()
{
Compiler_Dataflow_Constant value;
value.kind = Compiler_Dataflow_Constant_Kind::Undefined;
value.text = "undef";
return value;
}
inline Compiler_Dataflow_Constant
integer_constant(const long long value)
{
Compiler_Dataflow_Constant constant;
constant.kind = Compiler_Dataflow_Constant_Kind::Integer;
constant.integer_value = value;
constant.text = std::to_string(value);
return constant;
}
inline Compiler_Dataflow_Constant
boolean_constant(const bool value)
{
Compiler_Dataflow_Constant constant;
constant.kind = Compiler_Dataflow_Constant_Kind::Boolean;
constant.bool_value = value;
constant.text = value ? "true" : "false";
return constant;
}
inline Compiler_Dataflow_Constant
unit_constant()
{
Compiler_Dataflow_Constant constant;
constant.kind = Compiler_Dataflow_Constant_Kind::Unit;
constant.text = "unit";
return constant;
}
inline bool
same_constant(const Compiler_Dataflow_Constant & lhs,
const Compiler_Dataflow_Constant & rhs) noexcept
{
if (lhs.kind != rhs.kind)
return false;
switch (lhs.kind)
{
case Compiler_Dataflow_Constant_Kind::Integer:
return lhs.integer_value == rhs.integer_value;
case Compiler_Dataflow_Constant_Kind::Boolean:
return lhs.bool_value == rhs.bool_value;
case Compiler_Dataflow_Constant_Kind::Unknown:
case Compiler_Dataflow_Constant_Kind::Undefined:
case Compiler_Dataflow_Constant_Kind::Unit:
return true;
}
return false;
}
inline std::string
constant_to_string(const Compiler_Dataflow_Constant & constant)
{
switch (constant.kind)
{
case Compiler_Dataflow_Constant_Kind::Unknown:
return "?";
case Compiler_Dataflow_Constant_Kind::Undefined:
return "undef";
case Compiler_Dataflow_Constant_Kind::Integer:
return constant.text.empty() ? std::to_string(constant.integer_value)
: constant.text;
case Compiler_Dataflow_Constant_Kind::Boolean:
return constant.bool_value ? "true" : "false";
case Compiler_Dataflow_Constant_Kind::Unit:
return "unit";
}
return "?";
}
inline bool
parse_integer_constant(const std::string & text,
long long & value) noexcept
{
if (text.empty())
return false;
char * end = nullptr;
errno = 0;
const long long result = std::strtoll(text.c_str(), &end, 10);
if (end == text.c_str() or *end != '\0')
return false;
if (errno == ERANGE)
return false;
value = result;
return true;
}
inline Compiler_Dataflow_Constant
constant_from_instruction(const Compiler_IR_Instruction & inst)
{
if (inst.kind != Compiler_IR_Instruction_Kind::Constant)
return unknown_constant();
if (inst.text == "unit")
return unit_constant();
if (inst.text == "true")
return boolean_constant(true);
if (inst.text == "false")
return boolean_constant(false);
long long value = 0;
if (parse_integer_constant(inst.text, value))
return integer_constant(value);
return unknown_constant();
}
inline Compiler_Dataflow_Constant
meet_constants(const Compiler_Dataflow_Constant & lhs,
const Compiler_Dataflow_Constant & rhs)
{
if (same_constant(lhs, rhs))
return lhs;
if (lhs.kind == Compiler_Dataflow_Constant_Kind::Unknown
or rhs.kind == Compiler_Dataflow_Constant_Kind::Unknown)
return unknown_constant();
if (lhs.kind == Compiler_Dataflow_Constant_Kind::Undefined
or rhs.kind == Compiler_Dataflow_Constant_Kind::Undefined)
return unknown_constant();
return unknown_constant();
}
inline Compiler_Dataflow_Bit_Set
make_bit_set(const size_t count, const bool value = false)
{
Compiler_Dataflow_Bit_Set set;
set.resize(count, value);
return set;
}
inline DynArray<Compiler_Dataflow_Constant>
make_constant_vector(const size_t count,
const Compiler_Dataflow_Constant & fill)
{
DynArray<Compiler_Dataflow_Constant> values;
for (size_t i = 0; i < count; ++i)
values.append(fill);
return values;
}
inline bool
bit_set_equals(const Compiler_Dataflow_Bit_Set & lhs,
const Compiler_Dataflow_Bit_Set & rhs) noexcept
{
if (lhs.size() != rhs.size())
return false;
for (size_t i = 0; i < lhs.size(); ++i)
if (lhs.bits.access(i) != rhs.bits.access(i))
return false;
return true;
}
inline bool
constant_vector_equals(const DynArray<Compiler_Dataflow_Constant> & lhs,
const DynArray<Compiler_Dataflow_Constant> & rhs) noexcept
{
if (lhs.size() != rhs.size())
return false;
for (size_t i = 0; i < lhs.size(); ++i)
if (not same_constant(lhs.access(i), rhs.access(i)))
return false;
return true;
}
inline Compiler_Dataflow_Bit_Set
bit_set_union(const Compiler_Dataflow_Bit_Set & lhs,
const Compiler_Dataflow_Bit_Set & rhs)
{
ah_runtime_error_unless(lhs.size() == rhs.size())
<< "Compiler_Dataflow: union requires sets with the same size";
auto result = make_bit_set(lhs.size(), false);
for (size_t i = 0; i < lhs.size(); ++i)
result.bits.access(i) = static_cast<unsigned char>(lhs.test(i) or rhs.test(i));
return result;
}
inline Compiler_Dataflow_Bit_Set
bit_set_intersection(const Compiler_Dataflow_Bit_Set & lhs,
const Compiler_Dataflow_Bit_Set & rhs)
{
ah_runtime_error_unless(lhs.size() == rhs.size())
<< "Compiler_Dataflow: intersection requires sets with the same size";
auto result = make_bit_set(lhs.size(), false);
for (size_t i = 0; i < lhs.size(); ++i)
result.bits.access(i) = static_cast<unsigned char>(lhs.test(i) and rhs.test(i));
return result;
}
inline Compiler_Dataflow_Bit_Set
bit_set_subtract(const Compiler_Dataflow_Bit_Set & lhs,
const Compiler_Dataflow_Bit_Set & rhs)
{
ah_runtime_error_unless(lhs.size() == rhs.size())
<< "Compiler_Dataflow: subtraction requires sets with the same size";
auto result = make_bit_set(lhs.size(), false);
for (size_t i = 0; i < lhs.size(); ++i)
result.bits.access(i) = static_cast<unsigned char>(lhs.test(i) and not rhs.test(i));
return result;
}
inline Compiler_Dataflow_Bit_Set
initial_assigned_state(const Compiler_IR_Function & function)
{
auto assigned = make_bit_set(function.local_slots.size(), false);
for (size_t i = 0; i < function.local_slots.size(); ++i)
if (function.local_slots.access(i).kind == Compiler_IR_Slot_Kind::Parameter)
assigned.set(i, true);
return assigned;
}
inline DynArray<Compiler_Dataflow_Constant>
initial_constant_state(const Compiler_IR_Function & function)
{
auto constants = make_constant_vector(function.local_slots.size(),
undefined_constant());
for (size_t i = 0; i < function.local_slots.size(); ++i)
if (function.local_slots.access(i).kind == Compiler_IR_Slot_Kind::Parameter)
constants.access(i) = unknown_constant();
return constants;
}
inline Compiler_Dataflow_Constant
value_constant(const DynArray<Compiler_Dataflow_Constant> & values,
const Compiler_IR_Value_Id id)
{
if (id == 0 or id >= values.size())
return unknown_constant();
return values.access(id);
}
inline void
mark_value_used(DynArray<unsigned char> & used_values,
const Compiler_IR_Value_Id id)
{
if (id != 0 and id < used_values.size())
used_values.access(id) = 1u;
}
inline bool
is_value_used(const DynArray<unsigned char> & used_values,
const Compiler_IR_Value_Id id) noexcept
{
return id != 0 and id < used_values.size() and used_values.access(id) != 0;
}
inline bool
is_pure_instruction(const Compiler_IR_Instruction & inst) noexcept
{
return inst.kind == Compiler_IR_Instruction_Kind::Constant
or inst.kind == Compiler_IR_Instruction_Kind::Load
or inst.kind == Compiler_IR_Instruction_Kind::Unary
or inst.kind == Compiler_IR_Instruction_Kind::Binary
or inst.kind == Compiler_IR_Instruction_Kind::Function_Ref;
}
inline Compiler_Dataflow_Constant
evaluate_unary(const Compiler_Operator_Kind op,
const Compiler_Dataflow_Constant & operand)
{
switch (op)
{
case Compiler_Operator_Kind::Plus:
if (operand.kind == Compiler_Dataflow_Constant_Kind::Integer)
return integer_constant(operand.integer_value);
break;
case Compiler_Operator_Kind::Minus:
if (operand.kind == Compiler_Dataflow_Constant_Kind::Integer)
{
if (operand.integer_value == LLONG_MIN)
break; // -LLONG_MIN overflows; do not fold
return integer_constant(-operand.integer_value);
}
break;
case Compiler_Operator_Kind::Bang:
if (operand.kind == Compiler_Dataflow_Constant_Kind::Boolean)
return boolean_constant(not operand.bool_value);
break;
default:
break;
}
return unknown_constant();
}
inline Compiler_Dataflow_Constant
evaluate_binary(const Compiler_Operator_Kind op,
const Compiler_Dataflow_Constant & lhs,
const Compiler_Dataflow_Constant & rhs)
{
if (lhs.kind == Compiler_Dataflow_Constant_Kind::Integer
and rhs.kind == Compiler_Dataflow_Constant_Kind::Integer)
switch (op)
{
case Compiler_Operator_Kind::Plus:
{
long long result = 0;
#if defined(__has_builtin) && __has_builtin(__builtin_add_overflow)
if (__builtin_add_overflow(lhs.integer_value, rhs.integer_value, &result))
return unknown_constant();
#else
// Portable signed-addition overflow check via unsigned arithmetic.
const auto ul = static_cast<unsigned long long>(lhs.integer_value);
const auto ur = static_cast<unsigned long long>(rhs.integer_value);
result = static_cast<long long>(ul + ur);
if ((lhs.integer_value > 0 and rhs.integer_value > 0 and result < 0)
or (lhs.integer_value < 0 and rhs.integer_value < 0 and result >= 0))
return unknown_constant();
#endif
return integer_constant(result);
}
case Compiler_Operator_Kind::Minus:
{
long long result = 0;
#if defined(__has_builtin) && __has_builtin(__builtin_sub_overflow)
if (__builtin_sub_overflow(lhs.integer_value, rhs.integer_value, &result))
return unknown_constant();
#else
// Portable signed-subtraction overflow check via unsigned arithmetic.
const auto ul = static_cast<unsigned long long>(lhs.integer_value);
const auto ur = static_cast<unsigned long long>(rhs.integer_value);
result = static_cast<long long>(ul - ur);
if ((rhs.integer_value < 0 and lhs.integer_value > 0 and result < 0)
or (rhs.integer_value > 0 and lhs.integer_value < 0 and result >= 0))
return unknown_constant();
#endif
return integer_constant(result);
}
case Compiler_Operator_Kind::Star:
{
long long result = 0;
#if defined(__has_builtin) && __has_builtin(__builtin_mul_overflow)
if (__builtin_mul_overflow(lhs.integer_value, rhs.integer_value, &result))
return unknown_constant();
#else
// Portable signed-multiplication overflow check.
if (lhs.integer_value == 0 or rhs.integer_value == 0)
{
result = 0;
}
else
{
const auto ul = static_cast<unsigned long long>(
lhs.integer_value < 0 ? -(unsigned long long)lhs.integer_value
: (unsigned long long)lhs.integer_value);
const auto ur = static_cast<unsigned long long>(
rhs.integer_value < 0 ? -(unsigned long long)rhs.integer_value
: (unsigned long long)rhs.integer_value);
const unsigned long long uresult = ul * ur;
const bool neg = (lhs.integer_value < 0) != (rhs.integer_value < 0);
if (ul != 0 and uresult / ul != ur)
return unknown_constant();
if (neg and uresult > static_cast<unsigned long long>(LLONG_MAX) + 1ULL)
return unknown_constant();
if (not neg and uresult > static_cast<unsigned long long>(LLONG_MAX))
return unknown_constant();
if (neg and uresult == static_cast<unsigned long long>(LLONG_MAX) + 1ULL)
result = LLONG_MIN;
else
result = neg ? -static_cast<long long>(uresult)
: static_cast<long long>(uresult);
}
#endif
return integer_constant(result);
}
case Compiler_Operator_Kind::Slash:
if (rhs.integer_value == 0)
return unknown_constant();
if (lhs.integer_value == LLONG_MIN and rhs.integer_value == -1)
return unknown_constant();
return integer_constant(lhs.integer_value / rhs.integer_value);
case Compiler_Operator_Kind::Percent:
if (rhs.integer_value == 0)
return unknown_constant();
if (lhs.integer_value == LLONG_MIN and rhs.integer_value == -1)
return unknown_constant();
return integer_constant(lhs.integer_value % rhs.integer_value);
case Compiler_Operator_Kind::EqEq:
return boolean_constant(lhs.integer_value == rhs.integer_value);
case Compiler_Operator_Kind::NotEq:
return boolean_constant(lhs.integer_value != rhs.integer_value);
case Compiler_Operator_Kind::Less:
return boolean_constant(lhs.integer_value < rhs.integer_value);
case Compiler_Operator_Kind::LessEq:
return boolean_constant(lhs.integer_value <= rhs.integer_value);
case Compiler_Operator_Kind::Greater:
return boolean_constant(lhs.integer_value > rhs.integer_value);
case Compiler_Operator_Kind::GreaterEq:
return boolean_constant(lhs.integer_value >= rhs.integer_value);
default:
break;
}
if (lhs.kind == Compiler_Dataflow_Constant_Kind::Boolean
and rhs.kind == Compiler_Dataflow_Constant_Kind::Boolean)
switch (op)
{
case Compiler_Operator_Kind::AndAnd:
return boolean_constant(lhs.bool_value and rhs.bool_value);
case Compiler_Operator_Kind::OrOr:
return boolean_constant(lhs.bool_value or rhs.bool_value);
case Compiler_Operator_Kind::EqEq:
return boolean_constant(lhs.bool_value == rhs.bool_value);
case Compiler_Operator_Kind::NotEq:
return boolean_constant(lhs.bool_value != rhs.bool_value);
default:
break;
}
if (lhs.kind == Compiler_Dataflow_Constant_Kind::Unit
and rhs.kind == Compiler_Dataflow_Constant_Kind::Unit)
switch (op)
{
case Compiler_Operator_Kind::EqEq:
return boolean_constant(true);
case Compiler_Operator_Kind::NotEq:
return boolean_constant(false);
default:
break;
}
return unknown_constant();
}
struct Block_Use_Def
{
Compiler_Dataflow_Bit_Set use;
Compiler_Dataflow_Bit_Set def;
};
inline Block_Use_Def
compute_block_use_def(const Compiler_IR_Function & function,
const Compiler_IR_Block & block)
{
Block_Use_Def info;
info.use = make_bit_set(function.local_slots.size(), false);
info.def = make_bit_set(function.local_slots.size(), false);
for (size_t i = 0; i < block.instructions.size(); ++i)
{
const auto & inst = block.instructions.access(i);
if (inst.kind == Compiler_IR_Instruction_Kind::Load
and inst.local_slot_id != compiler_ir_invalid_id()
and inst.local_slot_id < function.local_slots.size()
and not info.def.test(inst.local_slot_id))
info.use.set(inst.local_slot_id, true);
if (inst.kind == Compiler_IR_Instruction_Kind::Store
and inst.local_slot_id != compiler_ir_invalid_id()
and inst.local_slot_id < function.local_slots.size())
info.def.set(inst.local_slot_id, true);
}
return info;
}
inline DynArray<bool>
compute_reachability(const Compiler_IR_Function & function)
{
DynArray<bool> reachable;
for (size_t i = 0; i < function.blocks.size(); ++i)
reachable.append(false);
if (function.blocks.is_empty() or function.entry_block >= function.blocks.size())
return reachable;
DynArray<Compiler_IR_Block_Id> worklist;
worklist.append(function.entry_block);
while (not worklist.is_empty())
{
const auto current = worklist.pop();
if (current >= function.blocks.size() or reachable.access(current))
continue;
reachable.access(current) = true;
const auto & block = function.blocks.access(current);
for (size_t i = 0; i < block.terminator.successors.size(); ++i)
{
const auto succ = block.terminator.successors.access(i);
if (succ < function.blocks.size() and not reachable.access(succ))
worklist.append(succ);
}
}
return reachable;
}
struct Block_Simulation
{
Compiler_Dataflow_Bit_Set assigned_out;
DynArray<Compiler_Dataflow_Constant> constant_out;
DynArray<Compiler_Dataflow_Constant> value_constants;
Compiler_Dataflow_Constant branch_constant;
};
inline Block_Simulation
simulate_block(const Compiler_IR_Function & function,
const Compiler_IR_Block & block,
const Compiler_Dataflow_Bit_Set & assigned_in,
const DynArray<Compiler_Dataflow_Constant> & constants_in,
DynArray<Compiler_Dataflow_Uninitialized_Read> * findings = nullptr)
{
Block_Simulation simulation;
simulation.assigned_out = assigned_in;
simulation.constant_out = constants_in;
simulation.value_constants = make_constant_vector(function.next_value_id + 1,
unknown_constant());
simulation.branch_constant = unknown_constant();
for (size_t i = 0; i < block.instructions.size(); ++i)
{
const auto & inst = block.instructions.access(i);
Compiler_Dataflow_Constant result = unknown_constant();
switch (inst.kind)
{
case Compiler_IR_Instruction_Kind::Constant:
result = constant_from_instruction(inst);
break;
case Compiler_IR_Instruction_Kind::Load:
if (inst.local_slot_id != compiler_ir_invalid_id()
and inst.local_slot_id < simulation.constant_out.size())
{
if (not simulation.assigned_out.test(inst.local_slot_id)
and findings != nullptr)
findings->append({block.id, i, inst.local_slot_id, inst.span});
result = simulation.assigned_out.test(inst.local_slot_id)
? simulation.constant_out.access(inst.local_slot_id)
: unknown_constant();
}
else
result = unknown_constant();
break;
case Compiler_IR_Instruction_Kind::Unary:
result = evaluate_unary(inst.op,
value_constant(simulation.value_constants,
inst.operands.is_empty()
? 0
: inst.operands.access(0)));
break;
case Compiler_IR_Instruction_Kind::Binary:
result = evaluate_binary(inst.op,
value_constant(simulation.value_constants,
inst.operands.size() > 0
? inst.operands.access(0)
: 0),
value_constant(simulation.value_constants,
inst.operands.size() > 1
? inst.operands.access(1)
: 0));
break;
case Compiler_IR_Instruction_Kind::Call:
case Compiler_IR_Instruction_Kind::Function_Ref:
result = unknown_constant();
break;
case Compiler_IR_Instruction_Kind::Store:
if (inst.local_slot_id != compiler_ir_invalid_id()
and inst.local_slot_id < simulation.constant_out.size())
{
simulation.assigned_out.set(inst.local_slot_id, true);
simulation.constant_out.access(inst.local_slot_id) =
value_constant(simulation.value_constants,
inst.operands.is_empty()
? 0
: inst.operands.access(0));
}
continue;
}
if (inst.result_id != 0 and inst.result_id < simulation.value_constants.size())
simulation.value_constants.access(inst.result_id) = result;
}
if (block.terminator.kind == Compiler_IR_Terminator_Kind::Branch)
simulation.branch_constant =
value_constant(simulation.value_constants,
block.terminator.condition_value);
return simulation;
}
inline std::string
format_slot_set(const Compiler_IR_Function & function,
const Compiler_Dataflow_Bit_Set & set)
{
std::ostringstream out;
bool first = true;
for (size_t i = 0; i < set.size(); ++i)
if (set.test(i))
{
if (not first)
out << ", ";
out << Compiler_IR_Detail::local_slot_name(function.local_slots.access(i).id);
first = false;
}
return first ? "<none>" : out.str();
}
inline std::string
format_slot_constants(const Compiler_IR_Function & function,
const DynArray<Compiler_Dataflow_Constant> & constants)
{
std::ostringstream out;
for (size_t i = 0; i < constants.size(); ++i)
{
if (i > 0)
out << ", ";
out << Compiler_IR_Detail::local_slot_name(function.local_slots.access(i).id)
<< '=' << constant_to_string(constants.access(i));
}
return constants.is_empty() ? "<none>" : out.str();
}
inline void
rebuild_predecessors(Compiler_IR_Function & function)
{
for (size_t i = 0; i < function.blocks.size(); ++i)
function.blocks.access(i).predecessors.clear();
for (size_t i = 0; i < function.blocks.size(); ++i)
for (size_t j = 0; j < function.blocks.access(i).terminator.successors.size(); ++j)
{
const auto succ = function.blocks.access(i).terminator.successors.access(j);
if (succ < function.blocks.size())
function.blocks.access(succ).predecessors.append(i);
}
}
inline DynArray<DynArray<Compiler_IR_Block_Id>>
compute_predecessor_lists(const Compiler_IR_Function & function)
{
DynArray<DynArray<Compiler_IR_Block_Id>> predecessors;
for (size_t i = 0; i < function.blocks.size(); ++i)
predecessors.append(DynArray<Compiler_IR_Block_Id>{});
for (size_t i = 0; i < function.blocks.size(); ++i)
for (size_t j = 0; j < function.blocks.access(i).terminator.successors.size(); ++j)
{
const auto succ = function.blocks.access(i).terminator.successors.access(j);
if (succ < function.blocks.size())
predecessors.access(succ).append(i);
}
return predecessors;
}
inline size_t
count_instructions(const Compiler_IR_Function & function)
{
size_t total = 0;
for (size_t i = 0; i < function.blocks.size(); ++i)
total += function.blocks.access(i).instructions.size();
return total;
}
inline bool
instruction_is_trivially_dead(const Compiler_IR_Instruction & inst,
const Compiler_Dataflow_Bit_Set & live_after,
const DynArray<unsigned char> & used_values,
const Compiler_IR_Function & function) noexcept
{
if (inst.kind == Compiler_IR_Instruction_Kind::Store
and inst.local_slot_id != compiler_ir_invalid_id()
and inst.local_slot_id < function.local_slots.size())
return not live_after.test(inst.local_slot_id);
if (is_pure_instruction(inst) and inst.result_id != 0)
return not is_value_used(used_values, inst.result_id);
return false;
}
}
/**
* @brief Computes reachability, liveness, definite assignment, and constant
* propagation for one IR function.
* @param function IR function to analyse; must have a valid entry and exit block.
* @return Populated Compiler_Dataflow_Function_Analysis for `function`.
* @note Complexity: O(B·S·iter) where B = number of blocks, S = number of
* local slots, and iter = number of fixed-point iterations (typically
* O(B) in the worst case). Not thread-safe on shared state.
*/
inline Compiler_Dataflow_Function_Analysis
analyze_dataflow_function(const Compiler_IR_Function & function)
{
Compiler_Dataflow_Function_Analysis analysis;
analysis.local_slot_count = function.local_slots.size();
const auto reachable = Compiler_Dataflow_Detail::compute_reachability(function);
const auto predecessors =
Compiler_Dataflow_Detail::compute_predecessor_lists(function);
analysis.reachable_blocks = reachable;
DynArray<Compiler_Dataflow_Detail::Block_Use_Def> block_sets;
for (size_t i = 0; i < function.blocks.size(); ++i)
block_sets.append(Compiler_Dataflow_Detail::compute_block_use_def(function,
function.blocks.access(i)));
for (size_t i = 0; i < function.blocks.size(); ++i)
{
analysis.live_in_slots.append(Compiler_Dataflow_Detail::make_bit_set(function.local_slots.size(), false));
analysis.live_out_slots.append(Compiler_Dataflow_Detail::make_bit_set(function.local_slots.size(), false));
analysis.assigned_in_slots.append(Compiler_Dataflow_Detail::make_bit_set(function.local_slots.size(), false));
analysis.assigned_out_slots.append(Compiler_Dataflow_Detail::make_bit_set(function.local_slots.size(), false));
analysis.constant_in_slots.append(Compiler_Dataflow_Detail::make_constant_vector(function.local_slots.size(),
Compiler_Dataflow_Detail::unknown_constant()));
analysis.constant_out_slots.append(Compiler_Dataflow_Detail::make_constant_vector(function.local_slots.size(),
Compiler_Dataflow_Detail::unknown_constant()));
}
bool changed = true;
while (changed)
{
changed = false;
for (size_t index = function.blocks.size(); index > 0; --index)
{
const auto block_id = index - 1;
if (block_id >= reachable.size() or not reachable.access(block_id))
continue;
auto live_out = Compiler_Dataflow_Detail::make_bit_set(function.local_slots.size(), false);
const auto & block = function.blocks.access(block_id);
for (size_t i = 0; i < block.terminator.successors.size(); ++i)
{
const auto succ = block.terminator.successors.access(i);
if (succ >= function.blocks.size() or not reachable.access(succ))
continue;
live_out = Compiler_Dataflow_Detail::bit_set_union(live_out,
analysis.live_in_slots.access(succ));
}
const auto live_in =
Compiler_Dataflow_Detail::bit_set_union(block_sets.access(block_id).use,
Compiler_Dataflow_Detail::bit_set_subtract(
live_out,
block_sets.access(block_id).def));
if (not Compiler_Dataflow_Detail::bit_set_equals(live_out,
analysis.live_out_slots.access(block_id)))
{