-
Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathconstant_folded_fp_operations.swift
649 lines (567 loc) · 21.8 KB
/
constant_folded_fp_operations.swift
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
// RUN: %empty-directory(%t)
// RUN: %swift_driver %s >%t/constant_folded_fp_operation_validation.swift
// RUN: %target-swift-frontend -emit-sil -O -suppress-warnings -verify %t/constant_folded_fp_operation_validation.swift 2>&1 | %FileCheck --check-prefix=CHECK-SIL %t/constant_folded_fp_operation_validation.swift
// RUN: %target-build-swift -O -suppress-warnings %t/constant_folded_fp_operation_validation.swift -o %t/a.out
// RUN: %target-codesign %t/a.out
// RUN: %target-run %t/a.out
// REQUIRES: executable_test,optimized_stdlib
// REQUIRES: swift_in_compiler
// Note: This code is not the testfile itself but generates the testfile in the %t directory.
createTestFile()
func createTestFile() {
generateOperandAccessors()
let cmpOpValidator = FPConstantFoldedComparisonOpsValidator()
cmpOpValidator.generateOptimizedFuncDecls()
cmpOpValidator.generateUnoptimizedFuncDecls()
cmpOpValidator.generateComparisonFuncDecls()
cmpOpValidator.generateComparisonFuncCalls()
let arithOpValidator = FPConstantFoldedArithmeticOpsValidator()
arithOpValidator.generateOptimizedFuncDecls()
arithOpValidator.generateUnoptimizedFuncDecls()
arithOpValidator.generateComparisonFuncDecls()
arithOpValidator.generateComparisonFuncCalls()
}
/////////////////// Protocols ///////////////////
/// Implemented by types that have distinct ways of
/// being represented in an expression context vs all
/// other contexts.
protocol Representable {
func math_name() -> String
func printable_name() -> String
}
/// An rough estimation of a type that needs to validate
/// optimized floating point operations in Swift.
///
/// Any new validator should conform to this protocol
/// and then call the generate* functions to generate
/// corresponding test file code.
protocol FPOptimizedOpsValidator {
associatedtype FPType: Representable
associatedtype FPOperation: Representable
associatedtype FPOperand: Representable
func generateOptimizedFuncDecls()
func generateUnoptimizedFuncDecls()
func generateComparisonFuncDecls()
func generateComparisonFuncCalls()
func optimizedFunDeclCheck(fpType: FPType, op: FPOperation, op1: FPOperand, op2: FPOperand) -> String
func unoptimizedFunDeclCheck(fpType: FPType, op: FPOperation, op1: FPOperand, op2: FPOperand) -> String
func resultComparisonCheck(fpType: FPType, op: FPOperation, op1: FPOperand, op2: FPOperand) -> String
}
////////////////// Common ///////////////////
// Generates accessors for floating point operands
// commonly used in the tests.
//
// These accessors prevent the unoptimized function versions
// from getting optimized by the mandatory optimization passes
// and returning a constant value.
func generateOperandAccessors() {
print("""
@inline(never) @_silgen_name("zero_float") @_optimize(none)
func zero_float() -> Float {
return 0.0
}
@inline(never) @_silgen_name("one_float") @_optimize(none)
func one_float() -> Float {
return 1.0
}
@inline(never) @_silgen_name("zero_double") @_optimize(none)
func zero_double() -> Double {
return 0.0
}
@inline(never) @_silgen_name("one_double") @_optimize(none)
func one_double() -> Double {
return 1.0
}
""")
}
////////////////// Comparison Operations Validator ///////////////////
struct FPConstantFoldedComparisonOpsValidator: FPOptimizedOpsValidator {
/////////////////////// TYPES ///////////////////////
/// Type of floating points this validator deals with.
enum _FpType : CaseIterable, Representable, Equatable {
case Float
case Double
func math_name() -> String {
switch self {
case .Float:
return "Float"
case .Double:
return "Double"
}
}
func printable_name() -> String {
switch self {
case .Float:
return "float"
case .Double:
return "double"
}
}
}
/// Type of floating point operations this validator deals with.
enum _FPOperation : CaseIterable, Representable, Equatable {
case LessThan
case GreaterThan
case LessThanOrEqual
case GreaterThanOrEqual
case Equal
case NotEqual
func math_name() -> String {
switch self {
case .LessThan:
return "<"
case .GreaterThan:
return ">"
case .LessThanOrEqual:
return "<="
case .GreaterThanOrEqual:
return ">="
case .Equal:
return "=="
case .NotEqual:
return "!="
}
}
func printable_name() -> String {
switch self {
case .LessThan:
return "lessThan"
case .GreaterThan:
return "greaterThan"
case .LessThanOrEqual:
return "lessThanOrEqual"
case .GreaterThanOrEqual:
return "greaterThanOrEqual"
case .Equal:
return "equal"
case .NotEqual:
return "notEqual"
}
}
}
/// Type of floating point operands this validator deals with.
enum _FPOperand : CaseIterable, Representable, Equatable {
case Zero
case One
case Infinity
case Nan
func isSpecial() -> Bool {
switch self {
case .Zero:
return false
case .One:
return false
case .Infinity:
return true
case .Nan:
return true
}
}
func math_name() -> String {
switch self {
case .Zero:
return "0.0"
case .One:
return "1.0"
case .Infinity:
return "infinity"
case .Nan:
return "nan"
}
}
func printable_name() -> String {
switch self {
case .Zero:
return "zero"
case .One:
return "one"
case .Infinity:
return "infinity"
case .Nan:
return "nan"
}
}
}
private let optPrefix = "opt"
private let unoptPrefix = "unopt"
/////////////////////// FPOptimizedOpsValidator Conformances ///////////////////////
typealias FPType = _FpType
typealias FPOperation = _FPOperation
typealias FPOperand = _FPOperand
func optimizedFunDeclCheck(
fpType: FPType,
op: FPOperation,
op1: FPOperand,
op2: FPOperand
) -> String {
let funcName = [optPrefix, fpType.printable_name(), op.printable_name(), op1.printable_name(), op2.printable_name()].joined(separator: "_")
return """
// CHECK-SIL-LABEL: sil hidden [noinline] @\(funcName)
// CHECK-SIL-NEXT: [global: ]
// CHECK-SIL-NEXT: bb0:
// CHECK-SIL-NOT: {{.*}}fcmp{{.*}}
// CHECK-SIL: } // end sil function '\(funcName)'
"""
}
func unoptimizedFunDeclCheck(
fpType: FPType,
op: FPOperation,
op1: FPOperand,
op2: FPOperand
) -> String {
let funcName = [unoptPrefix, fpType.printable_name(), op.printable_name(), op1.printable_name(), op2.printable_name()].joined(separator: "_")
return """
// CHECK-SIL-LABEL: sil hidden [noinline] [Onone] @\(funcName)
// CHECK-SIL-NEXT: bb0:
// CHECK-SIL: {{.*}}fcmp{{.*}}
// CHECK-SIL: } // end sil function '\(funcName)'
"""
}
func resultComparisonCheck(
fpType: FPType,
op: FPOperation,
op1: FPOperand,
op2: FPOperand
) -> String {
let comparisonFuncName = ["comparison", fpType.printable_name(), op.printable_name(), op1.printable_name(), op2.printable_name()].joined(separator: "_")
return """
precondition(\(comparisonFuncName)(), "\(comparisonFuncName) returned false!")
"""
}
func generateOptimizedFuncDecls() {
for fpType in FPType.allCases {
for op in FPOperation.allCases {
for op1 in FPOperand.allCases {
for op2 in FPOperand.allCases {
if checkIfEqCmpBetweenInfAndNonInf(op: op, op1: op1, op2: op2) {
continue
}
generateFuncDeclWithCheckDirectives(fpType: fpType, op: op, op1: op1, op2: op2, isopt: true)
}
}
}
}
}
func generateUnoptimizedFuncDecls() {
for fpType in FPType.allCases {
for op in FPOperation.allCases {
for op1 in FPOperand.allCases {
for op2 in FPOperand.allCases {
if checkIfEqCmpBetweenInfAndNonInf(op: op, op1: op1, op2: op2) {
continue
}
generateFuncDeclWithCheckDirectives(fpType: fpType, op: op, op1: op1, op2: op2, isopt: false)
}
}
}
}
}
func generateComparisonFuncDecls() {
for fpType in FPType.allCases {
for op in FPOperation.allCases {
for op1 in FPOperand.allCases {
for op2 in FPOperand.allCases {
if checkIfEqCmpBetweenInfAndNonInf(op: op, op1: op1, op2: op2) {
continue
}
let comparisonFuncName = ["comparison", fpType.printable_name(), op.printable_name(), op1.printable_name(), op2.printable_name()].joined(separator: "_")
let optFuncName = [optPrefix, fpType.printable_name(), op.printable_name(), op1.printable_name(), op2.printable_name()].joined(separator: "_")
let unoptFuncName = [unoptPrefix, fpType.printable_name(), op.printable_name(), op1.printable_name(), op2.printable_name()].joined(separator: "_")
print("""
@inline(never) @_silgen_name("\(comparisonFuncName)") @_optimize(none)
func \(comparisonFuncName)() -> Bool {
return \(optFuncName)() == \(unoptFuncName)()
}
""")
}
}
}
}
}
func generateComparisonFuncCalls() {
for fpType in FPType.allCases {
for op in FPOperation.allCases {
for op1 in FPOperand.allCases {
for op2 in FPOperand.allCases {
if checkIfEqCmpBetweenInfAndNonInf(op: op, op1: op1, op2: op2) {
continue
}
let comparison = resultComparisonCheck(fpType: fpType, op: op, op1: op1, op2: op2)
print("""
\(comparison)
""")
}
}
}
}
}
/////////////////////// Utilities ///////////////////////
private func generateFuncDeclWithCheckDirectives(
fpType: FPType,
op: FPOperation,
op1: FPOperand,
op2: FPOperand,
isopt: Bool = false
) {
var operand1 = op1.isSpecial() ? fpType.math_name() + "." + op1.math_name() : op1.math_name()
var operand2 = op2.isSpecial() ? fpType.math_name() + "." + op2.math_name() : op2.math_name()
if !isopt {
if !op1.isSpecial() {
if fpType == .Double {
operand1 = op1 == .Zero ? "zero_double()": "one_double()"
} else {
operand1 = op1 == .Zero ? "zero_float()": "one_float()"
}
}
if !op2.isSpecial() {
if fpType == .Double {
operand2 = op2 == .Zero ? "zero_double()": "one_double()"
} else {
operand2 = op2 == .Zero ? "zero_float()": "one_float()"
}
}
}
let optPrefix = isopt ? optPrefix : unoptPrefix
let optAttr = isopt ? "" : "@_optimize(none)"
let funcName = [optPrefix, fpType.printable_name(), op.printable_name(), op1.printable_name(), op2.printable_name()].joined(separator: "_")
let checkDirectives = isopt ?
optimizedFunDeclCheck(fpType: fpType, op: op, op1: op1, op2: op2) :
unoptimizedFunDeclCheck(fpType: fpType, op: op, op1: op1, op2: op2)
print("""
@inline(never) @_silgen_name("\(funcName)") \(optAttr)
func \(funcName)() -> Bool {
return \(operand1) \(op.math_name()) \(operand2)
}
\(checkDirectives)
""")
}
// Equality comparisons b/w infinity and non-infinity are not constant folded.
// In such comparisons, special floating point types - Float80 and Float16, may
// come into play and pattern matching against them complicates the constant folding
// logic more than we'd like.
private func checkIfEqCmpBetweenInfAndNonInf(op: FPOperation, op1: FPOperand, op2: FPOperand) -> Bool {
if op == .Equal || op == .NotEqual {
// If only one of the operands is infinity
if (op1 == .Infinity || op2 == .Infinity) && !(op1 == .Infinity && op2 == .Infinity) {
return true
}
}
return false
}
}
////////////////// Arithmetic Operations Validator ///////////////////
struct FPConstantFoldedArithmeticOpsValidator: FPOptimizedOpsValidator {
/// Type of floating points this validator deals with.
enum _FpType : CaseIterable, Representable, Equatable {
case Float
case Double
func math_name() -> String {
switch self {
case .Float:
return "Float"
case .Double:
return "Double"
}
}
func printable_name() -> String {
switch self {
case .Float:
return "float"
case .Double:
return "double"
}
}
}
/// Type of floating point operations this validator deals with.
enum _FPOperation : CaseIterable, Representable, Equatable {
case Add
case Subtract
case Multiply
case Divide
func math_name() -> String {
switch self {
case .Add:
return "+"
case .Subtract:
return "-"
case .Multiply:
return "*"
case .Divide:
return "/"
}
}
func printable_name() -> String {
switch self {
case .Add:
return "add"
case .Subtract:
return "sub"
case .Multiply:
return "mul"
case .Divide:
return "div"
}
}
}
/// Type of floating point operands this validator deals with.
enum _FPOperand : CaseIterable, Representable, Equatable {
case Zero
case One
func math_name() -> String {
switch self {
case .Zero:
return "0.0"
case .One:
return "1.0"
}
}
func printable_name() -> String {
switch self {
case .Zero:
return "zero"
case .One:
return "one"
}
}
}
private let optPrefix = "opt"
private let unoptPrefix = "unopt"
/////////////////////// FPOptimizedOpsValidator Conformances ///////////////////////
typealias FPType = _FpType
typealias FPOperation = _FPOperation
typealias FPOperand = _FPOperand
func optimizedFunDeclCheck(
fpType: FPType,
op: FPOperation,
op1: FPOperand,
op2: FPOperand
) -> String {
let funcName = [optPrefix, fpType.printable_name(), op.printable_name(), op1.printable_name(), op2.printable_name()].joined(separator: "_")
return """
// CHECK-SIL-LABEL: sil hidden [noinline] @\(funcName)
// CHECK-SIL-NEXT: [global: ]
// CHECK-SIL-NEXT: bb0:
// CHECK-SIL-NOT: {{.*}}f\(op.printable_name()){{.*}}
// CHECK-SIL: } // end sil function '\(funcName)'
"""
}
func unoptimizedFunDeclCheck(
fpType: FPType,
op: FPOperation,
op1: FPOperand,
op2: FPOperand
) -> String {
let funcName = [unoptPrefix, fpType.printable_name(), op.printable_name(), op1.printable_name(), op2.printable_name()].joined(separator: "_")
return """
// CHECK-SIL-LABEL: sil hidden [noinline] [Onone] @\(funcName)
// CHECK-SIL-NEXT: bb0:
// CHECK-SIL: {{.*}}f\(op.printable_name()){{.*}}
// CHECK-SIL: } // end sil function '\(funcName)'
"""
}
func resultComparisonCheck(
fpType: FPType,
op: FPOperation,
op1: FPOperand,
op2: FPOperand
) -> String {
let comparisonFuncName = ["comparison", fpType.printable_name(), op.printable_name(), op1.printable_name(), op2.printable_name()].joined(separator: "_")
// 0.0 / 0.0 is NaN and Nan != Nan
if op == .Divide && op1 == .Zero && op2 == .Zero {
return """
precondition(!\(comparisonFuncName)(), "\(comparisonFuncName) returned true. Expected false.")
"""
}
return """
precondition(\(comparisonFuncName)(), "\(comparisonFuncName) returned false. Expected true.")
"""
}
func generateOptimizedFuncDecls() {
for fpType in FPType.allCases {
for op in FPOperation.allCases {
for op1 in FPOperand.allCases {
for op2 in FPOperand.allCases {
generateFuncDeclWithCheckDirectives(fpType: fpType, op: op, op1: op1, op2: op2, isopt: true)
}
}
}
}
}
func generateUnoptimizedFuncDecls() {
for fpType in FPType.allCases {
for op in FPOperation.allCases {
for op1 in FPOperand.allCases {
for op2 in FPOperand.allCases {
generateFuncDeclWithCheckDirectives(fpType: fpType, op: op, op1: op1, op2: op2, isopt: false)
}
}
}
}
}
func generateComparisonFuncDecls() {
for fpType in FPType.allCases {
for op in FPOperation.allCases {
for op1 in FPOperand.allCases {
for op2 in FPOperand.allCases {
let comparisonFuncName = ["comparison", fpType.printable_name(), op.printable_name(), op1.printable_name(), op2.printable_name()].joined(separator: "_")
let optFuncName = [optPrefix, fpType.printable_name(), op.printable_name(), op1.printable_name(), op2.printable_name()].joined(separator: "_")
let unoptFuncName = [unoptPrefix, fpType.printable_name(), op.printable_name(), op1.printable_name(), op2.printable_name()].joined(separator: "_")
print("""
@inline(never) @_silgen_name("\(comparisonFuncName)") @_optimize(none)
func \(comparisonFuncName)() -> Bool {
return \(optFuncName)() == \(unoptFuncName)()
}
""")
}
}
}
}
}
func generateComparisonFuncCalls() {
for fpType in FPType.allCases {
for op in FPOperation.allCases {
for op1 in FPOperand.allCases {
for op2 in FPOperand.allCases {
let comparison = resultComparisonCheck(fpType: fpType, op: op, op1: op1, op2: op2)
print("""
\(comparison)
""")
}
}
}
}
}
/////////////////////// Utilities ///////////////////////
private func generateFuncDeclWithCheckDirectives(
fpType: FPType,
op: FPOperation,
op1: FPOperand,
op2: FPOperand,
isopt: Bool = false
) {
var operand1 = op1.math_name()
var operand2 = op2.math_name()
if !isopt {
if fpType == .Double {
operand1 = op1 == .Zero ? "zero_double()": "one_double()"
operand2 = op2 == .Zero ? "zero_double()": "one_double()"
} else {
operand1 = op1 == .Zero ? "zero_float()": "one_float()"
operand2 = op2 == .Zero ? "zero_float()": "one_float()"
}
}
let optPrefix = isopt ? optPrefix : unoptPrefix
let optAttr = isopt ? "" : "@_optimize(none)"
let funcName = [optPrefix, fpType.printable_name(), op.printable_name(), op1.printable_name(), op2.printable_name()].joined(separator: "_")
let checkDirectives = isopt ?
optimizedFunDeclCheck(fpType: fpType, op: op, op1: op1, op2: op2) :
unoptimizedFunDeclCheck(fpType: fpType, op: op, op1: op1, op2: op2)
print("""
@inline(never) @_silgen_name("\(funcName)") \(optAttr)
func \(funcName)() -> \(fpType.math_name()) {
return \(operand1) \(op.math_name()) \(operand2)
}
\(checkDirectives)
""")
}
}