-
Notifications
You must be signed in to change notification settings - Fork 56
/
AtomicFUTransformer.kt
1518 lines (1413 loc) · 72.9 KB
/
AtomicFUTransformer.kt
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
/*
* Copyright 2016-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
@file:Suppress("EXPERIMENTAL_FEATURE_WARNING")
package kotlinx.atomicfu.transformer
import org.objectweb.asm.*
import org.objectweb.asm.ClassReader.*
import org.objectweb.asm.Opcodes.*
import org.objectweb.asm.Type.*
import org.objectweb.asm.commons.*
import org.objectweb.asm.commons.InstructionAdapter.*
import org.objectweb.asm.tree.*
import java.io.*
import java.net.*
import java.util.*
class TypeInfo(val fuType: Type, val originalType: Type, val transformedType: Type)
private const val AFU_PKG = "kotlinx/atomicfu"
private const val JUCA_PKG = "java/util/concurrent/atomic"
private const val JLI_PKG = "java/lang/invoke"
private const val ATOMIC = "atomic"
private const val TRACE = "Trace"
private const val TRACE_BASE = "TraceBase"
private const val TRACE_FORMAT = "TraceFormat"
private val INT_ARRAY_TYPE = getType("[I")
private val LONG_ARRAY_TYPE = getType("[J")
private val BOOLEAN_ARRAY_TYPE = getType("[Z")
private val REF_ARRAY_TYPE = getType("[Ljava/lang/Object;")
private val REF_TYPE = getType("L$AFU_PKG/AtomicRef;")
private val ATOMIC_ARRAY_TYPE = getType("L$AFU_PKG/AtomicArray;")
private val AFU_CLASSES: Map<String, TypeInfo> = mapOf(
"$AFU_PKG/AtomicInt" to TypeInfo(getObjectType("$JUCA_PKG/AtomicIntegerFieldUpdater"), INT_TYPE, INT_TYPE),
"$AFU_PKG/AtomicLong" to TypeInfo(getObjectType("$JUCA_PKG/AtomicLongFieldUpdater"), LONG_TYPE, LONG_TYPE),
"$AFU_PKG/AtomicRef" to TypeInfo(getObjectType("$JUCA_PKG/AtomicReferenceFieldUpdater"), OBJECT_TYPE, OBJECT_TYPE),
"$AFU_PKG/AtomicBoolean" to TypeInfo(getObjectType("$JUCA_PKG/AtomicIntegerFieldUpdater"), BOOLEAN_TYPE, INT_TYPE),
"$AFU_PKG/AtomicIntArray" to TypeInfo(getObjectType("$JUCA_PKG/AtomicIntegerArray"), INT_ARRAY_TYPE, INT_ARRAY_TYPE),
"$AFU_PKG/AtomicLongArray" to TypeInfo(getObjectType("$JUCA_PKG/AtomicLongArray"), LONG_ARRAY_TYPE, LONG_ARRAY_TYPE),
"$AFU_PKG/AtomicBooleanArray" to TypeInfo(getObjectType("$JUCA_PKG/AtomicIntegerArray"), BOOLEAN_ARRAY_TYPE, INT_ARRAY_TYPE),
"$AFU_PKG/AtomicArray" to TypeInfo(getObjectType("$JUCA_PKG/AtomicReferenceArray"), REF_ARRAY_TYPE, REF_ARRAY_TYPE),
"$AFU_PKG/AtomicFU_commonKt" to TypeInfo(getObjectType("$JUCA_PKG/AtomicReferenceArray"), REF_ARRAY_TYPE, REF_ARRAY_TYPE)
)
private val WRAPPER: Map<Type, String> = mapOf(
INT_TYPE to "java/lang/Integer",
LONG_TYPE to "java/lang/Long",
BOOLEAN_TYPE to "java/lang/Boolean"
)
private val ARRAY_ELEMENT_TYPE: Map<Type, Int> = mapOf(
INT_ARRAY_TYPE to T_INT,
LONG_ARRAY_TYPE to T_LONG,
BOOLEAN_ARRAY_TYPE to T_BOOLEAN
)
private val AFU_TYPES: Map<Type, TypeInfo> = AFU_CLASSES.mapKeys { getObjectType(it.key) }
private val METHOD_HANDLES = "$JLI_PKG/MethodHandles"
private val LOOKUP = "$METHOD_HANDLES\$Lookup"
private val VH_TYPE = getObjectType("$JLI_PKG/VarHandle")
private val STRING_TYPE = getObjectType("java/lang/String")
private val CLASS_TYPE = getObjectType("java/lang/Class")
private fun String.prettyStr() = replace('/', '.')
data class MethodId(val owner: String, val name: String, val desc: String, val invokeOpcode: Int) {
override fun toString(): String = "${owner.prettyStr()}::$name"
}
private const val GET_VALUE = "getValue"
private const val SET_VALUE = "setValue"
private const val GET_SIZE = "getSize"
private const val AFU_CLS = "$AFU_PKG/AtomicFU"
private const val TRACE_KT = "$AFU_PKG/TraceKt"
private const val TRACE_BASE_CLS = "$AFU_PKG/$TRACE_BASE"
private val TRACE_BASE_TYPE = getObjectType(TRACE_BASE_CLS)
private val TRACE_APPEND = MethodId(TRACE_BASE_CLS, "append", getMethodDescriptor(VOID_TYPE, OBJECT_TYPE), INVOKEVIRTUAL)
private val TRACE_APPEND_2 = MethodId(TRACE_BASE_CLS, "append", getMethodDescriptor(VOID_TYPE, OBJECT_TYPE, OBJECT_TYPE), INVOKEVIRTUAL)
private val TRACE_APPEND_3 = MethodId(TRACE_BASE_CLS, "append", getMethodDescriptor(VOID_TYPE, OBJECT_TYPE, OBJECT_TYPE, OBJECT_TYPE), INVOKEVIRTUAL)
private val TRACE_APPEND_4 = MethodId(TRACE_BASE_CLS, "append", getMethodDescriptor(VOID_TYPE, OBJECT_TYPE, OBJECT_TYPE, OBJECT_TYPE, OBJECT_TYPE), INVOKEVIRTUAL)
private val TRACE_DEFAULT_ARGS = "I${OBJECT_TYPE.descriptor}"
private const val DEFAULT = "\$default"
private val TRACE_FACTORY = MethodId(TRACE_KT, TRACE, "(IL$AFU_PKG/$TRACE_FORMAT;)L$AFU_PKG/$TRACE_BASE;", INVOKESTATIC)
private val TRACE_PARTIAL_ARGS_FACTORY = MethodId(TRACE_KT, "$TRACE$DEFAULT", "(IL$AFU_PKG/$TRACE_FORMAT;$TRACE_DEFAULT_ARGS)L$AFU_PKG/$TRACE_BASE;", INVOKESTATIC)
private val FACTORIES: Set<MethodId> = setOf(
MethodId(AFU_CLS, ATOMIC, "(Ljava/lang/Object;)L$AFU_PKG/AtomicRef;", INVOKESTATIC),
MethodId(AFU_CLS, ATOMIC, "(I)L$AFU_PKG/AtomicInt;", INVOKESTATIC),
MethodId(AFU_CLS, ATOMIC, "(J)L$AFU_PKG/AtomicLong;", INVOKESTATIC),
MethodId(AFU_CLS, ATOMIC, "(Z)L$AFU_PKG/AtomicBoolean;", INVOKESTATIC),
MethodId("$AFU_PKG/AtomicIntArray", "<init>", "(I)V", INVOKESPECIAL),
MethodId("$AFU_PKG/AtomicLongArray", "<init>", "(I)V", INVOKESPECIAL),
MethodId("$AFU_PKG/AtomicBooleanArray", "<init>", "(I)V", INVOKESPECIAL),
MethodId("$AFU_PKG/AtomicArray", "<init>", "(I)V", INVOKESPECIAL),
MethodId("$AFU_PKG/AtomicFU_commonKt", "atomicArrayOfNulls", "(I)L$AFU_PKG/AtomicArray;", INVOKESTATIC),
MethodId(AFU_CLS, ATOMIC, "(Ljava/lang/Object;L$TRACE_BASE_CLS;)L$AFU_PKG/AtomicRef;", INVOKESTATIC),
MethodId(AFU_CLS, ATOMIC, "(IL$TRACE_BASE_CLS;)L$AFU_PKG/AtomicInt;", INVOKESTATIC),
MethodId(AFU_CLS, ATOMIC, "(JL$TRACE_BASE_CLS;)L$AFU_PKG/AtomicLong;", INVOKESTATIC),
MethodId(AFU_CLS, ATOMIC, "(ZL$TRACE_BASE_CLS;)L$AFU_PKG/AtomicBoolean;", INVOKESTATIC),
MethodId(AFU_CLS, ATOMIC + DEFAULT, "(Ljava/lang/Object;L$TRACE_BASE_CLS;$TRACE_DEFAULT_ARGS)L$AFU_PKG/AtomicRef;", INVOKESTATIC),
MethodId(AFU_CLS, ATOMIC + DEFAULT, "(IL$TRACE_BASE_CLS;$TRACE_DEFAULT_ARGS)L$AFU_PKG/AtomicInt;", INVOKESTATIC),
MethodId(AFU_CLS, ATOMIC + DEFAULT, "(JL$TRACE_BASE_CLS;$TRACE_DEFAULT_ARGS)L$AFU_PKG/AtomicLong;", INVOKESTATIC),
MethodId(AFU_CLS, ATOMIC + DEFAULT, "(ZL$TRACE_BASE_CLS;$TRACE_DEFAULT_ARGS)L$AFU_PKG/AtomicBoolean;", INVOKESTATIC)
)
private operator fun Int.contains(bit: Int) = this and bit != 0
private inline fun code(mv: MethodVisitor, block: InstructionAdapter.() -> Unit) {
block(InstructionAdapter(mv))
}
private inline fun insns(block: InstructionAdapter.() -> Unit): InsnList {
val node = MethodNode(ASM9)
block(InstructionAdapter(node))
return node.instructions
}
data class FieldId(val owner: String, val name: String, val desc: String) {
override fun toString(): String = "${owner.prettyStr()}::$name"
}
class FieldInfo(
val fieldId: FieldId,
val fieldType: Type,
val isStatic: Boolean = false
) {
val owner = fieldId.owner
val ownerType: Type = getObjectType(owner)
val typeInfo = AFU_CLASSES.getValue(fieldType.internalName)
val fuType = typeInfo.fuType
val isArray = typeInfo.originalType.sort == ARRAY
// state: updated during analysis
val accessors = mutableSetOf<MethodId>() // set of accessor method that read the corresponding atomic
var hasExternalAccess = false // accessed from different package
var hasAtomicOps = false // has atomic operations operations other than getValue/setValue
val name: String
get() = if (hasExternalAccess) mangleInternal(fieldId.name) else fieldId.name
val fuName: String
get() {
val fuName = fieldId.name + '$' + "FU"
return if (hasExternalAccess) mangleInternal(fuName) else fuName
}
val refVolatileClassName = "${owner.replace('.', '/')}$${name.capitalize()}RefVolatile"
val staticRefVolatileField = refVolatileClassName.substringAfterLast("/").decapitalize()
fun getPrimitiveType(vh: Boolean): Type = if (vh) typeInfo.originalType else typeInfo.transformedType
private fun mangleInternal(fieldName: String): String = "$fieldName\$internal"
override fun toString(): String = "${owner.prettyStr()}::$name"
}
enum class JvmVariant { FU, VH, BOTH }
class AtomicFUTransformer(
classpath: List<String>,
inputDir: File,
outputDir: File = inputDir,
var jvmVariant: JvmVariant = JvmVariant.FU
) : AtomicFUTransformerBase(inputDir, outputDir) {
private val classPathLoader = URLClassLoader(
(listOf(inputDir) + (classpath.map { File(it) } - outputDir))
.map { it.toURI().toURL() }.toTypedArray()
)
private val fields = mutableMapOf<FieldId, FieldInfo>()
private val accessors = mutableMapOf<MethodId, FieldInfo>()
private val traceFields = mutableSetOf<FieldId>()
private val traceAccessors = mutableSetOf<MethodId>()
private val fieldDelegates = mutableMapOf<FieldId, FieldInfo>()
private val delegatedPropertiesAccessors = mutableMapOf<FieldId, MethodId>()
private val removeMethods = mutableSetOf<MethodId>()
override fun transform() {
info("Analyzing in $inputDir")
val files = inputDir.walk().filter { it.isFile }.toList()
val needTransform = analyzeFilesForFields(files)
if (needTransform || outputDir == inputDir) {
val vh = jvmVariant == JvmVariant.VH
// visit method bodies for external references to fields, runs all logic, fails if anything is wrong
val needsTransform = analyzeFilesForRefs(files, vh)
// perform transformation
info("Transforming to $outputDir")
files.forEach { file ->
val bytes = file.readBytes()
val outBytes = if (file.isClassFile() && file in needsTransform) transformFile(file, bytes, vh) else bytes
val outFile = file.toOutputFile()
outFile.mkdirsAndWrite(outBytes)
if (jvmVariant == JvmVariant.BOTH && outBytes !== bytes) {
val vhBytes = transformFile(file, bytes, true)
val vhFile = outputDir / "META-INF" / "versions" / "9" / file.relativeTo(inputDir).toString()
vhFile.mkdirsAndWrite(vhBytes)
}
}
} else {
info("Nothing to transform -- all classes are up to date")
}
}
// Phase 1: visit methods and fields, register all accessors, collect times
// Returns 'true' if any files are out of date
private fun analyzeFilesForFields(files: List<File>): Boolean {
var needTransform = false
files.forEach { file ->
val inpTime = file.lastModified()
val outTime = file.toOutputFile().lastModified()
if (inpTime > outTime) needTransform = true
if (file.isClassFile()) analyzeFileForFields(file)
}
if (lastError != null) throw TransformerException("Encountered errors while analyzing fields", lastError)
return needTransform
}
private fun analyzeFileForFields(file: File) {
file.inputStream().use { ClassReader(it).accept(FieldsCollectorCV(), SKIP_FRAMES) }
}
// Phase2: visit method bodies for external references to fields and
// run method analysis in "analysisMode" to see which fields need AU/VH generated for them
// Returns a set of files that need transformation
private fun analyzeFilesForRefs(files: List<File>, vh: Boolean): Set<File> {
val result = HashSet<File>()
files.forEach { file ->
if (file.isClassFile() && analyzeFileForRefs(file, vh)) result += file
}
// Batch analyze all files, report all errors, bail out only at the end
if (lastError != null) throw TransformerException("Encountered errors while analyzing references", lastError)
return result
}
private fun analyzeFileForRefs(file: File, vh: Boolean): Boolean =
file.inputStream().use { input ->
transformed = false // clear global "transformed" flag
val cv = TransformerCV(null, vh, analyzePhase2 = true)
try {
ClassReader(input).accept(cv, SKIP_FRAMES)
} catch (e: Exception) {
error("Failed to analyze: $e", cv.sourceInfo)
e.printStackTrace(System.out)
if (lastError == null) lastError = e
}
transformed // true for classes that need transformation
}
// Phase 3: Transform file (only called for files that need to be transformed)
// Returns updated byte array for class data
private fun transformFile(file: File, bytes: ByteArray, vh: Boolean): ByteArray {
transformed = false // clear global "transformed" flag
val cw = CW()
val cv = TransformerCV(cw, vh, analyzePhase2 = false)
try {
ClassReader(ByteArrayInputStream(bytes)).accept(cv, SKIP_FRAMES)
} catch (e: Throwable) {
error("Failed to transform: $e", cv.sourceInfo)
e.printStackTrace(System.out)
if (lastError == null) lastError = e
}
if (!transformed) error("Invoked transformFile on a file that does not need transformation: $file")
if (lastError != null) throw TransformerException("Encountered errors while transforming: $file", lastError)
info("Transformed $file")
return cw.toByteArray() // write transformed bytes
}
private abstract inner class CV(cv: ClassVisitor?) : ClassVisitor(ASM9, cv) {
lateinit var className: String
override fun visit(
version: Int,
access: Int,
name: String,
signature: String?,
superName: String?,
interfaces: Array<out String>?
) {
className = name
super.visit(version, access, name, signature, superName, interfaces)
}
}
private fun registerField(field: FieldId, fieldType: Type, isStatic: Boolean): FieldInfo {
val result = fields.getOrPut(field) { FieldInfo(field, fieldType, isStatic) }
if (result.fieldType != fieldType) abort("$field type mismatch between $fieldType and ${result.fieldType}")
return result
}
private inner class FieldsCollectorCV : CV(null) {
override fun visitField(
access: Int,
name: String,
desc: String,
signature: String?,
value: Any?
): FieldVisitor? {
val fieldType = getType(desc)
if (fieldType.sort == OBJECT && fieldType.internalName in AFU_CLASSES) {
val field = FieldId(className, name, desc)
info("$field field found")
if (ACC_PUBLIC in access) error("$field field cannot be public")
if (ACC_FINAL !in access) error("$field field must be final")
registerField(field, fieldType, (ACC_STATIC in access))
}
return null
}
override fun visitMethod(
access: Int,
name: String,
desc: String,
signature: String?,
exceptions: Array<out String>?
): MethodVisitor? {
val methodType = getMethodType(desc)
if (methodType.argumentTypes.any { it in AFU_TYPES }) {
val methodId = MethodId(className, name, desc, accessToInvokeOpcode(access))
info("$methodId method to be removed")
removeMethods += methodId
}
getPotentialAccessorType(access, className, methodType)?.let { onType ->
return AccessorCollectorMV(onType.internalName, access, name, desc, signature, exceptions)
}
if (name == "<init>" || name == "<clinit>") {
// check for copying atomic values into delegate fields and register potential delegate fields
return DelegateFieldsCollectorMV(access, name, desc, signature, exceptions)
}
// collect accessors of potential delegated properties
if (methodType.argumentTypes.isEmpty()) {
return DelegatedFieldAccessorCollectorMV(className, methodType.returnType, access, name, desc, signature, exceptions)
}
return null
}
}
private inner class AccessorCollectorMV(
private val className: String,
access: Int, name: String, desc: String, signature: String?, exceptions: Array<out String>?
) : MethodNode(ASM9, access, name, desc, signature, exceptions) {
override fun visitEnd() {
val insns = instructions.listUseful(4)
if (insns.size == 3 &&
insns[0].isAload(0) &&
insns[1].isGetField(className) &&
insns[2].isAreturn() ||
insns.size == 2 &&
insns[0].isGetStatic(className) &&
insns[1].isAreturn()
) {
val isStatic = insns.size == 2
val fi = (if (isStatic) insns[0] else insns[1]) as FieldInsnNode
val fieldName = fi.name
val field = FieldId(className, fieldName, fi.desc)
val fieldType = getType(fi.desc)
val accessorMethod = MethodId(className, name, desc, accessToInvokeOpcode(access))
info("$field accessor $name found")
if (fieldType == TRACE_BASE_TYPE) {
traceAccessors.add(accessorMethod)
} else {
val fieldInfo = registerField(field, fieldType, isStatic)
fieldInfo.accessors += accessorMethod
accessors[accessorMethod] = fieldInfo
}
}
}
}
// returns a type on which this is a potential accessor
private fun getPotentialAccessorType(access: Int, className: String, methodType: Type): Type? {
if (methodType.returnType !in AFU_TYPES && methodType.returnType != TRACE_BASE_TYPE) return null
return if (access and ACC_STATIC != 0) {
if (access and ACC_FINAL != 0 && methodType.argumentTypes.isEmpty()) {
// accessor for top-level atomic
getObjectType(className)
} else {
// accessor for top-level atomic
if (methodType.argumentTypes.size == 1 && methodType.argumentTypes[0].sort == OBJECT)
methodType.argumentTypes[0] else null
}
} else {
// if it not static, then it must be final
if (access and ACC_FINAL != 0 && methodType.argumentTypes.isEmpty())
getObjectType(className) else null
}
}
private inner class DelegatedFieldAccessorCollectorMV(
private val className: String, private val returnType: Type,
access: Int, name: String, desc: String, signature: String?, exceptions: Array<out String>?
) : MethodNode(ASM5, access, name, desc, signature, exceptions) {
override fun visitEnd() {
// check for pattern of a delegated property getter
// getfield/getstatic a$delegate: Atomic*
// astore_i ...
// aload_i
// invokevirtual Atomic*.getValue()
// ireturn
var cur = instructions.first
while (cur != null && !(cur.isGetFieldOrGetStatic() && getType((cur as FieldInsnNode).desc) in AFU_TYPES)) {
cur = cur.next
}
if (cur != null && cur.next.opcode == ASTORE) {
val fi = cur as FieldInsnNode
val fieldDelegate = FieldId(className, fi.name, fi.desc)
val atomicType = getType(fi.desc)
val v = (cur.next as VarInsnNode).`var`
while (!(cur is VarInsnNode && cur.opcode == ALOAD && cur.`var` == v)) {
cur = cur.next
}
val invokeVirtual = cur.next
if (invokeVirtual.opcode == INVOKEVIRTUAL && (invokeVirtual as MethodInsnNode).name == GET_VALUE && invokeVirtual.owner == atomicType.internalName) {
// followed by RETURN operation
val next = invokeVirtual.nextUseful
val ret = if (next?.opcode == CHECKCAST) next.nextUseful else next
if (ret != null && ret.isTypeReturn(returnType)) {
// register delegated property accessor
delegatedPropertiesAccessors[fieldDelegate] = MethodId(className, name, desc, accessToInvokeOpcode(access))
}
}
}
}
}
private inner class DelegateFieldsCollectorMV(
access: Int, name: String, desc: String, signature: String?, exceptions: Array<out String>?
) : MethodNode(ASM9, access, name, desc, signature, exceptions) {
override fun visitEnd() {
// register delegate field and the corresponding original atomic field
// getfield a: *Atomic
// putfield a$delegate: *Atomic
instructions.forEach { insn ->
if (insn is FieldInsnNode) {
insn.checkGetFieldOrGetStatic()?.let { getfieldId ->
val next = insn.next
(next as? FieldInsnNode)?.checkPutFieldOrPutStatic()?.let { delegateFieldId ->
if (getfieldId in fields && delegateFieldId in fields) {
// original atomic value is copied to the synthetic delegate atomic field <delegated field name>$delegate
val originalField = fields[getfieldId]!!
fieldDelegates[delegateFieldId] = originalField
}
}
}
}
if (insn is MethodInsnNode) {
val methodId = MethodId(insn.owner, insn.name, insn.desc, insn.opcode)
if (methodId in FACTORIES) {
(insn.nextUseful as? FieldInsnNode)?.checkPutFieldOrPutStatic()?.let { delegateFieldId ->
val fieldType = getType(insn.desc).returnType
if (fieldType in AFU_TYPES) {
val isStatic = insn.nextUseful!!.opcode == PUTSTATIC
// delegate field is initialized by a factory invocation
// for volatile delegated properties store FieldInfo of the delegate field itself
fieldDelegates[delegateFieldId] = FieldInfo(delegateFieldId, fieldType, isStatic)
}
}
}
}
}
}
}
private fun descToName(desc: String): String = desc.drop(1).dropLast(1)
private fun FieldInsnNode.checkPutFieldOrPutStatic(): FieldId? {
if (opcode != PUTFIELD && opcode != PUTSTATIC) return null
val fieldId = FieldId(owner, name, desc)
return if (fieldId in fields) fieldId else null
}
private fun FieldInsnNode.checkGetFieldOrGetStatic(): FieldId? {
if (opcode != GETFIELD && opcode != GETSTATIC) return null
val fieldId = FieldId(owner, name, desc)
return if (fieldId in fields) fieldId else null
}
private fun FieldId.isFieldDelegate() = this in fieldDelegates && delegatedPropertiesAccessors.contains(this)
private inner class TransformerCV(
cv: ClassVisitor?,
private val vh: Boolean,
private val analyzePhase2: Boolean // true in Phase 2 when we are analyzing file for refs (not transforming yet)
) : CV(cv) {
private var source: String? = null
var sourceInfo: SourceInfo? = null
private var metadata: AnnotationNode? = null
private var originalClinit: MethodNode? = null
private var newClinit: MethodNode? = null
private fun newClinit() = MethodNode(ASM9, ACC_STATIC, "<clinit>", "()V", null, null)
fun getOrCreateNewClinit(): MethodNode = newClinit ?: newClinit().also { newClinit = it }
override fun visitSource(source: String?, debug: String?) {
this.source = source
super.visitSource(source, debug)
}
override fun visitField(
access: Int,
name: String,
desc: String,
signature: String?,
value: Any?
): FieldVisitor? {
val fieldType = getType(desc)
if (fieldType.sort == OBJECT && fieldType.internalName in AFU_CLASSES) {
val fieldId = FieldId(className, name, desc)
// skip field delegates except volatile delegated properties (e.g. val a: Int by atomic(0))
if (fieldId.isFieldDelegate() && (fieldId != fieldDelegates[fieldId]!!.fieldId)) {
transformed = true
return null
}
val f = fields[fieldId]!!
val visibility = when {
f.hasExternalAccess -> ACC_PUBLIC
f.accessors.isEmpty() -> ACC_PRIVATE
else -> 0
}
val protection = ACC_SYNTHETIC or visibility or when {
// reference to wrapper class (primitive atomics) or reference to to j.u.c.a.Atomic*Array (atomic array)
f.isStatic && !vh -> ACC_STATIC or ACC_FINAL
// primitive type field
f.isStatic && vh -> ACC_STATIC
else -> 0
}
val primitiveType = f.getPrimitiveType(vh)
val fv = when {
// replace (top-level) Atomic*Array with (static) j.u.c.a/Atomic*Array field
f.isArray && !vh -> super.visitField(protection, f.name, f.fuType.descriptor, null, null)
// replace top-level primitive atomics with static instance of the corresponding wrapping *RefVolatile class
f.isStatic && !vh -> super.visitField(
protection,
f.staticRefVolatileField,
getObjectType(f.refVolatileClassName).descriptor,
null,
null
)
// volatile primitive type field
else -> super.visitField(protection or ACC_VOLATILE, f.name, primitiveType.descriptor, null, null)
}
if (vh) {
// VarHandle is needed for all array element accesses and for regular fields with atomic ops
if (f.hasAtomicOps || f.isArray) vhField(protection, f)
} else {
// FieldUpdater is not needed for arrays (they use AtomicArrays)
if (f.hasAtomicOps && !f.isArray) fuField(protection, f)
}
transformed = true
return fv
}
// skip trace field
if (fieldType == TRACE_BASE_TYPE) {
traceFields += FieldId(className, name, desc)
transformed = true
return null
}
return super.visitField(access, name, desc, signature, value)
}
// Generates static VarHandle field
private fun vhField(protection: Int, f: FieldInfo) {
super.visitField(protection or ACC_FINAL or ACC_STATIC, f.fuName, VH_TYPE.descriptor, null, null)
code(getOrCreateNewClinit()) {
if (!f.isArray) {
invokestatic(METHOD_HANDLES, "lookup", "()L$LOOKUP;", false)
aconst(getObjectType(className))
aconst(f.name)
val primitiveType = f.getPrimitiveType(vh)
if (primitiveType.sort == OBJECT) {
aconst(primitiveType)
} else {
val wrapper = WRAPPER.getValue(primitiveType)
getstatic(wrapper, "TYPE", CLASS_TYPE.descriptor)
}
val findVHName = if (f.isStatic) "findStaticVarHandle" else "findVarHandle"
invokevirtual(
LOOKUP, findVHName,
getMethodDescriptor(VH_TYPE, CLASS_TYPE, STRING_TYPE, CLASS_TYPE), false
)
putstatic(className, f.fuName, VH_TYPE.descriptor)
} else {
// create VarHandle for array
aconst(f.getPrimitiveType(vh))
invokestatic(
METHOD_HANDLES,
"arrayElementVarHandle",
getMethodDescriptor(VH_TYPE, CLASS_TYPE),
false
)
putstatic(className, f.fuName, VH_TYPE.descriptor)
}
}
}
// Generates static AtomicXXXFieldUpdater field
private fun fuField(protection: Int, f: FieldInfo) {
super.visitField(protection or ACC_FINAL or ACC_STATIC, f.fuName, f.fuType.descriptor, null, null)
code(getOrCreateNewClinit()) {
val params = mutableListOf<Type>()
params += CLASS_TYPE
if (!f.isStatic) aconst(getObjectType(className)) else aconst(getObjectType(f.refVolatileClassName))
val primitiveType = f.getPrimitiveType(vh)
if (primitiveType.sort == OBJECT) {
params += CLASS_TYPE
aconst(primitiveType)
}
params += STRING_TYPE
aconst(f.name)
invokestatic(
f.fuType.internalName,
"newUpdater",
getMethodDescriptor(f.fuType, *params.toTypedArray()),
false
)
putstatic(className, f.fuName, f.fuType.descriptor)
}
}
override fun visitMethod(
access: Int,
name: String,
desc: String,
signature: String?,
exceptions: Array<out String>?
): MethodVisitor? {
val methodId = MethodId(className, name, desc, accessToInvokeOpcode(access))
if (methodId in accessors || methodId in traceAccessors || methodId in removeMethods) {
// drop and skip the methods that were found in Phase 1
// todo: should remove those methods from kotlin metadata, too
transformed = true
return null // drop accessor
}
val sourceInfo = SourceInfo(methodId, source)
val superMV = if (name == "<clinit>" && desc == "()V") {
if (access and ACC_STATIC == 0) abort("<clinit> method not marked as static")
// defer writing class initialization method
val node = MethodNode(ASM9, access, name, desc, signature, exceptions)
if (originalClinit != null) abort("Multiple <clinit> methods found")
originalClinit = node
node
} else {
// write transformed method to class right away
super.visitMethod(access, name, desc, signature, exceptions)
}
val mv = TransformerMV(
sourceInfo, access, name, desc, signature, exceptions, superMV,
className.ownerPackageName, vh, analyzePhase2
)
this.sourceInfo = mv.sourceInfo
return mv
}
override fun visitAnnotation(desc: String?, visible: Boolean): AnnotationVisitor? {
if (desc == KOTLIN_METADATA_DESC) {
check(visible) { "Expected run-time visible $KOTLIN_METADATA_DESC annotation" }
check(metadata == null) { "Only one $KOTLIN_METADATA_DESC annotation is expected" }
return AnnotationNode(desc).also { metadata = it }
}
return super.visitAnnotation(desc, visible)
}
override fun visitEnd() {
// remove unused methods from metadata
metadata?.let {
val mt = MetadataTransformer(
removeFields = fields.keys + traceFields,
removeMethods = accessors.keys + traceAccessors + removeMethods
)
if (mt.transformMetadata(it)) transformed = true
if (cv != null) it.accept(cv.visitAnnotation(KOTLIN_METADATA_DESC, true))
}
if (analyzePhase2) return // nop in analyze phase
// collect class initialization
if (originalClinit != null || newClinit != null) {
val newClinit = newClinit
if (newClinit == null) {
// dump just original clinit
originalClinit!!.accept(cv)
} else {
// create dummy base code if needed
val originalClinit = originalClinit ?: newClinit().also {
code(it) { visitInsn(RETURN) }
}
// makes sure return is last useful instruction
val last = originalClinit.instructions.last
val ret = last.thisOrPrevUseful
if (ret == null || !ret.isReturn()) abort("Last instruction in <clinit> shall be RETURN", ret)
originalClinit.instructions.insertBefore(ret, newClinit.instructions)
originalClinit.accept(cv)
}
}
super.visitEnd()
}
}
private inner class TransformerMV(
sourceInfo: SourceInfo,
access: Int, name: String, desc: String, signature: String?, exceptions: Array<out String>?,
mv: MethodVisitor?,
private val packageName: String,
private val vh: Boolean,
private val analyzePhase2: Boolean // true in Phase 2 when we are analyzing file for refs (not transforming yet)
) : MethodNode(ASM9, access, name, desc, signature, exceptions) {
init {
this.mv = mv
}
val sourceInfo = sourceInfo.copy(insnList = instructions)
private var tempLocal = 0
private var bumpedLocals = 0
private fun bumpLocals(n: Int) {
if (bumpedLocals == 0) tempLocal = maxLocals
while (n > bumpedLocals) bumpedLocals = n
maxLocals = tempLocal + bumpedLocals
}
override fun visitMethodInsn(opcode: Int, owner: String, name: String, desc: String, itf: Boolean) {
val methodId = MethodId(owner, name, desc, opcode)
val fieldInfo = accessors[methodId]
// compare owner packages
if (fieldInfo != null && methodId.owner.ownerPackageName != packageName) {
if (analyzePhase2) {
fieldInfo.hasExternalAccess = true
} else {
check(fieldInfo.hasExternalAccess) // should have been set on previous phase
}
}
super.visitMethodInsn(opcode, owner, name, desc, itf)
}
override fun visitEnd() {
// transform instructions list
var hasErrors = false
var i = instructions.first
while (i != null)
try {
i = transform(i)
} catch (e: AbortTransform) {
error(e.message!!, sourceInfo.copy(i = e.i))
i = i.next
hasErrors = true
}
// make sure all kotlinx/atomicfu references removed
removeAtomicReferencesFromLVT()
// save transformed method if not in analysis phase
if (!hasErrors && !analyzePhase2)
accept(mv)
}
private fun removeAtomicReferencesFromLVT() =
localVariables?.removeIf { getType(it.desc) in AFU_TYPES }
private fun FieldInsnNode.checkCopyToDelegate(): AbstractInsnNode? {
val fieldId = FieldId(owner, name, desc)
if (fieldId.isFieldDelegate()) {
// original atomic value is copied to the synthetic delegate atomic field <delegated field name>$delegate
val originalField = fieldDelegates[fieldId]!!
val getField = previous as FieldInsnNode
val next = this.next
if (!originalField.isStatic) instructions.remove(getField.previous) // no aload for static field
instructions.remove(getField)
instructions.remove(this)
return next
}
return null
}
// ld: instruction that loads atomic field (already changed to getstatic)
// iv: invoke virtual on the loaded atomic field (to be fixed)
private fun fixupInvokeVirtual(
ld: FieldInsnNode,
onArrayElement: Boolean, // true when fixing invokeVirtual on loaded array element
iv: MethodInsnNode,
f: FieldInfo
): AbstractInsnNode? {
check(f.isArray || !onArrayElement) { "Cannot fix array element access on non array fields" }
val typeInfo = if (onArrayElement) f.typeInfo else AFU_CLASSES.getValue(iv.owner)
if (iv.name == GET_VALUE || iv.name == SET_VALUE) {
check(!f.isArray || onArrayElement) { "getValue/setValue can only be called on elements of arrays" }
val setInsn = iv.name == SET_VALUE
if (!onArrayElement) return getPureTypeField(ld, f, iv)
var methodType = getMethodType(iv.desc)
if (f.typeInfo.originalType != f.typeInfo.transformedType && !vh) {
val ret = f.typeInfo.transformedType.elementType
iv.desc = if (setInsn) getMethodDescriptor(methodType.returnType, ret) else getMethodDescriptor(ret, *methodType.argumentTypes)
methodType = getMethodType(iv.desc)
}
iv.name = iv.name.substring(0, 3)
if (!vh) {
// map to j.u.c.a.Atomic*Array get or set
iv.owner = descToName(f.fuType.descriptor)
iv.desc = getMethodDescriptor(methodType.returnType, INT_TYPE, *methodType.argumentTypes)
} else {
// map to VarHandle get or set
iv.owner = descToName(VH_TYPE.descriptor)
iv.desc = getMethodDescriptor(
methodType.returnType,
f.getPrimitiveType(vh),
INT_TYPE,
*methodType.argumentTypes
)
}
return iv
}
if (f.isArray && iv.name == GET_SIZE) {
if (!vh) {
// map to j.u.c.a.Atomic*Array length()
iv.owner = descToName(f.fuType.descriptor)
iv.name = "length"
} else {
// replace with arraylength of the primitive type array
val arrayLength = InsnNode(ARRAYLENGTH)
instructions.insert(ld, arrayLength)
// do not need varhandle
if (!f.isStatic) {
instructions.remove(ld.previous.previous)
instructions.remove(ld.previous)
} else {
instructions.remove(ld.previous)
}
instructions.remove(iv)
return arrayLength
}
return iv
}
// An operation other than getValue/setValue is used
if (f.isArray && iv.name == "get") { // "operator get" that retrieves array element, further ops apply to it
// fixup atomic operation on this array element
return fixupLoadedArrayElement(f, ld, iv)
}
// non-trivial atomic operation
check(f.isArray == onArrayElement) { "Atomic operations can be performed on atomic elements only" }
if (analyzePhase2) {
f.hasAtomicOps = true // mark the fact that non-trivial atomic op is used here
} else {
check(f.hasAtomicOps) // should have been set on previous phase
}
// update method invocation
if (vh) {
vhOperation(iv, typeInfo, f)
} else {
fuOperation(iv, typeInfo, f)
}
if (f.isStatic && !onArrayElement) {
if (!vh) {
// getstatic *RefVolatile class
val aload = FieldInsnNode(
GETSTATIC,
f.owner,
f.staticRefVolatileField,
getObjectType(f.refVolatileClassName).descriptor
)
instructions.insert(ld, aload)
}
return iv.next
}
if (!onArrayElement) {
// insert swap after field load
val swap = InsnNode(SWAP)
instructions.insert(ld, swap)
return swap.next
}
return iv.next
}
private fun getPureTypeField(ld: FieldInsnNode, f: FieldInfo, iv: MethodInsnNode): AbstractInsnNode? {
val primitiveType = f.getPrimitiveType(vh)
val owner = if (!vh && f.isStatic) f.refVolatileClassName else f.owner
if (!vh && f.isStatic) {
val getOwnerClass = FieldInsnNode(
GETSTATIC,
f.owner,
f.staticRefVolatileField,
getObjectType(owner).descriptor
)
instructions.insert(ld, getOwnerClass)
}
instructions.remove(ld) // drop getfield/getstatic of the atomic field
val j = FieldInsnNode(
when {
iv.name == GET_VALUE -> if (f.isStatic && vh) GETSTATIC else GETFIELD
else -> if (f.isStatic && vh) PUTSTATIC else PUTFIELD
}, owner, f.name, primitiveType.descriptor
)
instructions.set(iv, j) // replace invokevirtual with get/setfield
return j.next
}
private fun vhOperation(iv: MethodInsnNode, typeInfo: TypeInfo, f: FieldInfo) {
val methodType = getMethodType(iv.desc)
val args = methodType.argumentTypes
iv.owner = VH_TYPE.internalName
val params = if (!f.isArray && !f.isStatic) mutableListOf<Type>(
OBJECT_TYPE,
*args
) else if (!f.isArray && f.isStatic) mutableListOf<Type>(*args) else mutableListOf(
typeInfo.originalType,
INT_TYPE,
*args
)
val elementType = if (f.isArray) typeInfo.originalType.elementType else typeInfo.originalType
val long = elementType == LONG_TYPE
when (iv.name) {
"lazySet" -> iv.name = "setRelease"
"getAndIncrement" -> {
instructions.insertBefore(iv, insns { if (long) lconst(1) else iconst(1) })
params += elementType
iv.name = "getAndAdd"
}
"getAndDecrement" -> {
instructions.insertBefore(iv, insns { if (long) lconst(-1) else iconst(-1) })
params += elementType
iv.name = "getAndAdd"
}
"addAndGet" -> {
bumpLocals(if (long) 2 else 1)
instructions.insertBefore(iv, insns {
if (long) dup2() else dup()
store(tempLocal, elementType)
})
iv.name = "getAndAdd"
instructions.insert(iv, insns {
load(tempLocal, elementType)
add(elementType)
})
}
"incrementAndGet" -> {
instructions.insertBefore(iv, insns { if (long) lconst(1) else iconst(1) })
params += elementType
iv.name = "getAndAdd"
instructions.insert(iv, insns {
if (long) lconst(1) else iconst(1)
add(elementType)
})
}
"decrementAndGet" -> {
instructions.insertBefore(iv, insns { if (long) lconst(-1) else iconst(-1) })
params += elementType
iv.name = "getAndAdd"
instructions.insert(iv, insns {
if (long) lconst(-1) else iconst(-1)
add(elementType)
})
}
}
iv.desc = getMethodDescriptor(methodType.returnType, *params.toTypedArray())
}
private fun fuOperation(iv: MethodInsnNode, typeInfo: TypeInfo, f: FieldInfo) {
val methodType = getMethodType(iv.desc)
val originalElementType = if (f.isArray) typeInfo.originalType.elementType else typeInfo.originalType
val transformedElementType =
if (f.isArray) typeInfo.transformedType.elementType else typeInfo.transformedType
val trans = originalElementType != transformedElementType
val args = methodType.argumentTypes
var ret = methodType.returnType
if (trans) {
args.forEachIndexed { i, type -> if (type == originalElementType) args[i] = transformedElementType }
if (iv.name == "getAndSet") ret = transformedElementType
}
if (f.isArray) {
// map to j.u.c.a.AtomicIntegerArray method
iv.owner = typeInfo.fuType.internalName
// add int argument as element index
iv.desc = getMethodDescriptor(ret, INT_TYPE, *args)
return // array operation in this mode does not use FU field
}
iv.owner = typeInfo.fuType.internalName
iv.desc = getMethodDescriptor(ret, OBJECT_TYPE, *args)
}
private fun tryEraseUncheckedCast(getter: AbstractInsnNode) {
if (getter.next.opcode == DUP && getter.next.next.opcode == IFNONNULL) {
// unchecked cast upon AtomicRef var is performed
// erase compiler check for this var being not null:
// (remove all insns from ld till the non null branch label)
val ifnonnull = (getter.next.next as JumpInsnNode)
var i: AbstractInsnNode = getter.next
while (!(i is LabelNode && i.label == ifnonnull.label.label)) {
val next = i.next
instructions.remove(i)