1 /*
   2  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   3  *
   4  * This code is free software; you can redistribute it and/or modify it
   5  * under the terms of the GNU General Public License version 2 only, as
   6  * published by the Free Software Foundation.  Oracle designates this
   7  * particular file as subject to the "Classpath" exception as provided
   8  * by Oracle in the LICENSE file that accompanied this code.
   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  */
  24 
  25 /*
  26  * This file is available under and governed by the GNU General Public
  27  * License version 2 only, as published by the Free Software Foundation.
  28  * However, the following notice accompanied the original version of this
  29  * file:
  30  *
  31  * ASM: a very small and fast Java bytecode manipulation framework
  32  * Copyright (c) 2000-2011 INRIA, France Telecom
  33  * All rights reserved.
  34  *
  35  * Redistribution and use in source and binary forms, with or without
  36  * modification, are permitted provided that the following conditions
  37  * are met:
  38  * 1. Redistributions of source code must retain the above copyright
  39  *    notice, this list of conditions and the following disclaimer.
  40  * 2. Redistributions in binary form must reproduce the above copyright
  41  *    notice, this list of conditions and the following disclaimer in the
  42  *    documentation and/or other materials provided with the distribution.
  43  * 3. Neither the name of the copyright holders nor the names of its
  44  *    contributors may be used to endorse or promote products derived from
  45  *    this software without specific prior written permission.
  46  *
  47  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  48  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  49  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  50  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  51  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  52  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  53  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  54  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  55  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  56  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
  57  * THE POSSIBILITY OF SUCH DAMAGE.
  58  */
  59 package jdk.internal.org.objectweb.asm;
  60 
  61 /**
  62  * A {@link MethodVisitor} that generates a corresponding 'method_info' structure, as defined in the
  63  * Java Virtual Machine Specification (JVMS).
  64  *
  65  * @see <a href="https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.6">JVMS
  66  *     4.6</a>
  67  * @author Eric Bruneton
  68  * @author Eugene Kuleshov
  69  */
  70 final class MethodWriter extends MethodVisitor {
  71 
  72     /** Indicates that nothing must be computed. */
  73     static final int COMPUTE_NOTHING = 0;
  74 
  75     /**
  76       * Indicates that the maximum stack size and the maximum number of local variables must be
  77       * computed, from scratch.
  78       */
  79     static final int COMPUTE_MAX_STACK_AND_LOCAL = 1;
  80 
  81     /**
  82       * Indicates that the maximum stack size and the maximum number of local variables must be
  83       * computed, from the existing stack map frames. This can be done more efficiently than with the
  84       * control flow graph algorithm used for {@link #COMPUTE_MAX_STACK_AND_LOCAL}, by using a linear
  85       * scan of the bytecode instructions.
  86       */
  87     static final int COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES = 2;
  88 
  89     /**
  90       * Indicates that the stack map frames of type F_INSERT must be computed. The other frames are not
  91       * computed. They should all be of type F_NEW and should be sufficient to compute the content of
  92       * the F_INSERT frames, together with the bytecode instructions between a F_NEW and a F_INSERT
  93       * frame - and without any knowledge of the type hierarchy (by definition of F_INSERT).
  94       */
  95     static final int COMPUTE_INSERTED_FRAMES = 3;
  96 
  97     /**
  98       * Indicates that all the stack map frames must be computed. In this case the maximum stack size
  99       * and the maximum number of local variables is also computed.
 100       */
 101     static final int COMPUTE_ALL_FRAMES = 4;
 102 
 103     /** Indicates that {@link #STACK_SIZE_DELTA} is not applicable (not constant or never used). */
 104     private static final int NA = 0;
 105 
 106     /**
 107       * The stack size variation corresponding to each JVM opcode. The stack size variation for opcode
 108       * 'o' is given by the array element at index 'o'.
 109       *
 110       * @see <a href="https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-6.html">JVMS 6</a>
 111       */
 112     private static final int[] STACK_SIZE_DELTA = {
 113         0, // nop = 0 (0x0)
 114         1, // aconst_null = 1 (0x1)
 115         1, // iconst_m1 = 2 (0x2)
 116         1, // iconst_0 = 3 (0x3)
 117         1, // iconst_1 = 4 (0x4)
 118         1, // iconst_2 = 5 (0x5)
 119         1, // iconst_3 = 6 (0x6)
 120         1, // iconst_4 = 7 (0x7)
 121         1, // iconst_5 = 8 (0x8)
 122         2, // lconst_0 = 9 (0x9)
 123         2, // lconst_1 = 10 (0xa)
 124         1, // fconst_0 = 11 (0xb)
 125         1, // fconst_1 = 12 (0xc)
 126         1, // fconst_2 = 13 (0xd)
 127         2, // dconst_0 = 14 (0xe)
 128         2, // dconst_1 = 15 (0xf)
 129         1, // bipush = 16 (0x10)
 130         1, // sipush = 17 (0x11)
 131         1, // ldc = 18 (0x12)
 132         NA, // ldc_w = 19 (0x13)
 133         NA, // ldc2_w = 20 (0x14)
 134         1, // iload = 21 (0x15)
 135         2, // lload = 22 (0x16)
 136         1, // fload = 23 (0x17)
 137         2, // dload = 24 (0x18)
 138         1, // aload = 25 (0x19)
 139         NA, // iload_0 = 26 (0x1a)
 140         NA, // iload_1 = 27 (0x1b)
 141         NA, // iload_2 = 28 (0x1c)
 142         NA, // iload_3 = 29 (0x1d)
 143         NA, // lload_0 = 30 (0x1e)
 144         NA, // lload_1 = 31 (0x1f)
 145         NA, // lload_2 = 32 (0x20)
 146         NA, // lload_3 = 33 (0x21)
 147         NA, // fload_0 = 34 (0x22)
 148         NA, // fload_1 = 35 (0x23)
 149         NA, // fload_2 = 36 (0x24)
 150         NA, // fload_3 = 37 (0x25)
 151         NA, // dload_0 = 38 (0x26)
 152         NA, // dload_1 = 39 (0x27)
 153         NA, // dload_2 = 40 (0x28)
 154         NA, // dload_3 = 41 (0x29)
 155         NA, // aload_0 = 42 (0x2a)
 156         NA, // aload_1 = 43 (0x2b)
 157         NA, // aload_2 = 44 (0x2c)
 158         NA, // aload_3 = 45 (0x2d)
 159         -1, // iaload = 46 (0x2e)
 160         0, // laload = 47 (0x2f)
 161         -1, // faload = 48 (0x30)
 162         0, // daload = 49 (0x31)
 163         -1, // aaload = 50 (0x32)
 164         -1, // baload = 51 (0x33)
 165         -1, // caload = 52 (0x34)
 166         -1, // saload = 53 (0x35)
 167         -1, // istore = 54 (0x36)
 168         -2, // lstore = 55 (0x37)
 169         -1, // fstore = 56 (0x38)
 170         -2, // dstore = 57 (0x39)
 171         -1, // astore = 58 (0x3a)
 172         NA, // istore_0 = 59 (0x3b)
 173         NA, // istore_1 = 60 (0x3c)
 174         NA, // istore_2 = 61 (0x3d)
 175         NA, // istore_3 = 62 (0x3e)
 176         NA, // lstore_0 = 63 (0x3f)
 177         NA, // lstore_1 = 64 (0x40)
 178         NA, // lstore_2 = 65 (0x41)
 179         NA, // lstore_3 = 66 (0x42)
 180         NA, // fstore_0 = 67 (0x43)
 181         NA, // fstore_1 = 68 (0x44)
 182         NA, // fstore_2 = 69 (0x45)
 183         NA, // fstore_3 = 70 (0x46)
 184         NA, // dstore_0 = 71 (0x47)
 185         NA, // dstore_1 = 72 (0x48)
 186         NA, // dstore_2 = 73 (0x49)
 187         NA, // dstore_3 = 74 (0x4a)
 188         NA, // astore_0 = 75 (0x4b)
 189         NA, // astore_1 = 76 (0x4c)
 190         NA, // astore_2 = 77 (0x4d)
 191         NA, // astore_3 = 78 (0x4e)
 192         -3, // iastore = 79 (0x4f)
 193         -4, // lastore = 80 (0x50)
 194         -3, // fastore = 81 (0x51)
 195         -4, // dastore = 82 (0x52)
 196         -3, // aastore = 83 (0x53)
 197         -3, // bastore = 84 (0x54)
 198         -3, // castore = 85 (0x55)
 199         -3, // sastore = 86 (0x56)
 200         -1, // pop = 87 (0x57)
 201         -2, // pop2 = 88 (0x58)
 202         1, // dup = 89 (0x59)
 203         1, // dup_x1 = 90 (0x5a)
 204         1, // dup_x2 = 91 (0x5b)
 205         2, // dup2 = 92 (0x5c)
 206         2, // dup2_x1 = 93 (0x5d)
 207         2, // dup2_x2 = 94 (0x5e)
 208         0, // swap = 95 (0x5f)
 209         -1, // iadd = 96 (0x60)
 210         -2, // ladd = 97 (0x61)
 211         -1, // fadd = 98 (0x62)
 212         -2, // dadd = 99 (0x63)
 213         -1, // isub = 100 (0x64)
 214         -2, // lsub = 101 (0x65)
 215         -1, // fsub = 102 (0x66)
 216         -2, // dsub = 103 (0x67)
 217         -1, // imul = 104 (0x68)
 218         -2, // lmul = 105 (0x69)
 219         -1, // fmul = 106 (0x6a)
 220         -2, // dmul = 107 (0x6b)
 221         -1, // idiv = 108 (0x6c)
 222         -2, // ldiv = 109 (0x6d)
 223         -1, // fdiv = 110 (0x6e)
 224         -2, // ddiv = 111 (0x6f)
 225         -1, // irem = 112 (0x70)
 226         -2, // lrem = 113 (0x71)
 227         -1, // frem = 114 (0x72)
 228         -2, // drem = 115 (0x73)
 229         0, // ineg = 116 (0x74)
 230         0, // lneg = 117 (0x75)
 231         0, // fneg = 118 (0x76)
 232         0, // dneg = 119 (0x77)
 233         -1, // ishl = 120 (0x78)
 234         -1, // lshl = 121 (0x79)
 235         -1, // ishr = 122 (0x7a)
 236         -1, // lshr = 123 (0x7b)
 237         -1, // iushr = 124 (0x7c)
 238         -1, // lushr = 125 (0x7d)
 239         -1, // iand = 126 (0x7e)
 240         -2, // land = 127 (0x7f)
 241         -1, // ior = 128 (0x80)
 242         -2, // lor = 129 (0x81)
 243         -1, // ixor = 130 (0x82)
 244         -2, // lxor = 131 (0x83)
 245         0, // iinc = 132 (0x84)
 246         1, // i2l = 133 (0x85)
 247         0, // i2f = 134 (0x86)
 248         1, // i2d = 135 (0x87)
 249         -1, // l2i = 136 (0x88)
 250         -1, // l2f = 137 (0x89)
 251         0, // l2d = 138 (0x8a)
 252         0, // f2i = 139 (0x8b)
 253         1, // f2l = 140 (0x8c)
 254         1, // f2d = 141 (0x8d)
 255         -1, // d2i = 142 (0x8e)
 256         0, // d2l = 143 (0x8f)
 257         -1, // d2f = 144 (0x90)
 258         0, // i2b = 145 (0x91)
 259         0, // i2c = 146 (0x92)
 260         0, // i2s = 147 (0x93)
 261         -3, // lcmp = 148 (0x94)
 262         -1, // fcmpl = 149 (0x95)
 263         -1, // fcmpg = 150 (0x96)
 264         -3, // dcmpl = 151 (0x97)
 265         -3, // dcmpg = 152 (0x98)
 266         -1, // ifeq = 153 (0x99)
 267         -1, // ifne = 154 (0x9a)
 268         -1, // iflt = 155 (0x9b)
 269         -1, // ifge = 156 (0x9c)
 270         -1, // ifgt = 157 (0x9d)
 271         -1, // ifle = 158 (0x9e)
 272         -2, // if_icmpeq = 159 (0x9f)
 273         -2, // if_icmpne = 160 (0xa0)
 274         -2, // if_icmplt = 161 (0xa1)
 275         -2, // if_icmpge = 162 (0xa2)
 276         -2, // if_icmpgt = 163 (0xa3)
 277         -2, // if_icmple = 164 (0xa4)
 278         -2, // if_acmpeq = 165 (0xa5)
 279         -2, // if_acmpne = 166 (0xa6)
 280         0, // goto = 167 (0xa7)
 281         1, // jsr = 168 (0xa8)
 282         0, // ret = 169 (0xa9)
 283         -1, // tableswitch = 170 (0xaa)
 284         -1, // lookupswitch = 171 (0xab)
 285         -1, // ireturn = 172 (0xac)
 286         -2, // lreturn = 173 (0xad)
 287         -1, // freturn = 174 (0xae)
 288         -2, // dreturn = 175 (0xaf)
 289         -1, // areturn = 176 (0xb0)
 290         0, // return = 177 (0xb1)
 291         NA, // getstatic = 178 (0xb2)
 292         NA, // putstatic = 179 (0xb3)
 293         NA, // getfield = 180 (0xb4)
 294         NA, // putfield = 181 (0xb5)
 295         NA, // invokevirtual = 182 (0xb6)
 296         NA, // invokespecial = 183 (0xb7)
 297         NA, // invokestatic = 184 (0xb8)
 298         NA, // invokeinterface = 185 (0xb9)
 299         NA, // invokedynamic = 186 (0xba)
 300         1, // new = 187 (0xbb)
 301         0, // newarray = 188 (0xbc)
 302         0, // anewarray = 189 (0xbd)
 303         0, // arraylength = 190 (0xbe)
 304         NA, // athrow = 191 (0xbf)
 305         0, // checkcast = 192 (0xc0)
 306         0, // instanceof = 193 (0xc1)
 307         -1, // monitorenter = 194 (0xc2)
 308         -1, // monitorexit = 195 (0xc3)
 309         NA, // wide = 196 (0xc4)
 310         NA, // multianewarray = 197 (0xc5)
 311         -1, // ifnull = 198 (0xc6)
 312         -1, // ifnonnull = 199 (0xc7)
 313         NA, // goto_w = 200 (0xc8)
 314         NA, // jsr_w = 201 (0xc9)
 315         NA, // breakpoint = 202 (0xca)
 316         NA, // default = 203 (0xcb)
 317         NA, // withfield = 204 (0xcc)
 318     };
 319 
 320     /** Where the constants used in this MethodWriter must be stored. */
 321     private final SymbolTable symbolTable;
 322 
 323     // Note: fields are ordered as in the method_info structure, and those related to attributes are
 324     // ordered as in Section 4.7 of the JVMS.
 325 
 326     /**
 327       * The access_flags field of the method_info JVMS structure. This field can contain ASM specific
 328       * access flags, such as {@link Opcodes#ACC_DEPRECATED}, which are removed when generating the
 329       * ClassFile structure.
 330       */
 331     private final int accessFlags;
 332 
 333     /** The name_index field of the method_info JVMS structure. */
 334     private final int nameIndex;
 335 
 336     /** The name of this method. */
 337     private final String name;
 338 
 339     /** The descriptor_index field of the method_info JVMS structure. */
 340     private final int descriptorIndex;
 341 
 342     /** The descriptor of this method. */
 343     private final String descriptor;
 344 
 345     // Code attribute fields and sub attributes:
 346 
 347     /** The max_stack field of the Code attribute. */
 348     private int maxStack;
 349 
 350     /** The max_locals field of the Code attribute. */
 351     private int maxLocals;
 352 
 353     /** The 'code' field of the Code attribute. */
 354     private final ByteVector code = new ByteVector();
 355 
 356     /**
 357       * The first element in the exception handler list (used to generate the exception_table of the
 358       * Code attribute). The next ones can be accessed with the {@link Handler#nextHandler} field. May
 359       * be {@literal null}.
 360       */
 361     private Handler firstHandler;
 362 
 363     /**
 364       * The last element in the exception handler list (used to generate the exception_table of the
 365       * Code attribute). The next ones can be accessed with the {@link Handler#nextHandler} field. May
 366       * be {@literal null}.
 367       */
 368     private Handler lastHandler;
 369 
 370     /** The line_number_table_length field of the LineNumberTable code attribute. */
 371     private int lineNumberTableLength;
 372 
 373     /** The line_number_table array of the LineNumberTable code attribute, or {@literal null}. */
 374     private ByteVector lineNumberTable;
 375 
 376     /** The local_variable_table_length field of the LocalVariableTable code attribute. */
 377     private int localVariableTableLength;
 378 
 379     /**
 380       * The local_variable_table array of the LocalVariableTable code attribute, or {@literal null}.
 381       */
 382     private ByteVector localVariableTable;
 383 
 384     /** The local_variable_type_table_length field of the LocalVariableTypeTable code attribute. */
 385     private int localVariableTypeTableLength;
 386 
 387     /**
 388       * The local_variable_type_table array of the LocalVariableTypeTable code attribute, or {@literal
 389       * null}.
 390       */
 391     private ByteVector localVariableTypeTable;
 392 
 393     /** The number_of_entries field of the StackMapTable code attribute. */
 394     private int stackMapTableNumberOfEntries;
 395 
 396     /** The 'entries' array of the StackMapTable code attribute. */
 397     private ByteVector stackMapTableEntries;
 398 
 399     /**
 400       * The last runtime visible type annotation of the Code attribute. The previous ones can be
 401       * accessed with the {@link AnnotationWriter#previousAnnotation} field. May be {@literal null}.
 402       */
 403     private AnnotationWriter lastCodeRuntimeVisibleTypeAnnotation;
 404 
 405     /**
 406       * The last runtime invisible type annotation of the Code attribute. The previous ones can be
 407       * accessed with the {@link AnnotationWriter#previousAnnotation} field. May be {@literal null}.
 408       */
 409     private AnnotationWriter lastCodeRuntimeInvisibleTypeAnnotation;
 410 
 411     /**
 412       * The first non standard attribute of the Code attribute. The next ones can be accessed with the
 413       * {@link Attribute#nextAttribute} field. May be {@literal null}.
 414       *
 415       * <p><b>WARNING</b>: this list stores the attributes in the <i>reverse</i> order of their visit.
 416       * firstAttribute is actually the last attribute visited in {@link #visitAttribute}. The {@link
 417       * #putMethodInfo} method writes the attributes in the order defined by this list, i.e. in the
 418       * reverse order specified by the user.
 419       */
 420     private Attribute firstCodeAttribute;
 421 
 422     // Other method_info attributes:
 423 
 424     /** The number_of_exceptions field of the Exceptions attribute. */
 425     private final int numberOfExceptions;
 426 
 427     /** The exception_index_table array of the Exceptions attribute, or {@literal null}. */
 428     private final int[] exceptionIndexTable;
 429 
 430     /** The signature_index field of the Signature attribute. */
 431     private final int signatureIndex;
 432 
 433     /**
 434       * The last runtime visible annotation of this method. The previous ones can be accessed with the
 435       * {@link AnnotationWriter#previousAnnotation} field. May be {@literal null}.
 436       */
 437     private AnnotationWriter lastRuntimeVisibleAnnotation;
 438 
 439     /**
 440       * The last runtime invisible annotation of this method. The previous ones can be accessed with
 441       * the {@link AnnotationWriter#previousAnnotation} field. May be {@literal null}.
 442       */
 443     private AnnotationWriter lastRuntimeInvisibleAnnotation;
 444 
 445     /** The number of method parameters that can have runtime visible annotations, or 0. */
 446     private int visibleAnnotableParameterCount;
 447 
 448     /**
 449       * The runtime visible parameter annotations of this method. Each array element contains the last
 450       * annotation of a parameter (which can be {@literal null} - the previous ones can be accessed
 451       * with the {@link AnnotationWriter#previousAnnotation} field). May be {@literal null}.
 452       */
 453     private AnnotationWriter[] lastRuntimeVisibleParameterAnnotations;
 454 
 455     /** The number of method parameters that can have runtime visible annotations, or 0. */
 456     private int invisibleAnnotableParameterCount;
 457 
 458     /**
 459       * The runtime invisible parameter annotations of this method. Each array element contains the
 460       * last annotation of a parameter (which can be {@literal null} - the previous ones can be
 461       * accessed with the {@link AnnotationWriter#previousAnnotation} field). May be {@literal null}.
 462       */
 463     private AnnotationWriter[] lastRuntimeInvisibleParameterAnnotations;
 464 
 465     /**
 466       * The last runtime visible type annotation of this method. The previous ones can be accessed with
 467       * the {@link AnnotationWriter#previousAnnotation} field. May be {@literal null}.
 468       */
 469     private AnnotationWriter lastRuntimeVisibleTypeAnnotation;
 470 
 471     /**
 472       * The last runtime invisible type annotation of this method. The previous ones can be accessed
 473       * with the {@link AnnotationWriter#previousAnnotation} field. May be {@literal null}.
 474       */
 475     private AnnotationWriter lastRuntimeInvisibleTypeAnnotation;
 476 
 477     /** The default_value field of the AnnotationDefault attribute, or {@literal null}. */
 478     private ByteVector defaultValue;
 479 
 480     /** The parameters_count field of the MethodParameters attribute. */
 481     private int parametersCount;
 482 
 483     /** The 'parameters' array of the MethodParameters attribute, or {@literal null}. */
 484     private ByteVector parameters;
 485 
 486     /**
 487       * The first non standard attribute of this method. The next ones can be accessed with the {@link
 488       * Attribute#nextAttribute} field. May be {@literal null}.
 489       *
 490       * <p><b>WARNING</b>: this list stores the attributes in the <i>reverse</i> order of their visit.
 491       * firstAttribute is actually the last attribute visited in {@link #visitAttribute}. The {@link
 492       * #putMethodInfo} method writes the attributes in the order defined by this list, i.e. in the
 493       * reverse order specified by the user.
 494       */
 495     private Attribute firstAttribute;
 496 
 497     // -----------------------------------------------------------------------------------------------
 498     // Fields used to compute the maximum stack size and number of locals, and the stack map frames
 499     // -----------------------------------------------------------------------------------------------
 500 
 501     /**
 502       * Indicates what must be computed. Must be one of {@link #COMPUTE_ALL_FRAMES}, {@link
 503       * #COMPUTE_INSERTED_FRAMES}, {@link #COMPUTE_MAX_STACK_AND_LOCAL} or {@link #COMPUTE_NOTHING}.
 504       */
 505     private final int compute;
 506 
 507     /**
 508       * The first basic block of the method. The next ones (in bytecode offset order) can be accessed
 509       * with the {@link Label#nextBasicBlock} field.
 510       */
 511     private Label firstBasicBlock;
 512 
 513     /**
 514       * The last basic block of the method (in bytecode offset order). This field is updated each time
 515       * a basic block is encountered, and is used to append it at the end of the basic block list.
 516       */
 517     private Label lastBasicBlock;
 518 
 519     /**
 520       * The current basic block, i.e. the basic block of the last visited instruction. When {@link
 521       * #compute} is equal to {@link #COMPUTE_MAX_STACK_AND_LOCAL} or {@link #COMPUTE_ALL_FRAMES}, this
 522       * field is {@literal null} for unreachable code. When {@link #compute} is equal to {@link
 523       * #COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES} or {@link #COMPUTE_INSERTED_FRAMES}, this field stays
 524       * unchanged throughout the whole method (i.e. the whole code is seen as a single basic block;
 525       * indeed, the existing frames are sufficient by hypothesis to compute any intermediate frame -
 526       * and the maximum stack size as well - without using any control flow graph).
 527       */
 528     private Label currentBasicBlock;
 529 
 530     /**
 531       * The relative stack size after the last visited instruction. This size is relative to the
 532       * beginning of {@link #currentBasicBlock}, i.e. the true stack size after the last visited
 533       * instruction is equal to the {@link Label#inputStackSize} of the current basic block plus {@link
 534       * #relativeStackSize}. When {@link #compute} is equal to {@link
 535       * #COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES}, {@link #currentBasicBlock} is always the start of
 536       * the method, so this relative size is also equal to the absolute stack size after the last
 537       * visited instruction.
 538       */
 539     private int relativeStackSize;
 540 
 541     /**
 542       * The maximum relative stack size after the last visited instruction. This size is relative to
 543       * the beginning of {@link #currentBasicBlock}, i.e. the true maximum stack size after the last
 544       * visited instruction is equal to the {@link Label#inputStackSize} of the current basic block
 545       * plus {@link #maxRelativeStackSize}.When {@link #compute} is equal to {@link
 546       * #COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES}, {@link #currentBasicBlock} is always the start of
 547       * the method, so this relative size is also equal to the absolute maximum stack size after the
 548       * last visited instruction.
 549       */
 550     private int maxRelativeStackSize;
 551 
 552     /** The number of local variables in the last visited stack map frame. */
 553     private int currentLocals;
 554 
 555     /** The bytecode offset of the last frame that was written in {@link #stackMapTableEntries}. */
 556     private int previousFrameOffset;
 557 
 558     /**
 559       * The last frame that was written in {@link #stackMapTableEntries}. This field has the same
 560       * format as {@link #currentFrame}.
 561       */
 562     private int[] previousFrame;
 563 
 564     /**
 565       * The current stack map frame. The first element contains the bytecode offset of the instruction
 566       * to which the frame corresponds, the second element is the number of locals and the third one is
 567       * the number of stack elements. The local variables start at index 3 and are followed by the
 568       * operand stack elements. In summary frame[0] = offset, frame[1] = numLocal, frame[2] = numStack.
 569       * Local variables and operand stack entries contain abstract types, as defined in {@link Frame},
 570       * but restricted to {@link Frame#CONSTANT_KIND}, {@link Frame#REFERENCE_KIND} or {@link
 571       * Frame#UNINITIALIZED_KIND} abstract types. Long and double types use only one array entry.
 572       */
 573     private int[] currentFrame;
 574 
 575     /** Whether this method contains subroutines. */
 576     private boolean hasSubroutines;
 577 
 578     // -----------------------------------------------------------------------------------------------
 579     // Other miscellaneous status fields
 580     // -----------------------------------------------------------------------------------------------
 581 
 582     /** Whether the bytecode of this method contains ASM specific instructions. */
 583     private boolean hasAsmInstructions;
 584 
 585     /**
 586       * The start offset of the last visited instruction. Used to set the offset field of type
 587       * annotations of type 'offset_target' (see <a
 588       * href="https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.7.20.1">JVMS
 589       * 4.7.20.1</a>).
 590       */
 591     private int lastBytecodeOffset;
 592 
 593     /**
 594       * The offset in bytes in {@link SymbolTable#getSource} from which the method_info for this method
 595       * (excluding its first 6 bytes) must be copied, or 0.
 596       */
 597     private int sourceOffset;
 598 
 599     /**
 600       * The length in bytes in {@link SymbolTable#getSource} which must be copied to get the
 601       * method_info for this method (excluding its first 6 bytes for access_flags, name_index and
 602       * descriptor_index).
 603       */
 604     private int sourceLength;
 605 
 606     // -----------------------------------------------------------------------------------------------
 607     // Constructor and accessors
 608     // -----------------------------------------------------------------------------------------------
 609 
 610     /**
 611       * Constructs a new {@link MethodWriter}.
 612       *
 613       * @param symbolTable where the constants used in this AnnotationWriter must be stored.
 614       * @param access the method's access flags (see {@link Opcodes}).
 615       * @param name the method's name.
 616       * @param descriptor the method's descriptor (see {@link Type}).
 617       * @param signature the method's signature. May be {@literal null}.
 618       * @param exceptions the internal names of the method's exceptions. May be {@literal null}.
 619       * @param compute indicates what must be computed (see #compute).
 620       */
 621     MethodWriter(
 622             final SymbolTable symbolTable,
 623             final int access,
 624             final String name,
 625             final String descriptor,
 626             final String signature,
 627             final String[] exceptions,
 628             final int compute) {
 629         super(/* latest api = */ Opcodes.ASM8);
 630         this.symbolTable = symbolTable;
 631         this.accessFlags = "<init>".equals(name) ? access | Constants.ACC_CONSTRUCTOR : access;
 632         this.nameIndex = symbolTable.addConstantUtf8(name);
 633         this.name = name;
 634         this.descriptorIndex = symbolTable.addConstantUtf8(descriptor);
 635         this.descriptor = descriptor;
 636         this.signatureIndex = signature == null ? 0 : symbolTable.addConstantUtf8(signature);
 637         if (exceptions != null && exceptions.length > 0) {
 638             numberOfExceptions = exceptions.length;
 639             this.exceptionIndexTable = new int[numberOfExceptions];
 640             for (int i = 0; i < numberOfExceptions; ++i) {
 641                 this.exceptionIndexTable[i] = symbolTable.addConstantClass(exceptions[i]).index;
 642             }
 643         } else {
 644             numberOfExceptions = 0;
 645             this.exceptionIndexTable = null;
 646         }
 647         this.compute = compute;
 648         if (compute != COMPUTE_NOTHING) {
 649             // Update maxLocals and currentLocals.
 650             int argumentsSize = Type.getArgumentsAndReturnSizes(descriptor) >> 2;
 651             if ((access & Opcodes.ACC_STATIC) != 0) {
 652                 --argumentsSize;
 653             }
 654             maxLocals = argumentsSize;
 655             currentLocals = argumentsSize;
 656             // Create and visit the label for the first basic block.
 657             firstBasicBlock = new Label();
 658             visitLabel(firstBasicBlock);
 659         }
 660     }
 661 
 662     boolean hasFrames() {
 663         return stackMapTableNumberOfEntries > 0;
 664     }
 665 
 666     boolean hasAsmInstructions() {
 667         return hasAsmInstructions;
 668     }
 669 
 670     // -----------------------------------------------------------------------------------------------
 671     // Implementation of the MethodVisitor abstract class
 672     // -----------------------------------------------------------------------------------------------
 673 
 674     @Override
 675     public void visitParameter(final String name, final int access) {
 676         if (parameters == null) {
 677             parameters = new ByteVector();
 678         }
 679         ++parametersCount;
 680         parameters.putShort((name == null) ? 0 : symbolTable.addConstantUtf8(name)).putShort(access);
 681     }
 682 
 683     @Override
 684     public AnnotationVisitor visitAnnotationDefault() {
 685         defaultValue = new ByteVector();
 686         return new AnnotationWriter(symbolTable, /* useNamedValues = */ false, defaultValue, null);
 687     }
 688 
 689     @Override
 690     public AnnotationVisitor visitAnnotation(final String descriptor, final boolean visible) {
 691         if (visible) {
 692             return lastRuntimeVisibleAnnotation =
 693                     AnnotationWriter.create(symbolTable, descriptor, lastRuntimeVisibleAnnotation);
 694         } else {
 695             return lastRuntimeInvisibleAnnotation =
 696                     AnnotationWriter.create(symbolTable, descriptor, lastRuntimeInvisibleAnnotation);
 697         }
 698     }
 699 
 700     @Override
 701     public AnnotationVisitor visitTypeAnnotation(
 702             final int typeRef, final TypePath typePath, final String descriptor, final boolean visible) {
 703         if (visible) {
 704             return lastRuntimeVisibleTypeAnnotation =
 705                     AnnotationWriter.create(
 706                             symbolTable, typeRef, typePath, descriptor, lastRuntimeVisibleTypeAnnotation);
 707         } else {
 708             return lastRuntimeInvisibleTypeAnnotation =
 709                     AnnotationWriter.create(
 710                             symbolTable, typeRef, typePath, descriptor, lastRuntimeInvisibleTypeAnnotation);
 711         }
 712     }
 713 
 714     @Override
 715     public void visitAnnotableParameterCount(final int parameterCount, final boolean visible) {
 716         if (visible) {
 717             visibleAnnotableParameterCount = parameterCount;
 718         } else {
 719             invisibleAnnotableParameterCount = parameterCount;
 720         }
 721     }
 722 
 723     @Override
 724     public AnnotationVisitor visitParameterAnnotation(
 725             final int parameter, final String annotationDescriptor, final boolean visible) {
 726         if (visible) {
 727             if (lastRuntimeVisibleParameterAnnotations == null) {
 728                 lastRuntimeVisibleParameterAnnotations =
 729                         new AnnotationWriter[Type.getArgumentTypes(descriptor).length];
 730             }
 731             return lastRuntimeVisibleParameterAnnotations[parameter] =
 732                     AnnotationWriter.create(
 733                             symbolTable, annotationDescriptor, lastRuntimeVisibleParameterAnnotations[parameter]);
 734         } else {
 735             if (lastRuntimeInvisibleParameterAnnotations == null) {
 736                 lastRuntimeInvisibleParameterAnnotations =
 737                         new AnnotationWriter[Type.getArgumentTypes(descriptor).length];
 738             }
 739             return lastRuntimeInvisibleParameterAnnotations[parameter] =
 740                     AnnotationWriter.create(
 741                             symbolTable,
 742                             annotationDescriptor,
 743                             lastRuntimeInvisibleParameterAnnotations[parameter]);
 744         }
 745     }
 746 
 747     @Override
 748     public void visitAttribute(final Attribute attribute) {
 749         // Store the attributes in the <i>reverse</i> order of their visit by this method.
 750         if (attribute.isCodeAttribute()) {
 751             attribute.nextAttribute = firstCodeAttribute;
 752             firstCodeAttribute = attribute;
 753         } else {
 754             attribute.nextAttribute = firstAttribute;
 755             firstAttribute = attribute;
 756         }
 757     }
 758 
 759     @Override
 760     public void visitCode() {
 761         // Nothing to do.
 762     }
 763 
 764     @Override
 765     public void visitFrame(
 766             final int type,
 767             final int numLocal,
 768             final Object[] local,
 769             final int numStack,
 770             final Object[] stack) {
 771         if (compute == COMPUTE_ALL_FRAMES) {
 772             return;
 773         }
 774 
 775         if (compute == COMPUTE_INSERTED_FRAMES) {
 776             if (currentBasicBlock.frame == null) {
 777                 // This should happen only once, for the implicit first frame (which is explicitly visited
 778                 // in ClassReader if the EXPAND_ASM_INSNS option is used - and COMPUTE_INSERTED_FRAMES
 779                 // can't be set if EXPAND_ASM_INSNS is not used).
 780                 currentBasicBlock.frame = new CurrentFrame(currentBasicBlock);
 781                 currentBasicBlock.frame.setInputFrameFromDescriptor(
 782                         symbolTable, accessFlags, descriptor, numLocal);
 783                 currentBasicBlock.frame.accept(this);
 784             } else {
 785                 if (type == Opcodes.F_NEW) {
 786                     currentBasicBlock.frame.setInputFrameFromApiFormat(
 787                             symbolTable, numLocal, local, numStack, stack);
 788                 }
 789                 // If type is not F_NEW then it is F_INSERT by hypothesis, and currentBlock.frame contains
 790                 // the stack map frame at the current instruction, computed from the last F_NEW frame and
 791                 // the bytecode instructions in between (via calls to CurrentFrame#execute).
 792                 currentBasicBlock.frame.accept(this);
 793             }
 794         } else if (type == Opcodes.F_NEW) {
 795             if (previousFrame == null) {
 796                 int argumentsSize = Type.getArgumentsAndReturnSizes(descriptor) >> 2;
 797                 Frame implicitFirstFrame = new Frame(new Label());
 798                 implicitFirstFrame.setInputFrameFromDescriptor(
 799                         symbolTable, accessFlags, descriptor, argumentsSize);
 800                 implicitFirstFrame.accept(this);
 801             }
 802             currentLocals = numLocal;
 803             int frameIndex = visitFrameStart(code.length, numLocal, numStack);
 804             for (int i = 0; i < numLocal; ++i) {
 805                 currentFrame[frameIndex++] = Frame.getAbstractTypeFromApiFormat(symbolTable, local[i]);
 806             }
 807             for (int i = 0; i < numStack; ++i) {
 808                 currentFrame[frameIndex++] = Frame.getAbstractTypeFromApiFormat(symbolTable, stack[i]);
 809             }
 810             visitFrameEnd();
 811         } else {
 812             if (symbolTable.getMajorVersion() < Opcodes.V1_6) {
 813                 throw new IllegalArgumentException("Class versions V1_5 or less must use F_NEW frames.");
 814             }
 815             int offsetDelta;
 816             if (stackMapTableEntries == null) {
 817                 stackMapTableEntries = new ByteVector();
 818                 offsetDelta = code.length;
 819             } else {
 820                 offsetDelta = code.length - previousFrameOffset - 1;
 821                 if (offsetDelta < 0) {
 822                     if (type == Opcodes.F_SAME) {
 823                         return;
 824                     } else {
 825                         throw new IllegalStateException();
 826                     }
 827                 }
 828             }
 829 
 830             switch (type) {
 831                 case Opcodes.F_FULL:
 832                     currentLocals = numLocal;
 833                     stackMapTableEntries.putByte(Frame.FULL_FRAME).putShort(offsetDelta).putShort(numLocal);
 834                     for (int i = 0; i < numLocal; ++i) {
 835                         putFrameType(local[i]);
 836                     }
 837                     stackMapTableEntries.putShort(numStack);
 838                     for (int i = 0; i < numStack; ++i) {
 839                         putFrameType(stack[i]);
 840                     }
 841                     break;
 842                 case Opcodes.F_APPEND:
 843                     currentLocals += numLocal;
 844                     stackMapTableEntries.putByte(Frame.SAME_FRAME_EXTENDED + numLocal).putShort(offsetDelta);
 845                     for (int i = 0; i < numLocal; ++i) {
 846                         putFrameType(local[i]);
 847                     }
 848                     break;
 849                 case Opcodes.F_CHOP:
 850                     currentLocals -= numLocal;
 851                     stackMapTableEntries.putByte(Frame.SAME_FRAME_EXTENDED - numLocal).putShort(offsetDelta);
 852                     break;
 853                 case Opcodes.F_SAME:
 854                     if (offsetDelta < 64) {
 855                         stackMapTableEntries.putByte(offsetDelta);
 856                     } else {
 857                         stackMapTableEntries.putByte(Frame.SAME_FRAME_EXTENDED).putShort(offsetDelta);
 858                     }
 859                     break;
 860                 case Opcodes.F_SAME1:
 861                     if (offsetDelta < 64) {
 862                         stackMapTableEntries.putByte(Frame.SAME_LOCALS_1_STACK_ITEM_FRAME + offsetDelta);
 863                     } else {
 864                         stackMapTableEntries
 865                                 .putByte(Frame.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED)
 866                                 .putShort(offsetDelta);
 867                     }
 868                     putFrameType(stack[0]);
 869                     break;
 870                 default:
 871                     throw new IllegalArgumentException();
 872             }
 873 
 874             previousFrameOffset = code.length;
 875             ++stackMapTableNumberOfEntries;
 876         }
 877 
 878         if (compute == COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES) {
 879             relativeStackSize = numStack;
 880             for (int i = 0; i < numStack; ++i) {
 881                 if (stack[i] == Opcodes.LONG || stack[i] == Opcodes.DOUBLE) {
 882                     relativeStackSize++;
 883                 }
 884             }
 885             if (relativeStackSize > maxRelativeStackSize) {
 886                 maxRelativeStackSize = relativeStackSize;
 887             }
 888         }
 889 
 890         maxStack = Math.max(maxStack, numStack);
 891         maxLocals = Math.max(maxLocals, currentLocals);
 892     }
 893 
 894     @Override
 895     public void visitInsn(final int opcode) {
 896         lastBytecodeOffset = code.length;
 897         // Add the instruction to the bytecode of the method.
 898         code.putByte(opcode);
 899         // If needed, update the maximum stack size and number of locals, and stack map frames.
 900         if (currentBasicBlock != null) {
 901             if (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES) {
 902                 currentBasicBlock.frame.execute(opcode, 0, null, null);
 903             } else {
 904                 int size = relativeStackSize + STACK_SIZE_DELTA[opcode];
 905                 if (size > maxRelativeStackSize) {
 906                     maxRelativeStackSize = size;
 907                 }
 908                 relativeStackSize = size;
 909             }
 910             if ((opcode >= Opcodes.IRETURN && opcode <= Opcodes.RETURN) || opcode == Opcodes.ATHROW) {
 911                 endCurrentBasicBlockWithNoSuccessor();
 912             }
 913         }
 914     }
 915 
 916     @Override
 917     public void visitIntInsn(final int opcode, final int operand) {
 918         lastBytecodeOffset = code.length;
 919         // Add the instruction to the bytecode of the method.
 920         if (opcode == Opcodes.SIPUSH) {
 921             code.put12(opcode, operand);
 922         } else { // BIPUSH or NEWARRAY
 923             code.put11(opcode, operand);
 924         }
 925         // If needed, update the maximum stack size and number of locals, and stack map frames.
 926         if (currentBasicBlock != null) {
 927             if (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES) {
 928                 currentBasicBlock.frame.execute(opcode, operand, null, null);
 929             } else if (opcode != Opcodes.NEWARRAY) {
 930                 // The stack size delta is 1 for BIPUSH or SIPUSH, and 0 for NEWARRAY.
 931                 int size = relativeStackSize + 1;
 932                 if (size > maxRelativeStackSize) {
 933                     maxRelativeStackSize = size;
 934                 }
 935                 relativeStackSize = size;
 936             }
 937         }
 938     }
 939 
 940     @Override
 941     public void visitVarInsn(final int opcode, final int var) {
 942         lastBytecodeOffset = code.length;
 943         // Add the instruction to the bytecode of the method.
 944         if (var < 4 && opcode != Opcodes.RET) {
 945             int optimizedOpcode;
 946             if (opcode < Opcodes.ISTORE) {
 947                 optimizedOpcode = Constants.ILOAD_0 + ((opcode - Opcodes.ILOAD) << 2) + var;
 948             } else {
 949                 optimizedOpcode = Constants.ISTORE_0 + ((opcode - Opcodes.ISTORE) << 2) + var;
 950             }
 951             code.putByte(optimizedOpcode);
 952         } else if (var >= 256) {
 953             code.putByte(Constants.WIDE).put12(opcode, var);
 954         } else {
 955             code.put11(opcode, var);
 956         }
 957         // If needed, update the maximum stack size and number of locals, and stack map frames.
 958         if (currentBasicBlock != null) {
 959             if (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES) {
 960                 currentBasicBlock.frame.execute(opcode, var, null, null);
 961             } else {
 962                 if (opcode == Opcodes.RET) {
 963                     // No stack size delta.
 964                     currentBasicBlock.flags |= Label.FLAG_SUBROUTINE_END;
 965                     currentBasicBlock.outputStackSize = (short) relativeStackSize;
 966                     endCurrentBasicBlockWithNoSuccessor();
 967                 } else { // xLOAD or xSTORE
 968                     int size = relativeStackSize + STACK_SIZE_DELTA[opcode];
 969                     if (size > maxRelativeStackSize) {
 970                         maxRelativeStackSize = size;
 971                     }
 972                     relativeStackSize = size;
 973                 }
 974             }
 975         }
 976         if (compute != COMPUTE_NOTHING) {
 977             int currentMaxLocals;
 978             if (opcode == Opcodes.LLOAD
 979                     || opcode == Opcodes.DLOAD
 980                     || opcode == Opcodes.LSTORE
 981                     || opcode == Opcodes.DSTORE) {
 982                 currentMaxLocals = var + 2;
 983             } else {
 984                 currentMaxLocals = var + 1;
 985             }
 986             if (currentMaxLocals > maxLocals) {
 987                 maxLocals = currentMaxLocals;
 988             }
 989         }
 990         if (opcode >= Opcodes.ISTORE && compute == COMPUTE_ALL_FRAMES && firstHandler != null) {
 991             // If there are exception handler blocks, each instruction within a handler range is, in
 992             // theory, a basic block (since execution can jump from this instruction to the exception
 993             // handler). As a consequence, the local variable types at the beginning of the handler
 994             // block should be the merge of the local variable types at all the instructions within the
 995             // handler range. However, instead of creating a basic block for each instruction, we can
 996             // get the same result in a more efficient way. Namely, by starting a new basic block after
 997             // each xSTORE instruction, which is what we do here.
 998             visitLabel(new Label());
 999         }
1000     }
1001 
1002     @Override
1003     public void visitTypeInsn(final int opcode, final String type) {
1004         lastBytecodeOffset = code.length;
1005         // Add the instruction to the bytecode of the method.
1006         Symbol typeSymbol = symbolTable.addConstantClass(type);
1007         code.put12(opcode, typeSymbol.index);
1008         // If needed, update the maximum stack size and number of locals, and stack map frames.
1009         if (currentBasicBlock != null) {
1010             if (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES) {
1011                 currentBasicBlock.frame.execute(opcode, lastBytecodeOffset, typeSymbol, symbolTable);
1012             } else if (opcode == Opcodes.NEW || opcode == Opcodes.DEFAULT) {
1013                 // The stack size delta is 1 for NEW, and 0 for ANEWARRAY, CHECKCAST, or INSTANCEOF.
1014                 int size = relativeStackSize + 1;
1015                 if (size > maxRelativeStackSize) {
1016                     maxRelativeStackSize = size;
1017                 }
1018                 relativeStackSize = size;
1019             }
1020         }
1021     }
1022 
1023     @Override
1024     public void visitFieldInsn(
1025             final int opcode, final String owner, final String name, final String descriptor) {
1026         lastBytecodeOffset = code.length;
1027         // Add the instruction to the bytecode of the method.
1028         Symbol fieldrefSymbol = symbolTable.addConstantFieldref(owner, name, descriptor);
1029         code.put12(opcode, fieldrefSymbol.index);
1030         // If needed, update the maximum stack size and number of locals, and stack map frames.
1031         if (currentBasicBlock != null) {
1032             if (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES) {
1033                 currentBasicBlock.frame.execute(opcode, 0, fieldrefSymbol, symbolTable);
1034             } else {
1035                 int size;
1036                 char firstDescChar = descriptor.charAt(0);
1037                 switch (opcode) {
1038                     case Opcodes.WITHFIELD:
1039                         size = relativeStackSize + (firstDescChar == 'D' || firstDescChar == 'J' ? -2 : -1);
1040                         break;
1041                     case Opcodes.GETSTATIC:
1042                         size = relativeStackSize + (firstDescChar == 'D' || firstDescChar == 'J' ? 2 : 1);
1043                         break;
1044                     case Opcodes.PUTSTATIC:
1045                         size = relativeStackSize + (firstDescChar == 'D' || firstDescChar == 'J' ? -2 : -1);
1046                         break;
1047                     case Opcodes.GETFIELD:
1048                         size = relativeStackSize + (firstDescChar == 'D' || firstDescChar == 'J' ? 1 : 0);
1049                         break;
1050                     case Opcodes.PUTFIELD:
1051                     default:
1052                         size = relativeStackSize + (firstDescChar == 'D' || firstDescChar == 'J' ? -3 : -2);
1053                         break;
1054                 }
1055                 if (size > maxRelativeStackSize) {
1056                     maxRelativeStackSize = size;
1057                 }
1058                 relativeStackSize = size;
1059             }
1060         }
1061     }
1062 
1063     @Override
1064     public void visitMethodInsn(
1065             final int opcode,
1066             final String owner,
1067             final String name,
1068             final String descriptor,
1069             final boolean isInterface) {
1070         lastBytecodeOffset = code.length;
1071         // Add the instruction to the bytecode of the method.
1072         Symbol methodrefSymbol = symbolTable.addConstantMethodref(owner, name, descriptor, isInterface);
1073         if (opcode == Opcodes.INVOKEINTERFACE) {
1074             code.put12(Opcodes.INVOKEINTERFACE, methodrefSymbol.index)
1075                     .put11(methodrefSymbol.getArgumentsAndReturnSizes() >> 2, 0);
1076         } else {
1077             code.put12(opcode, methodrefSymbol.index);
1078         }
1079         // If needed, update the maximum stack size and number of locals, and stack map frames.
1080         if (currentBasicBlock != null) {
1081             if (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES) {
1082                 currentBasicBlock.frame.execute(opcode, 0, methodrefSymbol, symbolTable);
1083             } else {
1084                 int argumentsAndReturnSize = methodrefSymbol.getArgumentsAndReturnSizes();
1085                 int stackSizeDelta = (argumentsAndReturnSize & 3) - (argumentsAndReturnSize >> 2);
1086                 int size;
1087                 if (opcode == Opcodes.INVOKESTATIC) {
1088                     size = relativeStackSize + stackSizeDelta + 1;
1089                 } else {
1090                     size = relativeStackSize + stackSizeDelta;
1091                 }
1092                 if (size > maxRelativeStackSize) {
1093                     maxRelativeStackSize = size;
1094                 }
1095                 relativeStackSize = size;
1096             }
1097         }
1098     }
1099 
1100     @Override
1101     public void visitInvokeDynamicInsn(
1102             final String name,
1103             final String descriptor,
1104             final Handle bootstrapMethodHandle,
1105             final Object... bootstrapMethodArguments) {
1106         lastBytecodeOffset = code.length;
1107         // Add the instruction to the bytecode of the method.
1108         Symbol invokeDynamicSymbol =
1109                 symbolTable.addConstantInvokeDynamic(
1110                         name, descriptor, bootstrapMethodHandle, bootstrapMethodArguments);
1111         code.put12(Opcodes.INVOKEDYNAMIC, invokeDynamicSymbol.index);
1112         code.putShort(0);
1113         // If needed, update the maximum stack size and number of locals, and stack map frames.
1114         if (currentBasicBlock != null) {
1115             if (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES) {
1116                 currentBasicBlock.frame.execute(Opcodes.INVOKEDYNAMIC, 0, invokeDynamicSymbol, symbolTable);
1117             } else {
1118                 int argumentsAndReturnSize = invokeDynamicSymbol.getArgumentsAndReturnSizes();
1119                 int stackSizeDelta = (argumentsAndReturnSize & 3) - (argumentsAndReturnSize >> 2) + 1;
1120                 int size = relativeStackSize + stackSizeDelta;
1121                 if (size > maxRelativeStackSize) {
1122                     maxRelativeStackSize = size;
1123                 }
1124                 relativeStackSize = size;
1125             }
1126         }
1127     }
1128 
1129     @Override
1130     public void visitJumpInsn(final int opcode, final Label label) {
1131         lastBytecodeOffset = code.length;
1132         // Add the instruction to the bytecode of the method.
1133         // Compute the 'base' opcode, i.e. GOTO or JSR if opcode is GOTO_W or JSR_W, otherwise opcode.
1134         int baseOpcode =
1135                 opcode >= Constants.GOTO_W ? opcode - Constants.WIDE_JUMP_OPCODE_DELTA : opcode;
1136         boolean nextInsnIsJumpTarget = false;
1137         if ((label.flags & Label.FLAG_RESOLVED) != 0
1138                 && label.bytecodeOffset - code.length < Short.MIN_VALUE) {
1139             // Case of a backward jump with an offset < -32768. In this case we automatically replace GOTO
1140             // with GOTO_W, JSR with JSR_W and IFxxx <l> with IFNOTxxx <L> GOTO_W <l> L:..., where
1141             // IFNOTxxx is the "opposite" opcode of IFxxx (e.g. IFNE for IFEQ) and where <L> designates
1142             // the instruction just after the GOTO_W.
1143             if (baseOpcode == Opcodes.GOTO) {
1144                 code.putByte(Constants.GOTO_W);
1145             } else if (baseOpcode == Opcodes.JSR) {
1146                 code.putByte(Constants.JSR_W);
1147             } else {
1148                 // Put the "opposite" opcode of baseOpcode. This can be done by flipping the least
1149                 // significant bit for IFNULL and IFNONNULL, and similarly for IFEQ ... IF_ACMPEQ (with a
1150                 // pre and post offset by 1). The jump offset is 8 bytes (3 for IFNOTxxx, 5 for GOTO_W).
1151                 code.putByte(baseOpcode >= Opcodes.IFNULL ? baseOpcode ^ 1 : ((baseOpcode + 1) ^ 1) - 1);
1152                 code.putShort(8);
1153                 // Here we could put a GOTO_W in theory, but if ASM specific instructions are used in this
1154                 // method or another one, and if the class has frames, we will need to insert a frame after
1155                 // this GOTO_W during the additional ClassReader -> ClassWriter round trip to remove the ASM
1156                 // specific instructions. To not miss this additional frame, we need to use an ASM_GOTO_W
1157                 // here, which has the unfortunate effect of forcing this additional round trip (which in
1158                 // some case would not have been really necessary, but we can't know this at this point).
1159                 code.putByte(Constants.ASM_GOTO_W);
1160                 hasAsmInstructions = true;
1161                 // The instruction after the GOTO_W becomes the target of the IFNOT instruction.
1162                 nextInsnIsJumpTarget = true;
1163             }
1164             label.put(code, code.length - 1, true);
1165         } else if (baseOpcode != opcode) {
1166             // Case of a GOTO_W or JSR_W specified by the user (normally ClassReader when used to remove
1167             // ASM specific instructions). In this case we keep the original instruction.
1168             code.putByte(opcode);
1169             label.put(code, code.length - 1, true);
1170         } else {
1171             // Case of a jump with an offset >= -32768, or of a jump with an unknown offset. In these
1172             // cases we store the offset in 2 bytes (which will be increased via a ClassReader ->
1173             // ClassWriter round trip if it turns out that 2 bytes are not sufficient).
1174             code.putByte(baseOpcode);
1175             label.put(code, code.length - 1, false);
1176         }
1177 
1178         // If needed, update the maximum stack size and number of locals, and stack map frames.
1179         if (currentBasicBlock != null) {
1180             Label nextBasicBlock = null;
1181             if (compute == COMPUTE_ALL_FRAMES) {
1182                 currentBasicBlock.frame.execute(baseOpcode, 0, null, null);
1183                 // Record the fact that 'label' is the target of a jump instruction.
1184                 label.getCanonicalInstance().flags |= Label.FLAG_JUMP_TARGET;
1185                 // Add 'label' as a successor of the current basic block.
1186                 addSuccessorToCurrentBasicBlock(Edge.JUMP, label);
1187                 if (baseOpcode != Opcodes.GOTO) {
1188                     // The next instruction starts a new basic block (except for GOTO: by default the code
1189                     // following a goto is unreachable - unless there is an explicit label for it - and we
1190                     // should not compute stack frame types for its instructions).
1191                     nextBasicBlock = new Label();
1192                 }
1193             } else if (compute == COMPUTE_INSERTED_FRAMES) {
1194                 currentBasicBlock.frame.execute(baseOpcode, 0, null, null);
1195             } else if (compute == COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES) {
1196                 // No need to update maxRelativeStackSize (the stack size delta is always negative).
1197                 relativeStackSize += STACK_SIZE_DELTA[baseOpcode];
1198             } else {
1199                 if (baseOpcode == Opcodes.JSR) {
1200                     // Record the fact that 'label' designates a subroutine, if not already done.
1201                     if ((label.flags & Label.FLAG_SUBROUTINE_START) == 0) {
1202                         label.flags |= Label.FLAG_SUBROUTINE_START;
1203                         hasSubroutines = true;
1204                     }
1205                     currentBasicBlock.flags |= Label.FLAG_SUBROUTINE_CALLER;
1206                     // Note that, by construction in this method, a block which calls a subroutine has at
1207                     // least two successors in the control flow graph: the first one (added below) leads to
1208                     // the instruction after the JSR, while the second one (added here) leads to the JSR
1209                     // target. Note that the first successor is virtual (it does not correspond to a possible
1210                     // execution path): it is only used to compute the successors of the basic blocks ending
1211                     // with a ret, in {@link Label#addSubroutineRetSuccessors}.
1212                     addSuccessorToCurrentBasicBlock(relativeStackSize + 1, label);
1213                     // The instruction after the JSR starts a new basic block.
1214                     nextBasicBlock = new Label();
1215                 } else {
1216                     // No need to update maxRelativeStackSize (the stack size delta is always negative).
1217                     relativeStackSize += STACK_SIZE_DELTA[baseOpcode];
1218                     addSuccessorToCurrentBasicBlock(relativeStackSize, label);
1219                 }
1220             }
1221             // If the next instruction starts a new basic block, call visitLabel to add the label of this
1222             // instruction as a successor of the current block, and to start a new basic block.
1223             if (nextBasicBlock != null) {
1224                 if (nextInsnIsJumpTarget) {
1225                     nextBasicBlock.flags |= Label.FLAG_JUMP_TARGET;
1226                 }
1227                 visitLabel(nextBasicBlock);
1228             }
1229             if (baseOpcode == Opcodes.GOTO) {
1230                 endCurrentBasicBlockWithNoSuccessor();
1231             }
1232         }
1233     }
1234 
1235     @Override
1236     public void visitLabel(final Label label) {
1237         // Resolve the forward references to this label, if any.
1238         hasAsmInstructions |= label.resolve(code.data, code.length);
1239         // visitLabel starts a new basic block (except for debug only labels), so we need to update the
1240         // previous and current block references and list of successors.
1241         if ((label.flags & Label.FLAG_DEBUG_ONLY) != 0) {
1242             return;
1243         }
1244         if (compute == COMPUTE_ALL_FRAMES) {
1245             if (currentBasicBlock != null) {
1246                 if (label.bytecodeOffset == currentBasicBlock.bytecodeOffset) {
1247                     // We use {@link Label#getCanonicalInstance} to store the state of a basic block in only
1248                     // one place, but this does not work for labels which have not been visited yet.
1249                     // Therefore, when we detect here two labels having the same bytecode offset, we need to
1250                     // - consolidate the state scattered in these two instances into the canonical instance:
1251                     currentBasicBlock.flags |= (label.flags & Label.FLAG_JUMP_TARGET);
1252                     // - make sure the two instances share the same Frame instance (the implementation of
1253                     // {@link Label#getCanonicalInstance} relies on this property; here label.frame should be
1254                     // null):
1255                     label.frame = currentBasicBlock.frame;
1256                     // - and make sure to NOT assign 'label' into 'currentBasicBlock' or 'lastBasicBlock', so
1257                     // that they still refer to the canonical instance for this bytecode offset.
1258                     return;
1259                 }
1260                 // End the current basic block (with one new successor).
1261                 addSuccessorToCurrentBasicBlock(Edge.JUMP, label);
1262             }
1263             // Append 'label' at the end of the basic block list.
1264             if (lastBasicBlock != null) {
1265                 if (label.bytecodeOffset == lastBasicBlock.bytecodeOffset) {
1266                     // Same comment as above.
1267                     lastBasicBlock.flags |= (label.flags & Label.FLAG_JUMP_TARGET);
1268                     // Here label.frame should be null.
1269                     label.frame = lastBasicBlock.frame;
1270                     currentBasicBlock = lastBasicBlock;
1271                     return;
1272                 }
1273                 lastBasicBlock.nextBasicBlock = label;
1274             }
1275             lastBasicBlock = label;
1276             // Make it the new current basic block.
1277             currentBasicBlock = label;
1278             // Here label.frame should be null.
1279             label.frame = new Frame(label);
1280         } else if (compute == COMPUTE_INSERTED_FRAMES) {
1281             if (currentBasicBlock == null) {
1282                 // This case should happen only once, for the visitLabel call in the constructor. Indeed, if
1283                 // compute is equal to COMPUTE_INSERTED_FRAMES, currentBasicBlock stays unchanged.
1284                 currentBasicBlock = label;
1285             } else {
1286                 // Update the frame owner so that a correct frame offset is computed in Frame.accept().
1287                 currentBasicBlock.frame.owner = label;
1288             }
1289         } else if (compute == COMPUTE_MAX_STACK_AND_LOCAL) {
1290             if (currentBasicBlock != null) {
1291                 // End the current basic block (with one new successor).
1292                 currentBasicBlock.outputStackMax = (short) maxRelativeStackSize;
1293                 addSuccessorToCurrentBasicBlock(relativeStackSize, label);
1294             }
1295             // Start a new current basic block, and reset the current and maximum relative stack sizes.
1296             currentBasicBlock = label;
1297             relativeStackSize = 0;
1298             maxRelativeStackSize = 0;
1299             // Append the new basic block at the end of the basic block list.
1300             if (lastBasicBlock != null) {
1301                 lastBasicBlock.nextBasicBlock = label;
1302             }
1303             lastBasicBlock = label;
1304         } else if (compute == COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES && currentBasicBlock == null) {
1305             // This case should happen only once, for the visitLabel call in the constructor. Indeed, if
1306             // compute is equal to COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES, currentBasicBlock stays
1307             // unchanged.
1308             currentBasicBlock = label;
1309         }
1310     }
1311 
1312     @Override
1313     public void visitLdcInsn(final Object value) {
1314         lastBytecodeOffset = code.length;
1315         // Add the instruction to the bytecode of the method.
1316         Symbol constantSymbol = symbolTable.addConstant(value);
1317         int constantIndex = constantSymbol.index;
1318         char firstDescriptorChar;
1319         boolean isLongOrDouble =
1320                 constantSymbol.tag == Symbol.CONSTANT_LONG_TAG
1321                         || constantSymbol.tag == Symbol.CONSTANT_DOUBLE_TAG
1322                         || (constantSymbol.tag == Symbol.CONSTANT_DYNAMIC_TAG
1323                                 && ((firstDescriptorChar = constantSymbol.value.charAt(0)) == 'J'
1324                                         || firstDescriptorChar == 'D'));
1325         if (isLongOrDouble) {
1326             code.put12(Constants.LDC2_W, constantIndex);
1327         } else if (constantIndex >= 256) {
1328             code.put12(Constants.LDC_W, constantIndex);
1329         } else {
1330             code.put11(Opcodes.LDC, constantIndex);
1331         }
1332         // If needed, update the maximum stack size and number of locals, and stack map frames.
1333         if (currentBasicBlock != null) {
1334             if (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES) {
1335                 currentBasicBlock.frame.execute(Opcodes.LDC, 0, constantSymbol, symbolTable);
1336             } else {
1337                 int size = relativeStackSize + (isLongOrDouble ? 2 : 1);
1338                 if (size > maxRelativeStackSize) {
1339                     maxRelativeStackSize = size;
1340                 }
1341                 relativeStackSize = size;
1342             }
1343         }
1344     }
1345 
1346     @Override
1347     public void visitIincInsn(final int var, final int increment) {
1348         lastBytecodeOffset = code.length;
1349         // Add the instruction to the bytecode of the method.
1350         if ((var > 255) || (increment > 127) || (increment < -128)) {
1351             code.putByte(Constants.WIDE).put12(Opcodes.IINC, var).putShort(increment);
1352         } else {
1353             code.putByte(Opcodes.IINC).put11(var, increment);
1354         }
1355         // If needed, update the maximum stack size and number of locals, and stack map frames.
1356         if (currentBasicBlock != null
1357                 && (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES)) {
1358             currentBasicBlock.frame.execute(Opcodes.IINC, var, null, null);
1359         }
1360         if (compute != COMPUTE_NOTHING) {
1361             int currentMaxLocals = var + 1;
1362             if (currentMaxLocals > maxLocals) {
1363                 maxLocals = currentMaxLocals;
1364             }
1365         }
1366     }
1367 
1368     @Override
1369     public void visitTableSwitchInsn(
1370             final int min, final int max, final Label dflt, final Label... labels) {
1371         lastBytecodeOffset = code.length;
1372         // Add the instruction to the bytecode of the method.
1373         code.putByte(Opcodes.TABLESWITCH).putByteArray(null, 0, (4 - code.length % 4) % 4);
1374         dflt.put(code, lastBytecodeOffset, true);
1375         code.putInt(min).putInt(max);
1376         for (Label label : labels) {
1377             label.put(code, lastBytecodeOffset, true);
1378         }
1379         // If needed, update the maximum stack size and number of locals, and stack map frames.
1380         visitSwitchInsn(dflt, labels);
1381     }
1382 
1383     @Override
1384     public void visitLookupSwitchInsn(final Label dflt, final int[] keys, final Label[] labels) {
1385         lastBytecodeOffset = code.length;
1386         // Add the instruction to the bytecode of the method.
1387         code.putByte(Opcodes.LOOKUPSWITCH).putByteArray(null, 0, (4 - code.length % 4) % 4);
1388         dflt.put(code, lastBytecodeOffset, true);
1389         code.putInt(labels.length);
1390         for (int i = 0; i < labels.length; ++i) {
1391             code.putInt(keys[i]);
1392             labels[i].put(code, lastBytecodeOffset, true);
1393         }
1394         // If needed, update the maximum stack size and number of locals, and stack map frames.
1395         visitSwitchInsn(dflt, labels);
1396     }
1397 
1398     private void visitSwitchInsn(final Label dflt, final Label[] labels) {
1399         if (currentBasicBlock != null) {
1400             if (compute == COMPUTE_ALL_FRAMES) {
1401                 currentBasicBlock.frame.execute(Opcodes.LOOKUPSWITCH, 0, null, null);
1402                 // Add all the labels as successors of the current basic block.
1403                 addSuccessorToCurrentBasicBlock(Edge.JUMP, dflt);
1404                 dflt.getCanonicalInstance().flags |= Label.FLAG_JUMP_TARGET;
1405                 for (Label label : labels) {
1406                     addSuccessorToCurrentBasicBlock(Edge.JUMP, label);
1407                     label.getCanonicalInstance().flags |= Label.FLAG_JUMP_TARGET;
1408                 }
1409             } else if (compute == COMPUTE_MAX_STACK_AND_LOCAL) {
1410                 // No need to update maxRelativeStackSize (the stack size delta is always negative).
1411                 --relativeStackSize;
1412                 // Add all the labels as successors of the current basic block.
1413                 addSuccessorToCurrentBasicBlock(relativeStackSize, dflt);
1414                 for (Label label : labels) {
1415                     addSuccessorToCurrentBasicBlock(relativeStackSize, label);
1416                 }
1417             }
1418             // End the current basic block.
1419             endCurrentBasicBlockWithNoSuccessor();
1420         }
1421     }
1422 
1423     @Override
1424     public void visitMultiANewArrayInsn(final String descriptor, final int numDimensions) {
1425         lastBytecodeOffset = code.length;
1426         // Add the instruction to the bytecode of the method.
1427         Symbol descSymbol = symbolTable.addConstantClass(descriptor);
1428         code.put12(Opcodes.MULTIANEWARRAY, descSymbol.index).putByte(numDimensions);
1429         // If needed, update the maximum stack size and number of locals, and stack map frames.
1430         if (currentBasicBlock != null) {
1431             if (compute == COMPUTE_ALL_FRAMES || compute == COMPUTE_INSERTED_FRAMES) {
1432                 currentBasicBlock.frame.execute(
1433                         Opcodes.MULTIANEWARRAY, numDimensions, descSymbol, symbolTable);
1434             } else {
1435                 // No need to update maxRelativeStackSize (the stack size delta is always negative).
1436                 relativeStackSize += 1 - numDimensions;
1437             }
1438         }
1439     }
1440 
1441     @Override
1442     public AnnotationVisitor visitInsnAnnotation(
1443             final int typeRef, final TypePath typePath, final String descriptor, final boolean visible) {
1444         if (visible) {
1445             return lastCodeRuntimeVisibleTypeAnnotation =
1446                     AnnotationWriter.create(
1447                             symbolTable,
1448                             (typeRef & 0xFF0000FF) | (lastBytecodeOffset << 8),
1449                             typePath,
1450                             descriptor,
1451                             lastCodeRuntimeVisibleTypeAnnotation);
1452         } else {
1453             return lastCodeRuntimeInvisibleTypeAnnotation =
1454                     AnnotationWriter.create(
1455                             symbolTable,
1456                             (typeRef & 0xFF0000FF) | (lastBytecodeOffset << 8),
1457                             typePath,
1458                             descriptor,
1459                             lastCodeRuntimeInvisibleTypeAnnotation);
1460         }
1461     }
1462 
1463     @Override
1464     public void visitTryCatchBlock(
1465             final Label start, final Label end, final Label handler, final String type) {
1466         Handler newHandler =
1467                 new Handler(
1468                         start, end, handler, type != null ? symbolTable.addConstantClass(type).index : 0, type);
1469         if (firstHandler == null) {
1470             firstHandler = newHandler;
1471         } else {
1472             lastHandler.nextHandler = newHandler;
1473         }
1474         lastHandler = newHandler;
1475     }
1476 
1477     @Override
1478     public AnnotationVisitor visitTryCatchAnnotation(
1479             final int typeRef, final TypePath typePath, final String descriptor, final boolean visible) {
1480         if (visible) {
1481             return lastCodeRuntimeVisibleTypeAnnotation =
1482                     AnnotationWriter.create(
1483                             symbolTable, typeRef, typePath, descriptor, lastCodeRuntimeVisibleTypeAnnotation);
1484         } else {
1485             return lastCodeRuntimeInvisibleTypeAnnotation =
1486                     AnnotationWriter.create(
1487                             symbolTable, typeRef, typePath, descriptor, lastCodeRuntimeInvisibleTypeAnnotation);
1488         }
1489     }
1490 
1491     @Override
1492     public void visitLocalVariable(
1493             final String name,
1494             final String descriptor,
1495             final String signature,
1496             final Label start,
1497             final Label end,
1498             final int index) {
1499         if (signature != null) {
1500             if (localVariableTypeTable == null) {
1501                 localVariableTypeTable = new ByteVector();
1502             }
1503             ++localVariableTypeTableLength;
1504             localVariableTypeTable
1505                     .putShort(start.bytecodeOffset)
1506                     .putShort(end.bytecodeOffset - start.bytecodeOffset)
1507                     .putShort(symbolTable.addConstantUtf8(name))
1508                     .putShort(symbolTable.addConstantUtf8(signature))
1509                     .putShort(index);
1510         }
1511         if (localVariableTable == null) {
1512             localVariableTable = new ByteVector();
1513         }
1514         ++localVariableTableLength;
1515         localVariableTable
1516                 .putShort(start.bytecodeOffset)
1517                 .putShort(end.bytecodeOffset - start.bytecodeOffset)
1518                 .putShort(symbolTable.addConstantUtf8(name))
1519                 .putShort(symbolTable.addConstantUtf8(descriptor))
1520                 .putShort(index);
1521         if (compute != COMPUTE_NOTHING) {
1522             char firstDescChar = descriptor.charAt(0);
1523             int currentMaxLocals = index + (firstDescChar == 'J' || firstDescChar == 'D' ? 2 : 1);
1524             if (currentMaxLocals > maxLocals) {
1525                 maxLocals = currentMaxLocals;
1526             }
1527         }
1528     }
1529 
1530     @Override
1531     public AnnotationVisitor visitLocalVariableAnnotation(
1532             final int typeRef,
1533             final TypePath typePath,
1534             final Label[] start,
1535             final Label[] end,
1536             final int[] index,
1537             final String descriptor,
1538             final boolean visible) {
1539         // Create a ByteVector to hold a 'type_annotation' JVMS structure.
1540         // See https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.7.20.
1541         ByteVector typeAnnotation = new ByteVector();
1542         // Write target_type, target_info, and target_path.
1543         typeAnnotation.putByte(typeRef >>> 24).putShort(start.length);
1544         for (int i = 0; i < start.length; ++i) {
1545             typeAnnotation
1546                     .putShort(start[i].bytecodeOffset)
1547                     .putShort(end[i].bytecodeOffset - start[i].bytecodeOffset)
1548                     .putShort(index[i]);
1549         }
1550         TypePath.put(typePath, typeAnnotation);
1551         // Write type_index and reserve space for num_element_value_pairs.
1552         typeAnnotation.putShort(symbolTable.addConstantUtf8(descriptor)).putShort(0);
1553         if (visible) {
1554             return lastCodeRuntimeVisibleTypeAnnotation =
1555                     new AnnotationWriter(
1556                             symbolTable,
1557                             /* useNamedValues = */ true,
1558                             typeAnnotation,
1559                             lastCodeRuntimeVisibleTypeAnnotation);
1560         } else {
1561             return lastCodeRuntimeInvisibleTypeAnnotation =
1562                     new AnnotationWriter(
1563                             symbolTable,
1564                             /* useNamedValues = */ true,
1565                             typeAnnotation,
1566                             lastCodeRuntimeInvisibleTypeAnnotation);
1567         }
1568     }
1569 
1570     @Override
1571     public void visitLineNumber(final int line, final Label start) {
1572         if (lineNumberTable == null) {
1573             lineNumberTable = new ByteVector();
1574         }
1575         ++lineNumberTableLength;
1576         lineNumberTable.putShort(start.bytecodeOffset);
1577         lineNumberTable.putShort(line);
1578     }
1579 
1580     @Override
1581     public void visitMaxs(final int maxStack, final int maxLocals) {
1582         if (compute == COMPUTE_ALL_FRAMES) {
1583             computeAllFrames();
1584         } else if (compute == COMPUTE_MAX_STACK_AND_LOCAL) {
1585             computeMaxStackAndLocal();
1586         } else if (compute == COMPUTE_MAX_STACK_AND_LOCAL_FROM_FRAMES) {
1587             this.maxStack = maxRelativeStackSize;
1588         } else {
1589             this.maxStack = maxStack;
1590             this.maxLocals = maxLocals;
1591         }
1592     }
1593 
1594     /** Computes all the stack map frames of the method, from scratch. */
1595     private void computeAllFrames() {
1596         // Complete the control flow graph with exception handler blocks.
1597         Handler handler = firstHandler;
1598         while (handler != null) {
1599             String catchTypeDescriptor =
1600                     handler.catchTypeDescriptor == null ? "java/lang/Throwable" : handler.catchTypeDescriptor;
1601             int catchType = Frame.getAbstractTypeFromInternalName(symbolTable, catchTypeDescriptor);
1602             // Mark handlerBlock as an exception handler.
1603             Label handlerBlock = handler.handlerPc.getCanonicalInstance();
1604             handlerBlock.flags |= Label.FLAG_JUMP_TARGET;
1605             // Add handlerBlock as a successor of all the basic blocks in the exception handler range.
1606             Label handlerRangeBlock = handler.startPc.getCanonicalInstance();
1607             Label handlerRangeEnd = handler.endPc.getCanonicalInstance();
1608             while (handlerRangeBlock != handlerRangeEnd) {
1609                 handlerRangeBlock.outgoingEdges =
1610                         new Edge(catchType, handlerBlock, handlerRangeBlock.outgoingEdges);
1611                 handlerRangeBlock = handlerRangeBlock.nextBasicBlock;
1612             }
1613             handler = handler.nextHandler;
1614         }
1615 
1616         // Create and visit the first (implicit) frame.
1617         Frame firstFrame = firstBasicBlock.frame;
1618         firstFrame.setInputFrameFromDescriptor(symbolTable, accessFlags, descriptor, this.maxLocals);
1619         firstFrame.accept(this);
1620 
1621         // Fix point algorithm: add the first basic block to a list of blocks to process (i.e. blocks
1622         // whose stack map frame has changed) and, while there are blocks to process, remove one from
1623         // the list and update the stack map frames of its successor blocks in the control flow graph
1624         // (which might change them, in which case these blocks must be processed too, and are thus
1625         // added to the list of blocks to process). Also compute the maximum stack size of the method,
1626         // as a by-product.
1627         Label listOfBlocksToProcess = firstBasicBlock;
1628         listOfBlocksToProcess.nextListElement = Label.EMPTY_LIST;
1629         int maxStackSize = 0;
1630         while (listOfBlocksToProcess != Label.EMPTY_LIST) {
1631             // Remove a basic block from the list of blocks to process.
1632             Label basicBlock = listOfBlocksToProcess;
1633             listOfBlocksToProcess = listOfBlocksToProcess.nextListElement;
1634             basicBlock.nextListElement = null;
1635             // By definition, basicBlock is reachable.
1636             basicBlock.flags |= Label.FLAG_REACHABLE;
1637             // Update the (absolute) maximum stack size.
1638             int maxBlockStackSize = basicBlock.frame.getInputStackSize() + basicBlock.outputStackMax;
1639             if (maxBlockStackSize > maxStackSize) {
1640                 maxStackSize = maxBlockStackSize;
1641             }
1642             // Update the successor blocks of basicBlock in the control flow graph.
1643             Edge outgoingEdge = basicBlock.outgoingEdges;
1644             while (outgoingEdge != null) {
1645                 Label successorBlock = outgoingEdge.successor.getCanonicalInstance();
1646                 boolean successorBlockChanged =
1647                         basicBlock.frame.merge(symbolTable, successorBlock.frame, outgoingEdge.info);
1648                 if (successorBlockChanged && successorBlock.nextListElement == null) {
1649                     // If successorBlock has changed it must be processed. Thus, if it is not already in the
1650                     // list of blocks to process, add it to this list.
1651                     successorBlock.nextListElement = listOfBlocksToProcess;
1652                     listOfBlocksToProcess = successorBlock;
1653                 }
1654                 outgoingEdge = outgoingEdge.nextEdge;
1655             }
1656         }
1657 
1658         // Loop over all the basic blocks and visit the stack map frames that must be stored in the
1659         // StackMapTable attribute. Also replace unreachable code with NOP* ATHROW, and remove it from
1660         // exception handler ranges.
1661         Label basicBlock = firstBasicBlock;
1662         while (basicBlock != null) {
1663             if ((basicBlock.flags & (Label.FLAG_JUMP_TARGET | Label.FLAG_REACHABLE))
1664                     == (Label.FLAG_JUMP_TARGET | Label.FLAG_REACHABLE)) {
1665                 basicBlock.frame.accept(this);
1666             }
1667             if ((basicBlock.flags & Label.FLAG_REACHABLE) == 0) {
1668                 // Find the start and end bytecode offsets of this unreachable block.
1669                 Label nextBasicBlock = basicBlock.nextBasicBlock;
1670                 int startOffset = basicBlock.bytecodeOffset;
1671                 int endOffset = (nextBasicBlock == null ? code.length : nextBasicBlock.bytecodeOffset) - 1;
1672                 if (endOffset >= startOffset) {
1673                     // Replace its instructions with NOP ... NOP ATHROW.
1674                     for (int i = startOffset; i < endOffset; ++i) {
1675                         code.data[i] = Opcodes.NOP;
1676                     }
1677                     code.data[endOffset] = (byte) Opcodes.ATHROW;
1678                     // Emit a frame for this unreachable block, with no local and a Throwable on the stack
1679                     // (so that the ATHROW could consume this Throwable if it were reachable).
1680                     int frameIndex = visitFrameStart(startOffset, /* numLocal = */ 0, /* numStack = */ 1);
1681                     currentFrame[frameIndex] =
1682                             Frame.getAbstractTypeFromInternalName(symbolTable, "java/lang/Throwable");
1683                     visitFrameEnd();
1684                     // Remove this unreachable basic block from the exception handler ranges.
1685                     firstHandler = Handler.removeRange(firstHandler, basicBlock, nextBasicBlock);
1686                     // The maximum stack size is now at least one, because of the Throwable declared above.
1687                     maxStackSize = Math.max(maxStackSize, 1);
1688                 }
1689             }
1690             basicBlock = basicBlock.nextBasicBlock;
1691         }
1692 
1693         this.maxStack = maxStackSize;
1694     }
1695 
1696     /** Computes the maximum stack size of the method. */
1697     private void computeMaxStackAndLocal() {
1698         // Complete the control flow graph with exception handler blocks.
1699         Handler handler = firstHandler;
1700         while (handler != null) {
1701             Label handlerBlock = handler.handlerPc;
1702             Label handlerRangeBlock = handler.startPc;
1703             Label handlerRangeEnd = handler.endPc;
1704             // Add handlerBlock as a successor of all the basic blocks in the exception handler range.
1705             while (handlerRangeBlock != handlerRangeEnd) {
1706                 if ((handlerRangeBlock.flags & Label.FLAG_SUBROUTINE_CALLER) == 0) {
1707                     handlerRangeBlock.outgoingEdges =
1708                             new Edge(Edge.EXCEPTION, handlerBlock, handlerRangeBlock.outgoingEdges);
1709                 } else {
1710                     // If handlerRangeBlock is a JSR block, add handlerBlock after the first two outgoing
1711                     // edges to preserve the hypothesis about JSR block successors order (see
1712                     // {@link #visitJumpInsn}).
1713                     handlerRangeBlock.outgoingEdges.nextEdge.nextEdge =
1714                             new Edge(
1715                                     Edge.EXCEPTION, handlerBlock, handlerRangeBlock.outgoingEdges.nextEdge.nextEdge);
1716                 }
1717                 handlerRangeBlock = handlerRangeBlock.nextBasicBlock;
1718             }
1719             handler = handler.nextHandler;
1720         }
1721 
1722         // Complete the control flow graph with the successor blocks of subroutines, if needed.
1723         if (hasSubroutines) {
1724             // First step: find the subroutines. This step determines, for each basic block, to which
1725             // subroutine(s) it belongs. Start with the main "subroutine":
1726             short numSubroutines = 1;
1727             firstBasicBlock.markSubroutine(numSubroutines);
1728             // Then, mark the subroutines called by the main subroutine, then the subroutines called by
1729             // those called by the main subroutine, etc.
1730             for (short currentSubroutine = 1; currentSubroutine <= numSubroutines; ++currentSubroutine) {
1731                 Label basicBlock = firstBasicBlock;
1732                 while (basicBlock != null) {
1733                     if ((basicBlock.flags & Label.FLAG_SUBROUTINE_CALLER) != 0
1734                             && basicBlock.subroutineId == currentSubroutine) {
1735                         Label jsrTarget = basicBlock.outgoingEdges.nextEdge.successor;
1736                         if (jsrTarget.subroutineId == 0) {
1737                             // If this subroutine has not been marked yet, find its basic blocks.
1738                             jsrTarget.markSubroutine(++numSubroutines);
1739                         }
1740                     }
1741                     basicBlock = basicBlock.nextBasicBlock;
1742                 }
1743             }
1744             // Second step: find the successors in the control flow graph of each subroutine basic block
1745             // 'r' ending with a RET instruction. These successors are the virtual successors of the basic
1746             // blocks ending with JSR instructions (see {@link #visitJumpInsn)} that can reach 'r'.
1747             Label basicBlock = firstBasicBlock;
1748             while (basicBlock != null) {
1749                 if ((basicBlock.flags & Label.FLAG_SUBROUTINE_CALLER) != 0) {
1750                     // By construction, jsr targets are stored in the second outgoing edge of basic blocks
1751                     // that ends with a jsr instruction (see {@link #FLAG_SUBROUTINE_CALLER}).
1752                     Label subroutine = basicBlock.outgoingEdges.nextEdge.successor;
1753                     subroutine.addSubroutineRetSuccessors(basicBlock);
1754                 }
1755                 basicBlock = basicBlock.nextBasicBlock;
1756             }
1757         }
1758 
1759         // Data flow algorithm: put the first basic block in a list of blocks to process (i.e. blocks
1760         // whose input stack size has changed) and, while there are blocks to process, remove one
1761         // from the list, update the input stack size of its successor blocks in the control flow
1762         // graph, and add these blocks to the list of blocks to process (if not already done).
1763         Label listOfBlocksToProcess = firstBasicBlock;
1764         listOfBlocksToProcess.nextListElement = Label.EMPTY_LIST;
1765         int maxStackSize = maxStack;
1766         while (listOfBlocksToProcess != Label.EMPTY_LIST) {
1767             // Remove a basic block from the list of blocks to process. Note that we don't reset
1768             // basicBlock.nextListElement to null on purpose, to make sure we don't reprocess already
1769             // processed basic blocks.
1770             Label basicBlock = listOfBlocksToProcess;
1771             listOfBlocksToProcess = listOfBlocksToProcess.nextListElement;
1772             // Compute the (absolute) input stack size and maximum stack size of this block.
1773             int inputStackTop = basicBlock.inputStackSize;
1774             int maxBlockStackSize = inputStackTop + basicBlock.outputStackMax;
1775             // Update the absolute maximum stack size of the method.
1776             if (maxBlockStackSize > maxStackSize) {
1777                 maxStackSize = maxBlockStackSize;
1778             }
1779             // Update the input stack size of the successor blocks of basicBlock in the control flow
1780             // graph, and add these blocks to the list of blocks to process, if not already done.
1781             Edge outgoingEdge = basicBlock.outgoingEdges;
1782             if ((basicBlock.flags & Label.FLAG_SUBROUTINE_CALLER) != 0) {
1783                 // Ignore the first outgoing edge of the basic blocks ending with a jsr: these are virtual
1784                 // edges which lead to the instruction just after the jsr, and do not correspond to a
1785                 // possible execution path (see {@link #visitJumpInsn} and
1786                 // {@link Label#FLAG_SUBROUTINE_CALLER}).
1787                 outgoingEdge = outgoingEdge.nextEdge;
1788             }
1789             while (outgoingEdge != null) {
1790                 Label successorBlock = outgoingEdge.successor;
1791                 if (successorBlock.nextListElement == null) {
1792                     successorBlock.inputStackSize =
1793                             (short) (outgoingEdge.info == Edge.EXCEPTION ? 1 : inputStackTop + outgoingEdge.info);
1794                     successorBlock.nextListElement = listOfBlocksToProcess;
1795                     listOfBlocksToProcess = successorBlock;
1796                 }
1797                 outgoingEdge = outgoingEdge.nextEdge;
1798             }
1799         }
1800         this.maxStack = maxStackSize;
1801     }
1802 
1803     @Override
1804     public void visitEnd() {
1805         // Nothing to do.
1806     }
1807 
1808     // -----------------------------------------------------------------------------------------------
1809     // Utility methods: control flow analysis algorithm
1810     // -----------------------------------------------------------------------------------------------
1811 
1812     /**
1813       * Adds a successor to {@link #currentBasicBlock} in the control flow graph.
1814       *
1815       * @param info information about the control flow edge to be added.
1816       * @param successor the successor block to be added to the current basic block.
1817       */
1818     private void addSuccessorToCurrentBasicBlock(final int info, final Label successor) {
1819         currentBasicBlock.outgoingEdges = new Edge(info, successor, currentBasicBlock.outgoingEdges);
1820     }
1821 
1822     /**
1823       * Ends the current basic block. This method must be used in the case where the current basic
1824       * block does not have any successor.
1825       *
1826       * <p>WARNING: this method must be called after the currently visited instruction has been put in
1827       * {@link #code} (if frames are computed, this method inserts a new Label to start a new basic
1828       * block after the current instruction).
1829       */
1830     private void endCurrentBasicBlockWithNoSuccessor() {
1831         if (compute == COMPUTE_ALL_FRAMES) {
1832             Label nextBasicBlock = new Label();
1833             nextBasicBlock.frame = new Frame(nextBasicBlock);
1834             nextBasicBlock.resolve(code.data, code.length);
1835             lastBasicBlock.nextBasicBlock = nextBasicBlock;
1836             lastBasicBlock = nextBasicBlock;
1837             currentBasicBlock = null;
1838         } else if (compute == COMPUTE_MAX_STACK_AND_LOCAL) {
1839             currentBasicBlock.outputStackMax = (short) maxRelativeStackSize;
1840             currentBasicBlock = null;
1841         }
1842     }
1843 
1844     // -----------------------------------------------------------------------------------------------
1845     // Utility methods: stack map frames
1846     // -----------------------------------------------------------------------------------------------
1847 
1848     /**
1849       * Starts the visit of a new stack map frame, stored in {@link #currentFrame}.
1850       *
1851       * @param offset the bytecode offset of the instruction to which the frame corresponds.
1852       * @param numLocal the number of local variables in the frame.
1853       * @param numStack the number of stack elements in the frame.
1854       * @return the index of the next element to be written in this frame.
1855       */
1856     int visitFrameStart(final int offset, final int numLocal, final int numStack) {
1857         int frameLength = 3 + numLocal + numStack;
1858         if (currentFrame == null || currentFrame.length < frameLength) {
1859             currentFrame = new int[frameLength];
1860         }
1861         currentFrame[0] = offset;
1862         currentFrame[1] = numLocal;
1863         currentFrame[2] = numStack;
1864         return 3;
1865     }
1866 
1867     /**
1868       * Sets an abstract type in {@link #currentFrame}.
1869       *
1870       * @param frameIndex the index of the element to be set in {@link #currentFrame}.
1871       * @param abstractType an abstract type.
1872       */
1873     void visitAbstractType(final int frameIndex, final int abstractType) {
1874         currentFrame[frameIndex] = abstractType;
1875     }
1876 
1877     /**
1878       * Ends the visit of {@link #currentFrame} by writing it in the StackMapTable entries and by
1879       * updating the StackMapTable number_of_entries (except if the current frame is the first one,
1880       * which is implicit in StackMapTable). Then resets {@link #currentFrame} to {@literal null}.
1881       */
1882     void visitFrameEnd() {
1883         if (previousFrame != null) {
1884             if (stackMapTableEntries == null) {
1885                 stackMapTableEntries = new ByteVector();
1886             }
1887             putFrame();
1888             ++stackMapTableNumberOfEntries;
1889         }
1890         previousFrame = currentFrame;
1891         currentFrame = null;
1892     }
1893 
1894     /** Compresses and writes {@link #currentFrame} in a new StackMapTable entry. */
1895     private void putFrame() {
1896         final int numLocal = currentFrame[1];
1897         final int numStack = currentFrame[2];
1898         if (symbolTable.getMajorVersion() < Opcodes.V1_6) {
1899             // Generate a StackMap attribute entry, which are always uncompressed.
1900             stackMapTableEntries.putShort(currentFrame[0]).putShort(numLocal);
1901             putAbstractTypes(3, 3 + numLocal);
1902             stackMapTableEntries.putShort(numStack);
1903             putAbstractTypes(3 + numLocal, 3 + numLocal + numStack);
1904             return;
1905         }
1906         final int offsetDelta =
1907                 stackMapTableNumberOfEntries == 0
1908                         ? currentFrame[0]
1909                         : currentFrame[0] - previousFrame[0] - 1;
1910         final int previousNumlocal = previousFrame[1];
1911         final int numLocalDelta = numLocal - previousNumlocal;
1912         int type = Frame.FULL_FRAME;
1913         if (numStack == 0) {
1914             switch (numLocalDelta) {
1915                 case -3:
1916                 case -2:
1917                 case -1:
1918                     type = Frame.CHOP_FRAME;
1919                     break;
1920                 case 0:
1921                     type = offsetDelta < 64 ? Frame.SAME_FRAME : Frame.SAME_FRAME_EXTENDED;
1922                     break;
1923                 case 1:
1924                 case 2:
1925                 case 3:
1926                     type = Frame.APPEND_FRAME;
1927                     break;
1928                 default:
1929                     // Keep the FULL_FRAME type.
1930                     break;
1931             }
1932         } else if (numLocalDelta == 0 && numStack == 1) {
1933             type =
1934                     offsetDelta < 63
1935                             ? Frame.SAME_LOCALS_1_STACK_ITEM_FRAME
1936                             : Frame.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED;
1937         }
1938         if (type != Frame.FULL_FRAME) {
1939             // Verify if locals are the same as in the previous frame.
1940             int frameIndex = 3;
1941             for (int i = 0; i < previousNumlocal && i < numLocal; i++) {
1942                 if (currentFrame[frameIndex] != previousFrame[frameIndex]) {
1943                     type = Frame.FULL_FRAME;
1944                     break;
1945                 }
1946                 frameIndex++;
1947             }
1948         }
1949         switch (type) {
1950             case Frame.SAME_FRAME:
1951                 stackMapTableEntries.putByte(offsetDelta);
1952                 break;
1953             case Frame.SAME_LOCALS_1_STACK_ITEM_FRAME:
1954                 stackMapTableEntries.putByte(Frame.SAME_LOCALS_1_STACK_ITEM_FRAME + offsetDelta);
1955                 putAbstractTypes(3 + numLocal, 4 + numLocal);
1956                 break;
1957             case Frame.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED:
1958                 stackMapTableEntries
1959                         .putByte(Frame.SAME_LOCALS_1_STACK_ITEM_FRAME_EXTENDED)
1960                         .putShort(offsetDelta);
1961                 putAbstractTypes(3 + numLocal, 4 + numLocal);
1962                 break;
1963             case Frame.SAME_FRAME_EXTENDED:
1964                 stackMapTableEntries.putByte(Frame.SAME_FRAME_EXTENDED).putShort(offsetDelta);
1965                 break;
1966             case Frame.CHOP_FRAME:
1967                 stackMapTableEntries
1968                         .putByte(Frame.SAME_FRAME_EXTENDED + numLocalDelta)
1969                         .putShort(offsetDelta);
1970                 break;
1971             case Frame.APPEND_FRAME:
1972                 stackMapTableEntries
1973                         .putByte(Frame.SAME_FRAME_EXTENDED + numLocalDelta)
1974                         .putShort(offsetDelta);
1975                 putAbstractTypes(3 + previousNumlocal, 3 + numLocal);
1976                 break;
1977             case Frame.FULL_FRAME:
1978             default:
1979                 stackMapTableEntries.putByte(Frame.FULL_FRAME).putShort(offsetDelta).putShort(numLocal);
1980                 putAbstractTypes(3, 3 + numLocal);
1981                 stackMapTableEntries.putShort(numStack);
1982                 putAbstractTypes(3 + numLocal, 3 + numLocal + numStack);
1983                 break;
1984         }
1985     }
1986 
1987     /**
1988       * Puts some abstract types of {@link #currentFrame} in {@link #stackMapTableEntries} , using the
1989       * JVMS verification_type_info format used in StackMapTable attributes.
1990       *
1991       * @param start index of the first type in {@link #currentFrame} to write.
1992       * @param end index of last type in {@link #currentFrame} to write (exclusive).
1993       */
1994     private void putAbstractTypes(final int start, final int end) {
1995         for (int i = start; i < end; ++i) {
1996             Frame.putAbstractType(symbolTable, currentFrame[i], stackMapTableEntries);
1997         }
1998     }
1999 
2000     /**
2001       * Puts the given public API frame element type in {@link #stackMapTableEntries} , using the JVMS
2002       * verification_type_info format used in StackMapTable attributes.
2003       *
2004       * @param type a frame element type described using the same format as in {@link
2005       *     MethodVisitor#visitFrame}, i.e. either {@link Opcodes#TOP}, {@link Opcodes#INTEGER}, {@link
2006       *     Opcodes#FLOAT}, {@link Opcodes#LONG}, {@link Opcodes#DOUBLE}, {@link Opcodes#NULL}, or
2007       *     {@link Opcodes#UNINITIALIZED_THIS}, or the internal name of a class, or a Label designating
2008       *     a NEW instruction (for uninitialized types).
2009       */
2010     private void putFrameType(final Object type) {
2011         if (type instanceof Integer) {
2012             stackMapTableEntries.putByte(((Integer) type).intValue());
2013         } else if (type instanceof String) {
2014             stackMapTableEntries
2015                     .putByte(Frame.ITEM_OBJECT)
2016                     .putShort(symbolTable.addConstantClass((String) type).index);
2017         } else {
2018             stackMapTableEntries
2019                     .putByte(Frame.ITEM_UNINITIALIZED)
2020                     .putShort(((Label) type).bytecodeOffset);
2021         }
2022     }
2023 
2024     // -----------------------------------------------------------------------------------------------
2025     // Utility methods
2026     // -----------------------------------------------------------------------------------------------
2027 
2028     /**
2029       * Returns whether the attributes of this method can be copied from the attributes of the given
2030       * method (assuming there is no method visitor between the given ClassReader and this
2031       * MethodWriter). This method should only be called just after this MethodWriter has been created,
2032       * and before any content is visited. It returns true if the attributes corresponding to the
2033       * constructor arguments (at most a Signature, an Exception, a Deprecated and a Synthetic
2034       * attribute) are the same as the corresponding attributes in the given method.
2035       *
2036       * @param source the source ClassReader from which the attributes of this method might be copied.
2037       * @param hasSyntheticAttribute whether the method_info JVMS structure from which the attributes
2038       *     of this method might be copied contains a Synthetic attribute.
2039       * @param hasDeprecatedAttribute whether the method_info JVMS structure from which the attributes
2040       *     of this method might be copied contains a Deprecated attribute.
2041       * @param descriptorIndex the descriptor_index field of the method_info JVMS structure from which
2042       *     the attributes of this method might be copied.
2043       * @param signatureIndex the constant pool index contained in the Signature attribute of the
2044       *     method_info JVMS structure from which the attributes of this method might be copied, or 0.
2045       * @param exceptionsOffset the offset in 'source.b' of the Exceptions attribute of the method_info
2046       *     JVMS structure from which the attributes of this method might be copied, or 0.
2047       * @return whether the attributes of this method can be copied from the attributes of the
2048       *     method_info JVMS structure in 'source.b', between 'methodInfoOffset' and 'methodInfoOffset'
2049       *     + 'methodInfoLength'.
2050       */
2051     boolean canCopyMethodAttributes(
2052             final ClassReader source,
2053             final boolean hasSyntheticAttribute,
2054             final boolean hasDeprecatedAttribute,
2055             final int descriptorIndex,
2056             final int signatureIndex,
2057             final int exceptionsOffset) {
2058         // If the method descriptor has changed, with more locals than the max_locals field of the
2059         // original Code attribute, if any, then the original method attributes can't be copied. A
2060         // conservative check on the descriptor changes alone ensures this (being more precise is not
2061         // worth the additional complexity, because these cases should be rare -- if a transform changes
2062         // a method descriptor, most of the time it needs to change the method's code too).
2063         if (source != symbolTable.getSource()
2064                 || descriptorIndex != this.descriptorIndex
2065                 || signatureIndex != this.signatureIndex
2066                 || hasDeprecatedAttribute != ((accessFlags & Opcodes.ACC_DEPRECATED) != 0)) {
2067             return false;
2068         }
2069         boolean needSyntheticAttribute =
2070                 symbolTable.getMajorVersion() < Opcodes.V1_5 && (accessFlags & Opcodes.ACC_SYNTHETIC) != 0;
2071         if (hasSyntheticAttribute != needSyntheticAttribute) {
2072             return false;
2073         }
2074         if (exceptionsOffset == 0) {
2075             if (numberOfExceptions != 0) {
2076                 return false;
2077             }
2078         } else if (source.readUnsignedShort(exceptionsOffset) == numberOfExceptions) {
2079             int currentExceptionOffset = exceptionsOffset + 2;
2080             for (int i = 0; i < numberOfExceptions; ++i) {
2081                 if (source.readUnsignedShort(currentExceptionOffset) != exceptionIndexTable[i]) {
2082                     return false;
2083                 }
2084                 currentExceptionOffset += 2;
2085             }
2086         }
2087         return true;
2088     }
2089 
2090     /**
2091       * Sets the source from which the attributes of this method will be copied.
2092       *
2093       * @param methodInfoOffset the offset in 'symbolTable.getSource()' of the method_info JVMS
2094       *     structure from which the attributes of this method will be copied.
2095       * @param methodInfoLength the length in 'symbolTable.getSource()' of the method_info JVMS
2096       *     structure from which the attributes of this method will be copied.
2097       */
2098     void setMethodAttributesSource(final int methodInfoOffset, final int methodInfoLength) {
2099         // Don't copy the attributes yet, instead store their location in the source class reader so
2100         // they can be copied later, in {@link #putMethodInfo}. Note that we skip the 6 header bytes
2101         // of the method_info JVMS structure.
2102         this.sourceOffset = methodInfoOffset + 6;
2103         this.sourceLength = methodInfoLength - 6;
2104     }
2105 
2106     /**
2107       * Returns the size of the method_info JVMS structure generated by this MethodWriter. Also add the
2108       * names of the attributes of this method in the constant pool.
2109       *
2110       * @return the size in bytes of the method_info JVMS structure.
2111       */
2112     int computeMethodInfoSize() {
2113         // If this method_info must be copied from an existing one, the size computation is trivial.
2114         if (sourceOffset != 0) {
2115             // sourceLength excludes the first 6 bytes for access_flags, name_index and descriptor_index.
2116             return 6 + sourceLength;
2117         }
2118         // 2 bytes each for access_flags, name_index, descriptor_index and attributes_count.
2119         int size = 8;
2120         // For ease of reference, we use here the same attribute order as in Section 4.7 of the JVMS.
2121         if (code.length > 0) {
2122             if (code.length > 65535) {
2123                 throw new MethodTooLargeException(
2124                         symbolTable.getClassName(), name, descriptor, code.length);
2125             }
2126             symbolTable.addConstantUtf8(Constants.CODE);
2127             // The Code attribute has 6 header bytes, plus 2, 2, 4 and 2 bytes respectively for max_stack,
2128             // max_locals, code_length and attributes_count, plus the bytecode and the exception table.
2129             size += 16 + code.length + Handler.getExceptionTableSize(firstHandler);
2130             if (stackMapTableEntries != null) {
2131                 boolean useStackMapTable = symbolTable.getMajorVersion() >= Opcodes.V1_6;
2132                 symbolTable.addConstantUtf8(useStackMapTable ? Constants.STACK_MAP_TABLE : "StackMap");
2133                 // 6 header bytes and 2 bytes for number_of_entries.
2134                 size += 8 + stackMapTableEntries.length;
2135             }
2136             if (lineNumberTable != null) {
2137                 symbolTable.addConstantUtf8(Constants.LINE_NUMBER_TABLE);
2138                 // 6 header bytes and 2 bytes for line_number_table_length.
2139                 size += 8 + lineNumberTable.length;
2140             }
2141             if (localVariableTable != null) {
2142                 symbolTable.addConstantUtf8(Constants.LOCAL_VARIABLE_TABLE);
2143                 // 6 header bytes and 2 bytes for local_variable_table_length.
2144                 size += 8 + localVariableTable.length;
2145             }
2146             if (localVariableTypeTable != null) {
2147                 symbolTable.addConstantUtf8(Constants.LOCAL_VARIABLE_TYPE_TABLE);
2148                 // 6 header bytes and 2 bytes for local_variable_type_table_length.
2149                 size += 8 + localVariableTypeTable.length;
2150             }
2151             if (lastCodeRuntimeVisibleTypeAnnotation != null) {
2152                 size +=
2153                         lastCodeRuntimeVisibleTypeAnnotation.computeAnnotationsSize(
2154                                 Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS);
2155             }
2156             if (lastCodeRuntimeInvisibleTypeAnnotation != null) {
2157                 size +=
2158                         lastCodeRuntimeInvisibleTypeAnnotation.computeAnnotationsSize(
2159                                 Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS);
2160             }
2161             if (firstCodeAttribute != null) {
2162                 size +=
2163                         firstCodeAttribute.computeAttributesSize(
2164                                 symbolTable, code.data, code.length, maxStack, maxLocals);
2165             }
2166         }
2167         if (numberOfExceptions > 0) {
2168             symbolTable.addConstantUtf8(Constants.EXCEPTIONS);
2169             size += 8 + 2 * numberOfExceptions;
2170         }
2171         size += Attribute.computeAttributesSize(symbolTable, accessFlags, signatureIndex);
2172         size +=
2173                 AnnotationWriter.computeAnnotationsSize(
2174                         lastRuntimeVisibleAnnotation,
2175                         lastRuntimeInvisibleAnnotation,
2176                         lastRuntimeVisibleTypeAnnotation,
2177                         lastRuntimeInvisibleTypeAnnotation);
2178         if (lastRuntimeVisibleParameterAnnotations != null) {
2179             size +=
2180                     AnnotationWriter.computeParameterAnnotationsSize(
2181                             Constants.RUNTIME_VISIBLE_PARAMETER_ANNOTATIONS,
2182                             lastRuntimeVisibleParameterAnnotations,
2183                             visibleAnnotableParameterCount == 0
2184                                     ? lastRuntimeVisibleParameterAnnotations.length
2185                                     : visibleAnnotableParameterCount);
2186         }
2187         if (lastRuntimeInvisibleParameterAnnotations != null) {
2188             size +=
2189                     AnnotationWriter.computeParameterAnnotationsSize(
2190                             Constants.RUNTIME_INVISIBLE_PARAMETER_ANNOTATIONS,
2191                             lastRuntimeInvisibleParameterAnnotations,
2192                             invisibleAnnotableParameterCount == 0
2193                                     ? lastRuntimeInvisibleParameterAnnotations.length
2194                                     : invisibleAnnotableParameterCount);
2195         }
2196         if (defaultValue != null) {
2197             symbolTable.addConstantUtf8(Constants.ANNOTATION_DEFAULT);
2198             size += 6 + defaultValue.length;
2199         }
2200         if (parameters != null) {
2201             symbolTable.addConstantUtf8(Constants.METHOD_PARAMETERS);
2202             // 6 header bytes and 1 byte for parameters_count.
2203             size += 7 + parameters.length;
2204         }
2205         if (firstAttribute != null) {
2206             size += firstAttribute.computeAttributesSize(symbolTable);
2207         }
2208         return size;
2209     }
2210 
2211     /**
2212       * Puts the content of the method_info JVMS structure generated by this MethodWriter into the
2213       * given ByteVector.
2214       *
2215       * @param output where the method_info structure must be put.
2216       */
2217     void putMethodInfo(final ByteVector output) {
2218         boolean useSyntheticAttribute = symbolTable.getMajorVersion() < Opcodes.V1_5;
2219         int mask = useSyntheticAttribute ? Opcodes.ACC_SYNTHETIC : 0;
2220         output.putShort(accessFlags & ~mask).putShort(nameIndex).putShort(descriptorIndex);
2221         // If this method_info must be copied from an existing one, copy it now and return early.
2222         if (sourceOffset != 0) {
2223             output.putByteArray(symbolTable.getSource().classFileBuffer, sourceOffset, sourceLength);
2224             return;
2225         }
2226         // For ease of reference, we use here the same attribute order as in Section 4.7 of the JVMS.
2227         int attributeCount = 0;
2228         if (code.length > 0) {
2229             ++attributeCount;
2230         }
2231         if (numberOfExceptions > 0) {
2232             ++attributeCount;
2233         }
2234         if ((accessFlags & Opcodes.ACC_SYNTHETIC) != 0 && useSyntheticAttribute) {
2235             ++attributeCount;
2236         }
2237         if (signatureIndex != 0) {
2238             ++attributeCount;
2239         }
2240         if ((accessFlags & Opcodes.ACC_DEPRECATED) != 0) {
2241             ++attributeCount;
2242         }
2243         if (lastRuntimeVisibleAnnotation != null) {
2244             ++attributeCount;
2245         }
2246         if (lastRuntimeInvisibleAnnotation != null) {
2247             ++attributeCount;
2248         }
2249         if (lastRuntimeVisibleParameterAnnotations != null) {
2250             ++attributeCount;
2251         }
2252         if (lastRuntimeInvisibleParameterAnnotations != null) {
2253             ++attributeCount;
2254         }
2255         if (lastRuntimeVisibleTypeAnnotation != null) {
2256             ++attributeCount;
2257         }
2258         if (lastRuntimeInvisibleTypeAnnotation != null) {
2259             ++attributeCount;
2260         }
2261         if (defaultValue != null) {
2262             ++attributeCount;
2263         }
2264         if (parameters != null) {
2265             ++attributeCount;
2266         }
2267         if (firstAttribute != null) {
2268             attributeCount += firstAttribute.getAttributeCount();
2269         }
2270         // For ease of reference, we use here the same attribute order as in Section 4.7 of the JVMS.
2271         output.putShort(attributeCount);
2272         if (code.length > 0) {
2273             // 2, 2, 4 and 2 bytes respectively for max_stack, max_locals, code_length and
2274             // attributes_count, plus the bytecode and the exception table.
2275             int size = 10 + code.length + Handler.getExceptionTableSize(firstHandler);
2276             int codeAttributeCount = 0;
2277             if (stackMapTableEntries != null) {
2278                 // 6 header bytes and 2 bytes for number_of_entries.
2279                 size += 8 + stackMapTableEntries.length;
2280                 ++codeAttributeCount;
2281             }
2282             if (lineNumberTable != null) {
2283                 // 6 header bytes and 2 bytes for line_number_table_length.
2284                 size += 8 + lineNumberTable.length;
2285                 ++codeAttributeCount;
2286             }
2287             if (localVariableTable != null) {
2288                 // 6 header bytes and 2 bytes for local_variable_table_length.
2289                 size += 8 + localVariableTable.length;
2290                 ++codeAttributeCount;
2291             }
2292             if (localVariableTypeTable != null) {
2293                 // 6 header bytes and 2 bytes for local_variable_type_table_length.
2294                 size += 8 + localVariableTypeTable.length;
2295                 ++codeAttributeCount;
2296             }
2297             if (lastCodeRuntimeVisibleTypeAnnotation != null) {
2298                 size +=
2299                         lastCodeRuntimeVisibleTypeAnnotation.computeAnnotationsSize(
2300                                 Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS);
2301                 ++codeAttributeCount;
2302             }
2303             if (lastCodeRuntimeInvisibleTypeAnnotation != null) {
2304                 size +=
2305                         lastCodeRuntimeInvisibleTypeAnnotation.computeAnnotationsSize(
2306                                 Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS);
2307                 ++codeAttributeCount;
2308             }
2309             if (firstCodeAttribute != null) {
2310                 size +=
2311                         firstCodeAttribute.computeAttributesSize(
2312                                 symbolTable, code.data, code.length, maxStack, maxLocals);
2313                 codeAttributeCount += firstCodeAttribute.getAttributeCount();
2314             }
2315             output
2316                     .putShort(symbolTable.addConstantUtf8(Constants.CODE))
2317                     .putInt(size)
2318                     .putShort(maxStack)
2319                     .putShort(maxLocals)
2320                     .putInt(code.length)
2321                     .putByteArray(code.data, 0, code.length);
2322             Handler.putExceptionTable(firstHandler, output);
2323             output.putShort(codeAttributeCount);
2324             if (stackMapTableEntries != null) {
2325                 boolean useStackMapTable = symbolTable.getMajorVersion() >= Opcodes.V1_6;
2326                 output
2327                         .putShort(
2328                                 symbolTable.addConstantUtf8(
2329                                         useStackMapTable ? Constants.STACK_MAP_TABLE : "StackMap"))
2330                         .putInt(2 + stackMapTableEntries.length)
2331                         .putShort(stackMapTableNumberOfEntries)
2332                         .putByteArray(stackMapTableEntries.data, 0, stackMapTableEntries.length);
2333             }
2334             if (lineNumberTable != null) {
2335                 output
2336                         .putShort(symbolTable.addConstantUtf8(Constants.LINE_NUMBER_TABLE))
2337                         .putInt(2 + lineNumberTable.length)
2338                         .putShort(lineNumberTableLength)
2339                         .putByteArray(lineNumberTable.data, 0, lineNumberTable.length);
2340             }
2341             if (localVariableTable != null) {
2342                 output
2343                         .putShort(symbolTable.addConstantUtf8(Constants.LOCAL_VARIABLE_TABLE))
2344                         .putInt(2 + localVariableTable.length)
2345                         .putShort(localVariableTableLength)
2346                         .putByteArray(localVariableTable.data, 0, localVariableTable.length);
2347             }
2348             if (localVariableTypeTable != null) {
2349                 output
2350                         .putShort(symbolTable.addConstantUtf8(Constants.LOCAL_VARIABLE_TYPE_TABLE))
2351                         .putInt(2 + localVariableTypeTable.length)
2352                         .putShort(localVariableTypeTableLength)
2353                         .putByteArray(localVariableTypeTable.data, 0, localVariableTypeTable.length);
2354             }
2355             if (lastCodeRuntimeVisibleTypeAnnotation != null) {
2356                 lastCodeRuntimeVisibleTypeAnnotation.putAnnotations(
2357                         symbolTable.addConstantUtf8(Constants.RUNTIME_VISIBLE_TYPE_ANNOTATIONS), output);
2358             }
2359             if (lastCodeRuntimeInvisibleTypeAnnotation != null) {
2360                 lastCodeRuntimeInvisibleTypeAnnotation.putAnnotations(
2361                         symbolTable.addConstantUtf8(Constants.RUNTIME_INVISIBLE_TYPE_ANNOTATIONS), output);
2362             }
2363             if (firstCodeAttribute != null) {
2364                 firstCodeAttribute.putAttributes(
2365                         symbolTable, code.data, code.length, maxStack, maxLocals, output);
2366             }
2367         }
2368         if (numberOfExceptions > 0) {
2369             output
2370                     .putShort(symbolTable.addConstantUtf8(Constants.EXCEPTIONS))
2371                     .putInt(2 + 2 * numberOfExceptions)
2372                     .putShort(numberOfExceptions);
2373             for (int exceptionIndex : exceptionIndexTable) {
2374                 output.putShort(exceptionIndex);
2375             }
2376         }
2377         Attribute.putAttributes(symbolTable, accessFlags, signatureIndex, output);
2378         AnnotationWriter.putAnnotations(
2379                 symbolTable,
2380                 lastRuntimeVisibleAnnotation,
2381                 lastRuntimeInvisibleAnnotation,
2382                 lastRuntimeVisibleTypeAnnotation,
2383                 lastRuntimeInvisibleTypeAnnotation,
2384                 output);
2385         if (lastRuntimeVisibleParameterAnnotations != null) {
2386             AnnotationWriter.putParameterAnnotations(
2387                     symbolTable.addConstantUtf8(Constants.RUNTIME_VISIBLE_PARAMETER_ANNOTATIONS),
2388                     lastRuntimeVisibleParameterAnnotations,
2389                     visibleAnnotableParameterCount == 0
2390                             ? lastRuntimeVisibleParameterAnnotations.length
2391                             : visibleAnnotableParameterCount,
2392                     output);
2393         }
2394         if (lastRuntimeInvisibleParameterAnnotations != null) {
2395             AnnotationWriter.putParameterAnnotations(
2396                     symbolTable.addConstantUtf8(Constants.RUNTIME_INVISIBLE_PARAMETER_ANNOTATIONS),
2397                     lastRuntimeInvisibleParameterAnnotations,
2398                     invisibleAnnotableParameterCount == 0
2399                             ? lastRuntimeInvisibleParameterAnnotations.length
2400                             : invisibleAnnotableParameterCount,
2401                     output);
2402         }
2403         if (defaultValue != null) {
2404             output
2405                     .putShort(symbolTable.addConstantUtf8(Constants.ANNOTATION_DEFAULT))
2406                     .putInt(defaultValue.length)
2407                     .putByteArray(defaultValue.data, 0, defaultValue.length);
2408         }
2409         if (parameters != null) {
2410             output
2411                     .putShort(symbolTable.addConstantUtf8(Constants.METHOD_PARAMETERS))
2412                     .putInt(1 + parameters.length)
2413                     .putByte(parametersCount)
2414                     .putByteArray(parameters.data, 0, parameters.length);
2415         }
2416         if (firstAttribute != null) {
2417             firstAttribute.putAttributes(symbolTable, output);
2418         }
2419     }
2420 
2421     /**
2422       * Collects the attributes of this method into the given set of attribute prototypes.
2423       *
2424       * @param attributePrototypes a set of attribute prototypes.
2425       */
2426     final void collectAttributePrototypes(final Attribute.Set attributePrototypes) {
2427         attributePrototypes.addAttributes(firstAttribute);
2428         attributePrototypes.addAttributes(firstCodeAttribute);
2429     }
2430 }