001 /*
002 * Copyright 2010-2015 JetBrains s.r.o.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017 package org.jetbrains.kotlin.codegen.inline;
018
019 import com.intellij.openapi.vfs.VirtualFile;
020 import com.intellij.psi.PsiFile;
021 import kotlin.text.StringsKt;
022 import org.jetbrains.annotations.NotNull;
023 import org.jetbrains.annotations.Nullable;
024 import org.jetbrains.kotlin.backend.common.output.OutputFile;
025 import org.jetbrains.kotlin.builtins.KotlinBuiltIns;
026 import org.jetbrains.kotlin.codegen.AsmUtil;
027 import org.jetbrains.kotlin.codegen.ExpressionCodegen;
028 import org.jetbrains.kotlin.codegen.MemberCodegen;
029 import org.jetbrains.kotlin.codegen.binding.CodegenBinding;
030 import org.jetbrains.kotlin.codegen.context.CodegenContext;
031 import org.jetbrains.kotlin.codegen.context.CodegenContextUtil;
032 import org.jetbrains.kotlin.codegen.context.InlineLambdaContext;
033 import org.jetbrains.kotlin.codegen.context.MethodContext;
034 import org.jetbrains.kotlin.codegen.intrinsics.IntrinsicArrayConstructorsKt;
035 import org.jetbrains.kotlin.codegen.state.GenerationState;
036 import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper;
037 import org.jetbrains.kotlin.codegen.when.WhenByEnumsMapping;
038 import org.jetbrains.kotlin.descriptors.*;
039 import org.jetbrains.kotlin.fileClasses.FileClasses;
040 import org.jetbrains.kotlin.fileClasses.JvmFileClassesProvider;
041 import org.jetbrains.kotlin.load.java.JvmAbi;
042 import org.jetbrains.kotlin.load.kotlin.JvmVirtualFileFinder;
043 import org.jetbrains.kotlin.name.ClassId;
044 import org.jetbrains.kotlin.name.FqName;
045 import org.jetbrains.kotlin.name.Name;
046 import org.jetbrains.kotlin.psi.KtFile;
047 import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils;
048 import org.jetbrains.kotlin.resolve.jvm.AsmTypes;
049 import org.jetbrains.kotlin.resolve.jvm.JvmClassName;
050 import org.jetbrains.kotlin.types.KotlinType;
051 import org.jetbrains.kotlin.util.OperatorNameConventions;
052 import org.jetbrains.org.objectweb.asm.*;
053 import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter;
054 import org.jetbrains.org.objectweb.asm.tree.*;
055 import org.jetbrains.org.objectweb.asm.util.Textifier;
056 import org.jetbrains.org.objectweb.asm.util.TraceMethodVisitor;
057
058 import java.io.IOException;
059 import java.io.PrintWriter;
060 import java.io.StringWriter;
061 import java.util.List;
062 import java.util.ListIterator;
063
064 import static org.jetbrains.kotlin.resolve.jvm.AsmTypes.ENUM_TYPE;
065 import static org.jetbrains.kotlin.resolve.jvm.AsmTypes.JAVA_CLASS_TYPE;
066
067 public class InlineCodegenUtil {
068 public static final boolean GENERATE_SMAP = true;
069 public static final int API = Opcodes.ASM5;
070
071 private static final String CAPTURED_FIELD_PREFIX = "$";
072 private static final String NON_CAPTURED_FIELD_PREFIX = "$$";
073 public static final String THIS$0 = "this$0";
074 public static final String THIS = "this";
075 private static final String RECEIVER$0 = "receiver$0";
076 private static final String NON_LOCAL_RETURN = "$$$$$NON_LOCAL_RETURN$$$$$";
077 public static final String FIRST_FUN_LABEL = "$$$$$ROOT$$$$$";
078 public static final String NUMBERED_FUNCTION_PREFIX = "kotlin/jvm/functions/Function";
079 private static final String INLINE_MARKER_CLASS_NAME = "kotlin/jvm/internal/InlineMarker";
080 private static final String INLINE_MARKER_BEFORE_METHOD_NAME = "beforeInlineCall";
081 private static final String INLINE_MARKER_AFTER_METHOD_NAME = "afterInlineCall";
082 private static final String INLINE_MARKER_FINALLY_START = "finallyStart";
083 private static final String INLINE_MARKER_FINALLY_END = "finallyEnd";
084 public static final String INLINE_TRANSFORMATION_SUFFIX = "$inlined";
085 public static final String INLINE_FUN_THIS_0_SUFFIX = "$inline_fun";
086 public static final String INLINE_FUN_VAR_SUFFIX = "$iv";
087
088 @Nullable
089 public static SMAPAndMethodNode getMethodNode(
090 byte[] classData,
091 final String methodName,
092 final String methodDescriptor,
093 ClassId classId,
094 final @NotNull GenerationState state
095 ) {
096 ClassReader cr = new ClassReader(classData);
097 final MethodNode[] node = new MethodNode[1];
098 final String[] debugInfo = new String[2];
099 final int[] lines = new int[2];
100 lines[0] = Integer.MAX_VALUE;
101 lines[1] = Integer.MIN_VALUE;
102 //noinspection PointlessBitwiseExpression
103 cr.accept(new ClassVisitor(API) {
104 @Override
105 public void visit(int version, int access, @NotNull String name, String signature, String superName, String[] interfaces) {
106 assertVersionNotGreaterThanGeneratedOne(version, name, state);
107 }
108
109 @Override
110 public void visitSource(String source, String debug) {
111 super.visitSource(source, debug);
112 debugInfo[0] = source;
113 debugInfo[1] = debug;
114 }
115
116 @Override
117 public MethodVisitor visitMethod(
118 int access,
119 @NotNull String name,
120 @NotNull String desc,
121 String signature,
122 String[] exceptions
123 ) {
124 if (methodName.equals(name) && methodDescriptor.equals(desc)) {
125 node[0] = new MethodNode(API, access, name, desc, signature, exceptions) {
126 @Override
127 public void visitLineNumber(int line, @NotNull Label start) {
128 super.visitLineNumber(line, start);
129 lines[0] = Math.min(lines[0], line);
130 lines[1] = Math.max(lines[1], line);
131 }
132 };
133 return node[0];
134 }
135 return null;
136 }
137 }, ClassReader.SKIP_FRAMES | (GENERATE_SMAP ? 0 : ClassReader.SKIP_DEBUG));
138
139 if (node[0] == null) {
140 return null;
141 }
142
143 if (classId.equals(IntrinsicArrayConstructorsKt.getClassId())) {
144 // Don't load source map for intrinsic array constructors
145 debugInfo[0] = null;
146 }
147
148 SMAP smap = SMAPParser.parseOrCreateDefault(debugInfo[1], debugInfo[0], classId.asString(), lines[0], lines[1]);
149 return new SMAPAndMethodNode(node[0], smap);
150 }
151
152 public static void assertVersionNotGreaterThanGeneratedOne(int version, String internalName, @NotNull GenerationState state) {
153 // TODO: report a proper diagnostic
154 if (version > state.getClassFileVersion() && !"true".equals(System.getProperty("kotlin.skip.bytecode.version.check"))) {
155 throw new UnsupportedOperationException(
156 "Cannot inline bytecode of class " + internalName + " which has version " + version + ". " +
157 "This compiler can only inline Java 1.6 bytecode (version " + Opcodes.V1_6 + ")"
158 );
159 }
160 }
161
162 public static void initDefaultSourceMappingIfNeeded(
163 @NotNull CodegenContext context, @NotNull MemberCodegen codegen, @NotNull GenerationState state
164 ) {
165 if (state.isInlineDisabled()) return;
166
167 CodegenContext<?> parentContext = context.getParentContext();
168 while (parentContext != null) {
169 if (parentContext.isInlineMethodContext()) {
170 //just init default one to one mapping
171 codegen.getOrCreateSourceMapper();
172 break;
173 }
174 parentContext = parentContext.getParentContext();
175 }
176 }
177
178 @Nullable
179 public static VirtualFile findVirtualFile(@NotNull GenerationState state, @NotNull ClassId classId) {
180 return JvmVirtualFileFinder.SERVICE.getInstance(state.getProject()).findVirtualFileWithHeader(classId);
181 }
182
183 @Nullable
184 private static VirtualFile findVirtualFileImprecise(@NotNull GenerationState state, @NotNull String internalClassName) {
185 FqName packageFqName = JvmClassName.byInternalName(internalClassName).getPackageFqName();
186 String classNameWithDollars = StringsKt.substringAfterLast(internalClassName, "/", internalClassName);
187 //TODO: we cannot construct proper classId at this point, we need to read InnerClasses info from class file
188 // we construct valid.package.name/RelativeClassNameAsSingleName that should work in compiler, but fails for inner classes in IDE
189 return findVirtualFile(state, new ClassId(packageFqName, Name.identifier(classNameWithDollars)));
190 }
191
192 @NotNull
193 public static String getInlineName(
194 @NotNull CodegenContext codegenContext,
195 @NotNull KotlinTypeMapper typeMapper,
196 @NotNull JvmFileClassesProvider fileClassesManager
197 ) {
198 return getInlineName(codegenContext, codegenContext.getContextDescriptor(), typeMapper, fileClassesManager);
199 }
200
201 @NotNull
202 private static String getInlineName(
203 @NotNull CodegenContext codegenContext,
204 @NotNull DeclarationDescriptor currentDescriptor,
205 @NotNull KotlinTypeMapper typeMapper,
206 @NotNull JvmFileClassesProvider fileClassesProvider
207 ) {
208 if (currentDescriptor instanceof PackageFragmentDescriptor) {
209 PsiFile file = DescriptorToSourceUtils.getContainingFile(codegenContext.getContextDescriptor());
210
211 Type implementationOwnerType;
212 if (file == null) {
213 implementationOwnerType = CodegenContextUtil.getImplementationOwnerClassType(codegenContext);
214 }
215 else {
216 implementationOwnerType = FileClasses.getFileClassType(fileClassesProvider, (KtFile) file);
217 }
218
219 if (implementationOwnerType == null) {
220 DeclarationDescriptor contextDescriptor = codegenContext.getContextDescriptor();
221 //noinspection ConstantConditions
222 throw new RuntimeException(
223 "Couldn't find declaration for " +
224 contextDescriptor.getContainingDeclaration().getName() + "." + contextDescriptor.getName() +
225 "; context: " + codegenContext
226 );
227 }
228
229 return implementationOwnerType.getInternalName();
230 }
231 else if (currentDescriptor instanceof ClassifierDescriptor) {
232 Type type = typeMapper.mapType((ClassifierDescriptor) currentDescriptor);
233 return type.getInternalName();
234 }
235 else if (currentDescriptor instanceof FunctionDescriptor) {
236 ClassDescriptor descriptor =
237 typeMapper.getBindingContext().get(CodegenBinding.CLASS_FOR_CALLABLE, (FunctionDescriptor) currentDescriptor);
238 if (descriptor != null) {
239 return typeMapper.mapType(descriptor).getInternalName();
240 }
241 }
242
243 //TODO: add suffix for special case
244 String suffix = currentDescriptor.getName().isSpecial() ? "" : currentDescriptor.getName().asString();
245
246 //noinspection ConstantConditions
247 return getInlineName(codegenContext, currentDescriptor.getContainingDeclaration(), typeMapper, fileClassesProvider) + "$" + suffix;
248 }
249
250 public static boolean isInvokeOnLambda(@NotNull String owner, @NotNull String name) {
251 return OperatorNameConventions.INVOKE.asString().equals(name) &&
252 owner.startsWith(NUMBERED_FUNCTION_PREFIX) &&
253 isInteger(owner.substring(NUMBERED_FUNCTION_PREFIX.length()));
254 }
255
256 public static boolean isAnonymousConstructorCall(@NotNull String internalName, @NotNull String methodName) {
257 return "<init>".equals(methodName) && isAnonymousClass(internalName);
258 }
259
260 public static boolean isWhenMappingAccess(@NotNull String internalName, @NotNull String fieldName) {
261 return fieldName.startsWith(WhenByEnumsMapping.MAPPING_ARRAY_FIELD_PREFIX) &&
262 internalName.endsWith(WhenByEnumsMapping.MAPPINGS_CLASS_NAME_POSTFIX);
263 }
264
265 public static boolean isAnonymousSingletonLoad(@NotNull String internalName, @NotNull String fieldName) {
266 return JvmAbi.INSTANCE_FIELD.equals(fieldName) && isAnonymousClass(internalName);
267 }
268
269 public static boolean isAnonymousClass(@NotNull String internalName) {
270 String shortName = getLastNamePart(internalName);
271 int index = shortName.lastIndexOf("$");
272
273 if (index < 0) {
274 return false;
275 }
276
277 String suffix = shortName.substring(index + 1);
278 return isInteger(suffix);
279 }
280
281 @NotNull
282 private static String getLastNamePart(@NotNull String internalName) {
283 int index = internalName.lastIndexOf("/");
284 return index < 0 ? internalName : internalName.substring(index + 1);
285 }
286
287 @NotNull
288 public static MethodVisitor wrapWithMaxLocalCalc(@NotNull MethodNode methodNode) {
289 return new MaxStackFrameSizeAndLocalsCalculator(API, methodNode.access, methodNode.desc, methodNode);
290 }
291
292 private static boolean isInteger(@NotNull String string) {
293 if (string.isEmpty()) {
294 return false;
295 }
296
297 for (int i = 0; i < string.length(); i++) {
298 if (!Character.isDigit(string.charAt(i))) {
299 return false;
300 }
301 }
302
303 return true;
304 }
305
306 public static boolean isCapturedFieldName(@NotNull String fieldName) {
307 // TODO: improve this heuristic
308 return fieldName.startsWith(CAPTURED_FIELD_PREFIX) &&
309 !fieldName.startsWith(NON_CAPTURED_FIELD_PREFIX) ||
310 THIS$0.equals(fieldName) ||
311 RECEIVER$0.equals(fieldName);
312 }
313
314 public static boolean isReturnOpcode(int opcode) {
315 return opcode >= Opcodes.IRETURN && opcode <= Opcodes.RETURN;
316 }
317
318 //marked return could be either non-local or local in case of labeled lambda self-returns
319 public static boolean isMarkedReturn(@NotNull AbstractInsnNode returnIns) {
320 return getMarkedReturnLabelOrNull(returnIns) != null;
321 }
322
323 @Nullable
324 public static String getMarkedReturnLabelOrNull(@NotNull AbstractInsnNode returnInsn) {
325 if (!isReturnOpcode(returnInsn.getOpcode())) {
326 return null;
327 }
328 AbstractInsnNode previous = returnInsn.getPrevious();
329 if (previous instanceof MethodInsnNode) {
330 MethodInsnNode marker = (MethodInsnNode) previous;
331 if (NON_LOCAL_RETURN.equals(marker.owner)) {
332 return marker.name;
333 }
334 }
335 return null;
336 }
337
338 public static void generateGlobalReturnFlag(@NotNull InstructionAdapter iv, @NotNull String labelName) {
339 iv.invokestatic(NON_LOCAL_RETURN, labelName, "()V", false);
340 }
341
342 @NotNull
343 public static Type getReturnType(int opcode) {
344 switch (opcode) {
345 case Opcodes.RETURN:
346 return Type.VOID_TYPE;
347 case Opcodes.IRETURN:
348 return Type.INT_TYPE;
349 case Opcodes.DRETURN:
350 return Type.DOUBLE_TYPE;
351 case Opcodes.FRETURN:
352 return Type.FLOAT_TYPE;
353 case Opcodes.LRETURN:
354 return Type.LONG_TYPE;
355 default:
356 return AsmTypes.OBJECT_TYPE;
357 }
358 }
359
360 public static void insertNodeBefore(@NotNull MethodNode from, @NotNull MethodNode to, @NotNull AbstractInsnNode beforeNode) {
361 ListIterator<AbstractInsnNode> iterator = from.instructions.iterator();
362 while (iterator.hasNext()) {
363 AbstractInsnNode next = iterator.next();
364 to.instructions.insertBefore(beforeNode, next);
365 }
366 }
367
368 @NotNull
369 public static MethodNode createEmptyMethodNode() {
370 return new MethodNode(API, 0, "fake", "()V", null, null);
371 }
372
373 @NotNull
374 public static LabelNode firstLabelInChain(@NotNull LabelNode node) {
375 LabelNode curNode = node;
376 while (curNode.getPrevious() instanceof LabelNode) {
377 curNode = (LabelNode) curNode.getPrevious();
378 }
379 return curNode;
380 }
381
382 @NotNull
383 public static String getNodeText(@Nullable MethodNode node) {
384 Textifier textifier = new Textifier();
385 if (node == null) {
386 return "Not generated";
387 }
388 node.accept(new TraceMethodVisitor(textifier));
389 StringWriter sw = new StringWriter();
390 textifier.print(new PrintWriter(sw));
391 sw.flush();
392 return node.name + " " + node.desc + ":\n" + sw.getBuffer().toString();
393 }
394
395 @NotNull
396 public static String getInsnText(@Nullable AbstractInsnNode node) {
397 if (node == null) return "<null>";
398 Textifier textifier = new Textifier();
399 node.accept(new TraceMethodVisitor(textifier));
400 StringWriter sw = new StringWriter();
401 textifier.print(new PrintWriter(sw));
402 sw.flush();
403 return sw.toString().trim();
404 }
405
406 @NotNull
407 /* package */ static ClassReader buildClassReaderByInternalName(@NotNull GenerationState state, @NotNull String internalName) {
408 //try to find just compiled classes then in dependencies
409 try {
410 OutputFile outputFile = state.getFactory().get(internalName + ".class");
411 if (outputFile != null) {
412 return new ClassReader(outputFile.asByteArray());
413 }
414 VirtualFile file = findVirtualFileImprecise(state, internalName);
415 if (file != null) {
416 return new ClassReader(file.contentsToByteArray());
417 }
418 throw new RuntimeException("Couldn't find virtual file for " + internalName);
419 }
420 catch (IOException e) {
421 throw new RuntimeException(e);
422 }
423 }
424
425 public static void generateFinallyMarker(@NotNull InstructionAdapter v, int depth, boolean start) {
426 v.iconst(depth);
427 v.invokestatic(INLINE_MARKER_CLASS_NAME, start ? INLINE_MARKER_FINALLY_START : INLINE_MARKER_FINALLY_END, "(I)V", false);
428 }
429
430 public static boolean isFinallyEnd(@NotNull AbstractInsnNode node) {
431 return isFinallyMarker(node, INLINE_MARKER_FINALLY_END);
432 }
433
434 public static boolean isFinallyStart(@NotNull AbstractInsnNode node) {
435 return isFinallyMarker(node, INLINE_MARKER_FINALLY_START);
436 }
437
438 public static boolean isFinallyMarker(@Nullable AbstractInsnNode node) {
439 return node != null && (isFinallyStart(node) || isFinallyEnd(node));
440 }
441
442 private static boolean isFinallyMarker(@NotNull AbstractInsnNode node, String name) {
443 if (!(node instanceof MethodInsnNode)) return false;
444 MethodInsnNode method = (MethodInsnNode) node;
445 return INLINE_MARKER_CLASS_NAME.equals(method.owner) && name.equals(method.name);
446 }
447
448 public static boolean isFinallyMarkerRequired(@NotNull MethodContext context) {
449 return context.isInlineMethodContext() || context instanceof InlineLambdaContext;
450 }
451
452 public static int getConstant(@NotNull AbstractInsnNode ins) {
453 int opcode = ins.getOpcode();
454 Integer value;
455 if (opcode >= Opcodes.ICONST_0 && opcode <= Opcodes.ICONST_5) {
456 return opcode - Opcodes.ICONST_0;
457 }
458 else if (opcode == Opcodes.BIPUSH || opcode == Opcodes.SIPUSH) {
459 return ((IntInsnNode) ins).operand;
460 }
461 else {
462 LdcInsnNode index = (LdcInsnNode) ins;
463 return (Integer) index.cst;
464 }
465 }
466
467 public static void addInlineMarker(@NotNull InstructionAdapter v, boolean isStartNotEnd) {
468 v.visitMethodInsn(
469 Opcodes.INVOKESTATIC, INLINE_MARKER_CLASS_NAME,
470 isStartNotEnd ? INLINE_MARKER_BEFORE_METHOD_NAME : INLINE_MARKER_AFTER_METHOD_NAME,
471 "()V", false
472 );
473 }
474
475 public static boolean isInlineMarker(@NotNull AbstractInsnNode insn) {
476 return isInlineMarker(insn, null);
477 }
478
479 private static boolean isInlineMarker(@NotNull AbstractInsnNode insn, @Nullable String name) {
480 if (!(insn instanceof MethodInsnNode)) {
481 return false;
482 }
483
484 MethodInsnNode methodInsnNode = (MethodInsnNode) insn;
485 return insn.getOpcode() == Opcodes.INVOKESTATIC &&
486 methodInsnNode.owner.equals(INLINE_MARKER_CLASS_NAME) &&
487 (name != null ? methodInsnNode.name.equals(name)
488 : methodInsnNode.name.equals(INLINE_MARKER_BEFORE_METHOD_NAME) ||
489 methodInsnNode.name.equals(INLINE_MARKER_AFTER_METHOD_NAME));
490 }
491
492 public static boolean isBeforeInlineMarker(@NotNull AbstractInsnNode insn) {
493 return isInlineMarker(insn, INLINE_MARKER_BEFORE_METHOD_NAME);
494 }
495
496 public static boolean isAfterInlineMarker(@NotNull AbstractInsnNode insn) {
497 return isInlineMarker(insn, INLINE_MARKER_AFTER_METHOD_NAME);
498 }
499
500 public static int getLoadStoreArgSize(int opcode) {
501 return opcode == Opcodes.DSTORE || opcode == Opcodes.LSTORE || opcode == Opcodes.DLOAD || opcode == Opcodes.LLOAD ? 2 : 1;
502 }
503
504 public static boolean isStoreInstruction(int opcode) {
505 return opcode >= Opcodes.ISTORE && opcode <= Opcodes.ASTORE;
506 }
507
508 public static int calcMarkerShift(@NotNull Parameters parameters, @NotNull MethodNode node) {
509 int markerShiftTemp = getIndexAfterLastMarker(node);
510 return markerShiftTemp - parameters.getRealParametersSizeOnStack() + parameters.getArgsSizeOnStack();
511 }
512
513 private static int getIndexAfterLastMarker(@NotNull MethodNode node) {
514 int result = -1;
515 for (LocalVariableNode variable : node.localVariables) {
516 if (isFakeLocalVariableForInline(variable.name)) {
517 result = Math.max(result, variable.index + 1);
518 }
519 }
520 return result;
521 }
522
523 public static boolean isFakeLocalVariableForInline(@NotNull String name) {
524 return name.startsWith(JvmAbi.LOCAL_VARIABLE_NAME_PREFIX_INLINE_FUNCTION) ||
525 name.startsWith(JvmAbi.LOCAL_VARIABLE_NAME_PREFIX_INLINE_ARGUMENT);
526 }
527
528 public static boolean isThis0(@NotNull String name) {
529 return THIS$0.equals(name);
530 }
531
532 public static boolean isSpecialEnumMethod(@NotNull FunctionDescriptor functionDescriptor) {
533 DeclarationDescriptor containingDeclaration = functionDescriptor.getContainingDeclaration();
534 if (!(containingDeclaration instanceof PackageFragmentDescriptor)) {
535 return false;
536 }
537 if (!((PackageFragmentDescriptor) containingDeclaration).getFqName().equals(KotlinBuiltIns.BUILT_INS_PACKAGE_FQ_NAME)) {
538 return false;
539 }
540 if (functionDescriptor.getTypeParameters().size() != 1) {
541 return false;
542 }
543 String name = functionDescriptor.getName().asString();
544 List<ValueParameterDescriptor> parameters = functionDescriptor.getValueParameters();
545 return "enumValues".equals(name) && parameters.size() == 0 ||
546 "enumValueOf".equals(name) && parameters.size() == 1 && KotlinBuiltIns.isString(parameters.get(0).getType());
547 }
548
549 public static MethodNode createSpecialEnumMethodBody(
550 @NotNull ExpressionCodegen codegen,
551 @NotNull String name,
552 @NotNull KotlinType type,
553 @NotNull KotlinTypeMapper typeMapper
554 ) {
555 boolean isValueOf = "enumValueOf".equals(name);
556 Type invokeType = typeMapper.mapType(type);
557 String desc = getSpecialEnumFunDescriptor(invokeType, isValueOf);
558 MethodNode node = new MethodNode(API, Opcodes.ACC_STATIC, "fake", desc, null, null);
559 codegen.putReifiedOperationMarkerIfTypeIsReifiedParameter(type, ReifiedTypeInliner.OperationKind.ENUM_REIFIED, new InstructionAdapter(node));
560 if (isValueOf) {
561 node.visitInsn(Opcodes.ACONST_NULL);
562 node.visitVarInsn(Opcodes.ALOAD, 0);
563
564 node.visitMethodInsn(Opcodes.INVOKESTATIC, ENUM_TYPE.getInternalName(), "valueOf",
565 Type.getMethodDescriptor(ENUM_TYPE, JAVA_CLASS_TYPE, AsmTypes.JAVA_STRING_TYPE), false);
566 }
567 else {
568 node.visitInsn(Opcodes.ICONST_0);
569 node.visitTypeInsn(Opcodes.ANEWARRAY, ENUM_TYPE.getInternalName());
570 }
571 node.visitInsn(Opcodes.ARETURN);
572 node.visitMaxs(isValueOf ? 3 : 2, isValueOf ? 1 : 0);
573 return node;
574 }
575
576 @NotNull
577 public static String getSpecialEnumFunDescriptor(@NotNull Type type, boolean isValueOf) {
578 return isValueOf ? Type.getMethodDescriptor(type, AsmTypes.JAVA_STRING_TYPE) : Type.getMethodDescriptor(AsmUtil.getArrayType(type));
579 }
580 }
581