< prev index next >

src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/Gen.java

Print this page

   1 /*
   2  * Copyright (c) 1999, 2024, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any

  80     private final StringConcat concat;
  81 
  82     /** Format of stackmap tables to be generated. */
  83     private final Code.StackMapFormat stackMap;
  84 
  85     /** A type that serves as the expected type for all method expressions.
  86      */
  87     private final Type methodType;
  88 
  89     public static Gen instance(Context context) {
  90         Gen instance = context.get(genKey);
  91         if (instance == null)
  92             instance = new Gen(context);
  93         return instance;
  94     }
  95 
  96     /** Constant pool writer, set by genClass.
  97      */
  98     final PoolWriter poolWriter;
  99 


 100     @SuppressWarnings("this-escape")
 101     protected Gen(Context context) {
 102         context.put(genKey, this);
 103 
 104         names = Names.instance(context);
 105         log = Log.instance(context);
 106         syms = Symtab.instance(context);
 107         chk = Check.instance(context);
 108         rs = Resolve.instance(context);
 109         make = TreeMaker.instance(context);
 110         target = Target.instance(context);
 111         types = Types.instance(context);
 112         concat = StringConcat.instance(context);
 113 
 114         methodType = new MethodType(null, null, null, syms.methodClass);
 115         accessDollar = "access" + target.syntheticNameChar();
 116         lower = Lower.instance(context);
 117 
 118         Options options = Options.instance(context);
 119         lineDebugInfo =
 120             options.isUnset(G_CUSTOM) ||
 121             options.isSet(G_CUSTOM, "lines");
 122         varDebugInfo =
 123             options.isUnset(G_CUSTOM)
 124             ? options.isSet(G)
 125             : options.isSet(G_CUSTOM, "vars");
 126         genCrt = options.isSet(XJCOV);
 127         debugCode = options.isSet("debug.code");
 128         disableVirtualizedPrivateInvoke = options.isSet("disableVirtualizedPrivateInvoke");
 129         poolWriter = new PoolWriter(types, names);

 130 
 131         // ignore cldc because we cannot have both stackmap formats
 132         this.stackMap = StackMapFormat.JSR202;
 133         annotate = Annotate.instance(context);
 134         qualifiedSymbolCache = new HashMap<>();

 135     }
 136 
 137     /** Switches
 138      */
 139     private final boolean lineDebugInfo;
 140     private final boolean varDebugInfo;
 141     private final boolean genCrt;
 142     private final boolean debugCode;
 143     private boolean disableVirtualizedPrivateInvoke;

 144 
 145     /** Code buffer, set by genMethod.
 146      */
 147     private Code code;
 148 
 149     /** Items structure, set by genMethod.
 150      */
 151     private Items items;
 152 
 153     /** Environment for symbol lookup, set by genClass
 154      */
 155     private Env<AttrContext> attrEnv;
 156 
 157     /** The top level tree.
 158      */
 159     private JCCompilationUnit toplevel;
 160 
 161     /** The number of code-gen errors in this class.
 162      */
 163     private int nerrs = 0;

 407     boolean hasFinally(JCTree target, Env<GenContext> env) {
 408         while (env.tree != target) {
 409             if (env.tree.hasTag(TRY) && env.info.finalize.hasFinalizer())
 410                 return true;
 411             env = env.next;
 412         }
 413         return false;
 414     }
 415 
 416 /* ************************************************************************
 417  * Normalizing class-members.
 418  *************************************************************************/
 419 
 420     /** Distribute member initializer code into constructors and {@code <clinit>}
 421      *  method.
 422      *  @param defs         The list of class member declarations.
 423      *  @param c            The enclosing class.
 424      */
 425     List<JCTree> normalizeDefs(List<JCTree> defs, ClassSymbol c) {
 426         ListBuffer<JCStatement> initCode = new ListBuffer<>();


 427         ListBuffer<Attribute.TypeCompound> initTAs = new ListBuffer<>();
 428         ListBuffer<JCStatement> clinitCode = new ListBuffer<>();
 429         ListBuffer<Attribute.TypeCompound> clinitTAs = new ListBuffer<>();
 430         ListBuffer<JCTree> methodDefs = new ListBuffer<>();
 431         // Sort definitions into three listbuffers:
 432         //  - initCode for instance initializers
 433         //  - clinitCode for class initializers
 434         //  - methodDefs for method definitions
 435         for (List<JCTree> l = defs; l.nonEmpty(); l = l.tail) {
 436             JCTree def = l.head;
 437             switch (def.getTag()) {
 438             case BLOCK:
 439                 JCBlock block = (JCBlock)def;
 440                 if ((block.flags & STATIC) != 0)
 441                     clinitCode.append(block);
 442                 else if ((block.flags & SYNTHETIC) == 0)
 443                     initCode.append(block);





 444                 break;
 445             case METHODDEF:
 446                 methodDefs.append(def);
 447                 break;
 448             case VARDEF:
 449                 JCVariableDecl vdef = (JCVariableDecl) def;
 450                 VarSymbol sym = vdef.sym;
 451                 checkDimension(vdef.pos(), sym.type);
 452                 if (vdef.init != null) {
 453                     if ((sym.flags() & STATIC) == 0) {
 454                         // Always initialize instance variables.
 455                         JCStatement init = make.at(vdef.pos()).
 456                             Assignment(sym, vdef.init);
 457                         initCode.append(init);
 458                         endPosTable.replaceTree(vdef, init);
 459                         initTAs.addAll(getAndRemoveNonFieldTAs(sym));
 460                     } else if (sym.getConstValue() == null) {
 461                         // Initialize class (static) variables only if
 462                         // they are not compile-time constants.
 463                         JCStatement init = make.at(vdef.pos).
 464                             Assignment(sym, vdef.init);
 465                         clinitCode.append(init);
 466                         endPosTable.replaceTree(vdef, init);
 467                         clinitTAs.addAll(getAndRemoveNonFieldTAs(sym));
 468                     } else {
 469                         checkStringConstant(vdef.init.pos(), sym.getConstValue());
 470                         /* if the init contains a reference to an external class, add it to the
 471                          * constant's pool
 472                          */
 473                         vdef.init.accept(classReferenceVisitor);
 474                     }
 475                 }
 476                 break;
 477             default:
 478                 Assert.error();
 479             }
 480         }
 481         // Insert any instance initializers into all constructors.
 482         if (initCode.length() != 0) {
 483             List<JCStatement> inits = initCode.toList();
 484             initTAs.addAll(c.getInitTypeAttributes());
 485             List<Attribute.TypeCompound> initTAlist = initTAs.toList();
 486             for (JCTree t : methodDefs) {
 487                 normalizeMethod((JCMethodDecl)t, inits, initTAlist);
 488             }
 489         }
 490         // If there are class initializers, create a <clinit> method
 491         // that contains them as its body.
 492         if (clinitCode.length() != 0) {
 493             MethodSymbol clinit = new MethodSymbol(
 494                 STATIC | (c.flags() & STRICTFP),
 495                 names.clinit,
 496                 new MethodType(
 497                     List.nil(), syms.voidType,
 498                     List.nil(), syms.methodClass),
 499                 c);
 500             c.members().enter(clinit);
 501             List<JCStatement> clinitStats = clinitCode.toList();
 502             JCBlock block = make.at(clinitStats.head.pos()).Block(0, clinitStats);
 503             block.endpos = TreeInfo.endPos(clinitStats.last());
 504             methodDefs.append(make.MethodDef(clinit, block));
 505 
 506             if (!clinitTAs.isEmpty())
 507                 clinit.appendUniqueTypeAttributes(clinitTAs.toList());

 530 
 531     /** Check a constant value and report if it is a string that is
 532      *  too large.
 533      */
 534     private void checkStringConstant(DiagnosticPosition pos, Object constValue) {
 535         if (nerrs != 0 || // only complain about a long string once
 536             constValue == null ||
 537             !(constValue instanceof String str) ||
 538             str.length() < PoolWriter.MAX_STRING_LENGTH)
 539             return;
 540         log.error(pos, Errors.LimitString);
 541         nerrs++;
 542     }
 543 
 544     /** Insert instance initializer code into constructors prior to the super() call.
 545      *  @param md        The tree potentially representing a
 546      *                   constructor's definition.
 547      *  @param initCode  The list of instance initializer statements.
 548      *  @param initTAs  Type annotations from the initializer expression.
 549      */
 550     void normalizeMethod(JCMethodDecl md, List<JCStatement> initCode, List<TypeCompound> initTAs) {
 551         if (TreeInfo.isConstructor(md) && TreeInfo.hasConstructorCall(md, names._super)) {
 552             // We are seeing a constructor that has a super() call.
 553             // Find the super() invocation and append the given initializer code.
 554             TreeInfo.mapSuperCalls(md.body, supercall -> make.Block(0, initCode.prepend(supercall)));






 555 
 556             if (md.body.endpos == Position.NOPOS)
 557                 md.body.endpos = TreeInfo.endPos(md.body.stats.last());
 558 
 559             md.sym.appendUniqueTypeAttributes(initTAs);
 560         }
 561     }
 562 


































 563 /* ************************************************************************
 564  * Traversal methods
 565  *************************************************************************/
 566 
 567     /** Visitor argument: The current environment.
 568      */
 569     Env<GenContext> env;
 570 
 571     /** Visitor argument: The expected type (prototype).
 572      */
 573     Type pt;
 574 
 575     /** Visitor result: The item representing the computed value.
 576      */
 577     Item result;
 578 
 579     /** Visitor method: generate code for a definition, catching and reporting
 580      *  any completion failures.
 581      *  @param tree    The definition to be visited.
 582      *  @param env     The environment current at the definition.

 927             // Count up extra parameters
 928             if (meth.isConstructor()) {
 929                 extras++;
 930                 if (meth.enclClass().isInner() &&
 931                     !meth.enclClass().isStatic()) {
 932                     extras++;
 933                 }
 934             } else if ((tree.mods.flags & STATIC) == 0) {
 935                 extras++;
 936             }
 937             //      System.err.println("Generating " + meth + " in " + meth.owner); //DEBUG
 938             if (Code.width(types.erasure(env.enclMethod.sym.type).getParameterTypes()) + extras >
 939                 ClassFile.MAX_PARAMETERS) {
 940                 log.error(tree.pos(), Errors.LimitParameters);
 941                 nerrs++;
 942             }
 943 
 944             else if (tree.body != null) {
 945                 // Create a new code structure and initialize it.
 946                 int startpcCrt = initCode(tree, env, fatcode);





 947 
 948                 try {
 949                     genStat(tree.body, env);
 950                 } catch (CodeSizeOverflow e) {
 951                     // Failed due to code limit, try again with jsr/ret
 952                     startpcCrt = initCode(tree, env, fatcode);
 953                     genStat(tree.body, env);


 954                 }
 955 
 956                 if (code.state.stacksize != 0) {
 957                     log.error(tree.body.pos(), Errors.StackSimError(tree.sym));
 958                     throw new AssertionError();
 959                 }
 960 
 961                 // If last statement could complete normally, insert a
 962                 // return at the end.
 963                 if (code.isAlive()) {
 964                     code.statBegin(TreeInfo.endPos(tree.body));
 965                     if (env.enclMethod == null ||
 966                         env.enclMethod.sym.type.getReturnType().hasTag(VOID)) {
 967                         code.emitop0(return_);
 968                     } else {
 969                         // sometime dead code seems alive (4415991);
 970                         // generate a small loop instead
 971                         int startpc = code.entryPoint();
 972                         CondItem c = items.makeCondItem(goto_);
 973                         code.resolve(c.jumpTrue(), startpc);

1002 
1003                 // Fill in type annotation positions for exception parameters
1004                 code.fillExceptionParameterPositions();
1005             }
1006         }
1007 
1008         private int initCode(JCMethodDecl tree, Env<GenContext> env, boolean fatcode) {
1009             MethodSymbol meth = tree.sym;
1010 
1011             // Create a new code structure.
1012             meth.code = code = new Code(meth,
1013                                         fatcode,
1014                                         lineDebugInfo ? toplevel.lineMap : null,
1015                                         varDebugInfo,
1016                                         stackMap,
1017                                         debugCode,
1018                                         genCrt ? new CRTable(tree, env.toplevel.endPositions)
1019                                                : null,
1020                                         syms,
1021                                         types,
1022                                         poolWriter);

1023             items = new Items(poolWriter, code, syms, types);
1024             if (code.debugCode) {
1025                 System.err.println(meth + " for body " + tree);
1026             }
1027 
1028             // If method is not static, create a new local variable address
1029             // for `this'.
1030             if ((tree.mods.flags & STATIC) == 0) {
1031                 Type selfType = meth.owner.type;
1032                 if (meth.isConstructor() && selfType != syms.objectType)
1033                     selfType = UninitializedType.uninitializedThis(selfType);
1034                 code.setDefined(
1035                         code.newLocal(
1036                             new VarSymbol(FINAL, names._this, selfType, meth.owner)));
1037             }
1038 
1039             // Mark all parameters as defined from the beginning of
1040             // the method.
1041             for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
1042                 checkDimension(l.head.pos(), l.head.sym.type);

1138     public void visitForLoop(JCForLoop tree) {
1139         int limit = code.nextreg;
1140         genStats(tree.init, env);
1141         genLoop(tree, tree.body, tree.cond, tree.step, true);
1142         code.endScopes(limit);
1143     }
1144     //where
1145         /** Generate code for a loop.
1146          *  @param loop       The tree representing the loop.
1147          *  @param body       The loop's body.
1148          *  @param cond       The loop's controlling condition.
1149          *  @param step       "Step" statements to be inserted at end of
1150          *                    each iteration.
1151          *  @param testFirst  True if the loop test belongs before the body.
1152          */
1153         private void genLoop(JCStatement loop,
1154                              JCStatement body,
1155                              JCExpression cond,
1156                              List<JCExpressionStatement> step,
1157                              boolean testFirst) {













1158             Env<GenContext> loopEnv = env.dup(loop, new GenContext());
1159             int startpc = code.entryPoint();
1160             if (testFirst) { //while or for loop
1161                 CondItem c;
1162                 if (cond != null) {
1163                     code.statBegin(cond.pos);
1164                     Assert.check(code.isStatementStart());
1165                     c = genCond(TreeInfo.skipParens(cond), CRT_FLOW_CONTROLLER);
1166                 } else {
1167                     c = items.makeCondItem(goto_);
1168                 }
1169                 Chain loopDone = c.jumpFalse();
1170                 code.resolve(c.trueJumps);
1171                 Assert.check(code.isStatementStart());
1172                 genStat(body, loopEnv, CRT_STATEMENT | CRT_FLOW_TARGET);
1173                 code.resolve(loopEnv.info.cont);
1174                 genStats(step, loopEnv);
1175                 code.resolve(code.branch(goto_), startpc);
1176                 code.resolve(loopDone);
1177             } else {

1204     }
1205 
1206     public void visitLabelled(JCLabeledStatement tree) {
1207         Env<GenContext> localEnv = env.dup(tree, new GenContext());
1208         genStat(tree.body, localEnv, CRT_STATEMENT);
1209         Chain exit = localEnv.info.exit;
1210         if (exit != null) {
1211             code.resolve(exit);
1212             exit.state.defined.excludeFrom(code.nextreg);
1213         }
1214     }
1215 
1216     public void visitSwitch(JCSwitch tree) {
1217         handleSwitch(tree, tree.selector, tree.cases, tree.patternSwitch);
1218     }
1219 
1220     @Override
1221     public void visitSwitchExpression(JCSwitchExpression tree) {
1222         code.resolvePending();
1223         boolean prevInCondSwitchExpression = inCondSwitchExpression;

1224         try {
1225             inCondSwitchExpression = false;
1226             doHandleSwitchExpression(tree);
1227         } finally {
1228             inCondSwitchExpression = prevInCondSwitchExpression;

1229         }
1230         result = items.makeStackItem(pt);
1231     }
1232 
1233     private void doHandleSwitchExpression(JCSwitchExpression tree) {
1234         List<LocalItem> prevStackBeforeSwitchExpression = stackBeforeSwitchExpression;
1235         LocalItem prevSwitchResult = switchResult;
1236         int limit = code.nextreg;
1237         try {
1238             stackBeforeSwitchExpression = List.nil();
1239             switchResult = null;
1240             if (hasTry(tree)) {
1241                 //if the switch expression contains try-catch, the catch handlers need to have
1242                 //an empty stack. So stash whole stack to local variables, and restore it before
1243                 //breaks:
1244                 while (code.state.stacksize > 0) {
1245                     Type type = code.state.peek();
1246                     Name varName = names.fromString(target.syntheticNameChar() +
1247                                                     "stack" +
1248                                                     target.syntheticNameChar() +

1284                     hasTry = true;
1285                 }
1286 
1287                 @Override
1288                 public void visitClassDef(JCClassDecl tree) {
1289                 }
1290 
1291                 @Override
1292                 public void visitLambda(JCLambda tree) {
1293                 }
1294             };
1295 
1296             HasTryScanner hasTryScanner = new HasTryScanner();
1297 
1298             hasTryScanner.scan(tree);
1299             return hasTryScanner.hasTry;
1300         }
1301 
1302     private void handleSwitch(JCTree swtch, JCExpression selector, List<JCCase> cases,
1303                               boolean patternSwitch) {










1304         int limit = code.nextreg;
1305         Assert.check(!selector.type.hasTag(CLASS));
1306         int switchStart = patternSwitch ? code.entryPoint() : -1;
1307         int startpcCrt = genCrt ? code.curCP() : 0;
1308         Assert.check(code.isStatementStart());
1309         Item sel = genExpr(selector, syms.intType);
1310         if (cases.isEmpty()) {
1311             // We are seeing:  switch <sel> {}
1312             sel.load().drop();
1313             if (genCrt)
1314                 code.crt.put(TreeInfo.skipParens(selector),
1315                              CRT_FLOW_CONTROLLER, startpcCrt, code.curCP());
1316         } else {
1317             // We are seeing a nonempty switch.
1318             sel.load();
1319             if (genCrt)
1320                 code.crt.put(TreeInfo.skipParens(selector),
1321                              CRT_FLOW_CONTROLLER, startpcCrt, code.curCP());
1322             Env<GenContext> switchEnv = env.dup(swtch, new GenContext());
1323             switchEnv.info.isSwitch = true;
1324 
1325             // Compute number of labels and minimum and maximum label values.
1326             // For each case, store its label in an array.
1327             int lo = Integer.MAX_VALUE;  // minimum label.
1328             int hi = Integer.MIN_VALUE;  // maximum label.
1329             int nlabels = 0;               // number of labels.
1330 
1331             int[] labels = new int[cases.length()];  // the label array.
1332             int defaultIndex = -1;     // the index of the default clause.
1333 
1334             List<JCCase> l = cases;
1335             for (int i = 0; i < labels.length; i++) {
1336                 if (l.head.labels.head instanceof JCConstantCaseLabel constLabel) {
1337                     Assert.check(l.head.labels.size() == 1);
1338                     int val = ((Number) constLabel.expr.type.constValue()).intValue();
1339                     labels[i] = val;
1340                     if (val < lo) lo = val;
1341                     if (hi < val) hi = val;
1342                     nlabels++;
1343                 } else {
1344                     Assert.check(defaultIndex == -1);
1345                     defaultIndex = i;
1346                 }
1347                 l = l.tail;
1348             }
1349 
1350             // Determine whether to issue a tableswitch or a lookupswitch
1351             // instruction.
1352             long table_space_cost = 4 + ((long) hi - lo + 1); // words
1353             long table_time_cost = 3; // comparisons
1354             long lookup_space_cost = 3 + 2 * (long) nlabels;
1355             long lookup_time_cost = nlabels;
1356             int opcode =
1357                 nlabels > 0 &&
1358                 table_space_cost + 3 * table_time_cost <=
1359                 lookup_space_cost + 3 * lookup_time_cost
1360                 ?
1361                 tableswitch : lookupswitch;
1362 
1363             int startpc = code.curCP();    // the position of the selector operation
1364             code.emitop0(opcode);
1365             code.align(4);
1366             int tableBase = code.curCP();  // the start of the jump table
1367             int[] offsets = null;          // a table of offsets for a lookupswitch
1368             code.emit4(-1);                // leave space for default offset
1369             if (opcode == tableswitch) {
1370                 code.emit4(lo);            // minimum label
1371                 code.emit4(hi);            // maximum label
1372                 for (long i = lo; i <= hi; i++) {  // leave space for jump table
1373                     code.emit4(-1);
1374                 }
1375             } else {
1376                 code.emit4(nlabels);    // number of labels
1377                 for (int i = 0; i < nlabels; i++) {
1378                     code.emit4(-1); code.emit4(-1); // leave space for lookup table
1379                 }
1380                 offsets = new int[labels.length];
1381             }
1382             Code.State stateSwitch = code.state.dup();
1383             code.markDead();
1384 
1385             // For each case do:
1386             l = cases;
1387             for (int i = 0; i < labels.length; i++) {
1388                 JCCase c = l.head;
1389                 l = l.tail;
1390 
1391                 int pc = code.entryPoint(stateSwitch);
1392                 // Insert offset directly into code or else into the
1393                 // offsets table.
1394                 if (i != defaultIndex) {
1395                     if (opcode == tableswitch) {
1396                         code.put4(
1397                             tableBase + 4 * (labels[i] - lo + 3),
1398                             pc - startpc);
1399                     } else {
1400                         offsets[i] = pc - startpc;
1401                     }
1402                 } else {
1403                     code.put4(tableBase, pc - startpc);
1404                 }
1405 
1406                 // Generate code for the statements in this case.
1407                 genStats(c.stats, switchEnv, CRT_FLOW_TARGET);
1408             }
1409 
1410             if (switchEnv.info.cont != null) {
1411                 Assert.check(patternSwitch);
1412                 code.resolve(switchEnv.info.cont, switchStart);
1413             }
1414 
1415             // Resolve all breaks.
1416             Chain exit = switchEnv.info.exit;
1417             if  (exit != null) {
1418                 code.resolve(exit);

1432                     if (code.get4(t) == -1)
1433                         code.put4(t, defaultOffset);
1434                 }
1435             } else {
1436                 // Sort non-default offsets and copy into lookup table.
1437                 if (defaultIndex >= 0)
1438                     for (int i = defaultIndex; i < labels.length - 1; i++) {
1439                         labels[i] = labels[i+1];
1440                         offsets[i] = offsets[i+1];
1441                     }
1442                 if (nlabels > 0)
1443                     qsort2(labels, offsets, 0, nlabels - 1);
1444                 for (int i = 0; i < nlabels; i++) {
1445                     int caseidx = tableBase + 8 * (i + 1);
1446                     code.put4(caseidx, labels[i]);
1447                     code.put4(caseidx + 4, offsets[i]);
1448                 }
1449             }
1450 
1451             if (swtch instanceof JCSwitchExpression) {
1452                  // Emit line position for the end of a switch expression
1453                  code.statBegin(TreeInfo.endPos(swtch));
1454             }
1455         }
1456         code.endScopes(limit);
1457     }
1458 //where
1459         /** Sort (int) arrays of keys and values
1460          */
1461        static void qsort2(int[] keys, int[] values, int lo, int hi) {
1462             int i = lo;
1463             int j = hi;
1464             int pivot = keys[(i+j)/2];
1465             do {
1466                 while (keys[i] < pivot) i++;
1467                 while (pivot < keys[j]) j--;
1468                 if (i <= j) {
1469                     int temp1 = keys[i];
1470                     keys[i] = keys[j];
1471                     keys[j] = temp1;
1472                     int temp2 = values[i];
1473                     values[i] = values[j];

1536             @Override
1537             void afterBody() {
1538                 if (tree.finalizer != null && (tree.finalizer.flags & BODY_ONLY_FINALIZE) != 0) {
1539                     //for body-only finally, remove the GenFinalizer after try body
1540                     //so that the finally is not generated to catch bodies:
1541                     tryEnv.info.finalize = null;
1542                 }
1543             }
1544 
1545         };
1546         tryEnv.info.gaps = new ListBuffer<>();
1547         genTry(tree.body, tree.catchers, tryEnv);
1548     }
1549     //where
1550         /** Generate code for a try or synchronized statement
1551          *  @param body      The body of the try or synchronized statement.
1552          *  @param catchers  The list of catch clauses.
1553          *  @param env       The current environment of the body.
1554          */
1555         void genTry(JCTree body, List<JCCatch> catchers, Env<GenContext> env) {









1556             int limit = code.nextreg;
1557             int startpc = code.curCP();
1558             Code.State stateTry = code.state.dup();
1559             genStat(body, env, CRT_BLOCK);
1560             int endpc = code.curCP();
1561             List<Integer> gaps = env.info.gaps.toList();
1562             code.statBegin(TreeInfo.endPos(body));
1563             genFinalizer(env);
1564             code.statBegin(TreeInfo.endPos(env.tree));
1565             Chain exitChain;
1566             boolean actualTry = env.tree.hasTag(TRY);
1567             if (startpc == endpc && actualTry) {
1568                 exitChain = code.branch(dontgoto);
1569             } else {
1570                 exitChain = code.branch(goto_);
1571             }
1572             endFinalizerGap(env);
1573             env.info.finalize.afterBody();
1574             boolean hasFinalizer =
1575                 env.info.finalize != null &&
1576                 env.info.finalize.hasFinalizer();
1577             if (startpc != endpc) for (List<JCCatch> l = catchers; l.nonEmpty(); l = l.tail) {
1578                 // start off with exception on stack
1579                 code.entryPoint(stateTry, l.head.param.sym.type);
1580                 genCatch(l.head, env, startpc, endpc, gaps);
1581                 genFinalizer(env);
1582                 if (hasFinalizer || l.tail.nonEmpty()) {
1583                     code.statBegin(TreeInfo.endPos(env.tree));
1584                     exitChain = Code.mergeChains(exitChain,
1585                                                  code.branch(goto_));
1586                 }
1587                 endFinalizerGap(env);
1588             }
1589             if (hasFinalizer && (startpc != endpc || !actualTry)) {
1590                 // Create a new register segment to avoid allocating
1591                 // the same variables in finalizers and other statements.
1592                 code.newRegSegment();
1593 
1594                 // Add a catch-all clause.
1595 
1596                 // start off with exception on stack
1597                 int catchallpc = code.entryPoint(stateTry, syms.throwableType);
1598 
1599                 // Register all exception ranges for catch all clause.
1600                 // The range of the catch all clause is from the beginning
1601                 // of the try or synchronized block until the present
1602                 // code pointer excluding all gaps in the current
1603                 // environment's GenContext.
1604                 int startseg = startpc;
1605                 while (env.info.gaps.nonEmpty()) {
1606                     int endseg = env.info.gaps.next().intValue();
1607                     registerCatch(body.pos(), startseg, endseg,
1608                                   catchallpc, 0);
1609                     startseg = env.info.gaps.next().intValue();
1610                 }
1611                 code.statBegin(TreeInfo.finalizerPos(env.tree, PosKind.FIRST_STAT_POS));
1612                 code.markStatBegin();
1613 
1614                 Item excVar = makeTemp(syms.throwableType);
1615                 excVar.store();
1616                 genFinalizer(env);
1617                 code.resolvePending();
1618                 code.statBegin(TreeInfo.finalizerPos(env.tree, PosKind.END_POS));
1619                 code.markStatBegin();
1620 
1621                 excVar.load();
1622                 registerCatch(body.pos(), startseg,
1623                               env.info.gaps.next().intValue(),
1624                               catchallpc, 0);
1625                 code.emitop0(athrow);
1626                 code.markDead();
1627 
1628                 // If there are jsr's to this finalizer, ...
1629                 if (env.info.cont != null) {
1630                     // Resolve all jsr's.
1631                     code.resolve(env.info.cont);
1632 
1633                     // Mark statement line number
1634                     code.statBegin(TreeInfo.finalizerPos(env.tree, PosKind.FIRST_STAT_POS));
1635                     code.markStatBegin();
1636 
1637                     // Save return address.
1638                     LocalItem retVar = makeTemp(syms.throwableType);
1639                     retVar.store();
1640 
1641                     // Generate finalizer code.
1642                     env.info.finalize.genLast();
1643 
1644                     // Return.

1747         /** Register a catch clause in the "Exceptions" code-attribute.
1748          */
1749         void registerCatch(DiagnosticPosition pos,
1750                            int startpc, int endpc,
1751                            int handler_pc, int catch_type) {
1752             char startpc1 = (char)startpc;
1753             char endpc1 = (char)endpc;
1754             char handler_pc1 = (char)handler_pc;
1755             if (startpc1 == startpc &&
1756                 endpc1 == endpc &&
1757                 handler_pc1 == handler_pc) {
1758                 code.addCatch(startpc1, endpc1, handler_pc1,
1759                               (char)catch_type);
1760             } else {
1761                 log.error(pos, Errors.LimitCodeTooLargeForTryStmt);
1762                 nerrs++;
1763             }
1764         }
1765 
1766     public void visitIf(JCIf tree) {









1767         int limit = code.nextreg;
1768         Chain thenExit = null;
1769         Assert.check(code.isStatementStart());
1770         CondItem c = genCond(TreeInfo.skipParens(tree.cond),
1771                              CRT_FLOW_CONTROLLER);
1772         Chain elseChain = c.jumpFalse();
1773         Assert.check(code.isStatementStart());
1774         if (!c.isFalse()) {
1775             code.resolve(c.trueJumps);
1776             genStat(tree.thenpart, env, CRT_STATEMENT | CRT_FLOW_TARGET);
1777             thenExit = code.branch(goto_);
1778         }
1779         if (elseChain != null) {
1780             code.resolve(elseChain);
1781             if (tree.elsepart != null) {
1782                 genStat(tree.elsepart, env,CRT_STATEMENT | CRT_FLOW_TARGET);
1783             }
1784         }
1785         code.resolve(thenExit);
1786         code.endScopes(limit);
1787         Assert.check(code.isStatementStart());
1788     }
1789 
1790     public void visitExec(JCExpressionStatement tree) {
1791         // Optimize x++ to ++x and x-- to --x.

2078                 nerrs++;
2079             }
2080             int elemcode = Code.arraycode(elemtype);
2081             if (elemcode == 0 || (elemcode == 1 && ndims == 1)) {
2082                 code.emitAnewarray(makeRef(pos, elemtype), type);
2083             } else if (elemcode == 1) {
2084                 code.emitMultianewarray(ndims, makeRef(pos, type), type);
2085             } else {
2086                 code.emitNewarray(elemcode, type);
2087             }
2088             return items.makeStackItem(type);
2089         }
2090 
2091     public void visitParens(JCParens tree) {
2092         result = genExpr(tree.expr, tree.expr.type);
2093     }
2094 
2095     public void visitAssign(JCAssign tree) {
2096         Item l = genExpr(tree.lhs, tree.lhs.type);
2097         genExpr(tree.rhs, tree.lhs.type).load();


2098         if (tree.rhs.type.hasTag(BOT)) {
2099             /* This is just a case of widening reference conversion that per 5.1.5 simply calls
2100                for "regarding a reference as having some other type in a manner that can be proved
2101                correct at compile time."
2102             */
2103             code.state.forceStackTop(tree.lhs.type);
2104         }
2105         result = items.makeAssignItem(l);
2106     }
2107 
2108     public void visitAssignop(JCAssignOp tree) {
2109         OperatorSymbol operator = tree.operator;
2110         Item l;
2111         if (operator.opcode == string_add) {
2112             l = concat.makeConcat(tree);
2113         } else {
2114             // Generate code for first expression
2115             l = genExpr(tree.lhs, tree.lhs.type);
2116 
2117             // If we have an increment of -32768 to +32767 of a local

2356             items.makeThisItem().load();
2357             sym = binaryQualifier(sym, env.enclClass.type);
2358             result = items.makeMemberItem(sym, nonVirtualForPrivateAccess(sym));
2359         }
2360     }
2361 
2362     //where
2363     private boolean nonVirtualForPrivateAccess(Symbol sym) {
2364         boolean useVirtual = target.hasVirtualPrivateInvoke() &&
2365                              !disableVirtualizedPrivateInvoke;
2366         return !useVirtual && ((sym.flags() & PRIVATE) != 0);
2367     }
2368 
2369     public void visitSelect(JCFieldAccess tree) {
2370         Symbol sym = tree.sym;
2371 
2372         if (tree.name == names._class) {
2373             code.emitLdc((LoadableConstant)checkDimension(tree.pos(), tree.selected.type));
2374             result = items.makeStackItem(pt);
2375             return;
2376        }
2377 
2378         Symbol ssym = TreeInfo.symbol(tree.selected);
2379 
2380         // Are we selecting via super?
2381         boolean selectSuper =
2382             ssym != null && (ssym.kind == TYP || ssym.name == names._super);
2383 
2384         // Are we accessing a member of the superclass in an access method
2385         // resulting from a qualified super?
2386         boolean accessSuper = isAccessSuper(env.enclMethod);
2387 
2388         Item base = (selectSuper)
2389             ? items.makeSuperItem()
2390             : genExpr(tree.selected, tree.selected.type);
2391 
2392         if (sym.kind == VAR && ((VarSymbol) sym).getConstValue() != null) {
2393             // We are seeing a variable that is constant but its selecting
2394             // expression is not.
2395             if ((sym.flags() & STATIC) != 0) {
2396                 if (!selectSuper && (ssym == null || ssym.kind != TYP))

   1 /*
   2  * Copyright (c) 1999, 2025, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any

  80     private final StringConcat concat;
  81 
  82     /** Format of stackmap tables to be generated. */
  83     private final Code.StackMapFormat stackMap;
  84 
  85     /** A type that serves as the expected type for all method expressions.
  86      */
  87     private final Type methodType;
  88 
  89     public static Gen instance(Context context) {
  90         Gen instance = context.get(genKey);
  91         if (instance == null)
  92             instance = new Gen(context);
  93         return instance;
  94     }
  95 
  96     /** Constant pool writer, set by genClass.
  97      */
  98     final PoolWriter poolWriter;
  99 
 100     private final UnsetFieldsInfo unsetFieldsInfo;
 101 
 102     @SuppressWarnings("this-escape")
 103     protected Gen(Context context) {
 104         context.put(genKey, this);
 105 
 106         names = Names.instance(context);
 107         log = Log.instance(context);
 108         syms = Symtab.instance(context);
 109         chk = Check.instance(context);
 110         rs = Resolve.instance(context);
 111         make = TreeMaker.instance(context);
 112         target = Target.instance(context);
 113         types = Types.instance(context);
 114         concat = StringConcat.instance(context);
 115 
 116         methodType = new MethodType(null, null, null, syms.methodClass);
 117         accessDollar = "access" + target.syntheticNameChar();
 118         lower = Lower.instance(context);
 119 
 120         Options options = Options.instance(context);
 121         lineDebugInfo =
 122             options.isUnset(G_CUSTOM) ||
 123             options.isSet(G_CUSTOM, "lines");
 124         varDebugInfo =
 125             options.isUnset(G_CUSTOM)
 126             ? options.isSet(G)
 127             : options.isSet(G_CUSTOM, "vars");
 128         genCrt = options.isSet(XJCOV);
 129         debugCode = options.isSet("debug.code");
 130         disableVirtualizedPrivateInvoke = options.isSet("disableVirtualizedPrivateInvoke");
 131         poolWriter = new PoolWriter(types, names);
 132         unsetFieldsInfo = UnsetFieldsInfo.instance(context);
 133 
 134         // ignore cldc because we cannot have both stackmap formats
 135         this.stackMap = StackMapFormat.JSR202;
 136         annotate = Annotate.instance(context);
 137         qualifiedSymbolCache = new HashMap<>();
 138         generateAssertUnsetFieldsFrame = options.isSet("generateAssertUnsetFieldsFrame");
 139     }
 140 
 141     /** Switches
 142      */
 143     private final boolean lineDebugInfo;
 144     private final boolean varDebugInfo;
 145     private final boolean genCrt;
 146     private final boolean debugCode;
 147     private boolean disableVirtualizedPrivateInvoke;
 148     private boolean generateAssertUnsetFieldsFrame;
 149 
 150     /** Code buffer, set by genMethod.
 151      */
 152     private Code code;
 153 
 154     /** Items structure, set by genMethod.
 155      */
 156     private Items items;
 157 
 158     /** Environment for symbol lookup, set by genClass
 159      */
 160     private Env<AttrContext> attrEnv;
 161 
 162     /** The top level tree.
 163      */
 164     private JCCompilationUnit toplevel;
 165 
 166     /** The number of code-gen errors in this class.
 167      */
 168     private int nerrs = 0;

 412     boolean hasFinally(JCTree target, Env<GenContext> env) {
 413         while (env.tree != target) {
 414             if (env.tree.hasTag(TRY) && env.info.finalize.hasFinalizer())
 415                 return true;
 416             env = env.next;
 417         }
 418         return false;
 419     }
 420 
 421 /* ************************************************************************
 422  * Normalizing class-members.
 423  *************************************************************************/
 424 
 425     /** Distribute member initializer code into constructors and {@code <clinit>}
 426      *  method.
 427      *  @param defs         The list of class member declarations.
 428      *  @param c            The enclosing class.
 429      */
 430     List<JCTree> normalizeDefs(List<JCTree> defs, ClassSymbol c) {
 431         ListBuffer<JCStatement> initCode = new ListBuffer<>();
 432         // only used for value classes
 433         ListBuffer<JCStatement> initBlocks = new ListBuffer<>();
 434         ListBuffer<Attribute.TypeCompound> initTAs = new ListBuffer<>();
 435         ListBuffer<JCStatement> clinitCode = new ListBuffer<>();
 436         ListBuffer<Attribute.TypeCompound> clinitTAs = new ListBuffer<>();
 437         ListBuffer<JCTree> methodDefs = new ListBuffer<>();
 438         // Sort definitions into three listbuffers:
 439         //  - initCode for instance initializers
 440         //  - clinitCode for class initializers
 441         //  - methodDefs for method definitions
 442         for (List<JCTree> l = defs; l.nonEmpty(); l = l.tail) {
 443             JCTree def = l.head;
 444             switch (def.getTag()) {
 445             case BLOCK:
 446                 JCBlock block = (JCBlock)def;
 447                 if ((block.flags & STATIC) != 0)
 448                     clinitCode.append(block);
 449                 else if ((block.flags & SYNTHETIC) == 0) {
 450                     if (c.isValueClass() || c.hasStrict()) {
 451                         initBlocks.append(block);
 452                     } else {
 453                         initCode.append(block);
 454                     }
 455                 }
 456                 break;
 457             case METHODDEF:
 458                 methodDefs.append(def);
 459                 break;
 460             case VARDEF:
 461                 JCVariableDecl vdef = (JCVariableDecl) def;
 462                 VarSymbol sym = vdef.sym;
 463                 checkDimension(vdef.pos(), sym.type);
 464                 if (vdef.init != null) {
 465                     if ((sym.flags() & STATIC) == 0) {
 466                         // Always initialize instance variables.
 467                         JCStatement init = make.at(vdef.pos()).
 468                             Assignment(sym, vdef.init);
 469                         initCode.append(init);
 470                         endPosTable.replaceTree(vdef, init);
 471                         initTAs.addAll(getAndRemoveNonFieldTAs(sym));
 472                     } else if (sym.getConstValue() == null) {
 473                         // Initialize class (static) variables only if
 474                         // they are not compile-time constants.
 475                         JCStatement init = make.at(vdef.pos).
 476                             Assignment(sym, vdef.init);
 477                         clinitCode.append(init);
 478                         endPosTable.replaceTree(vdef, init);
 479                         clinitTAs.addAll(getAndRemoveNonFieldTAs(sym));
 480                     } else {
 481                         checkStringConstant(vdef.init.pos(), sym.getConstValue());
 482                         /* if the init contains a reference to an external class, add it to the
 483                          * constant's pool
 484                          */
 485                         vdef.init.accept(classReferenceVisitor);
 486                     }
 487                 }
 488                 break;
 489             default:
 490                 Assert.error();
 491             }
 492         }
 493         // Insert any instance initializers into all constructors.
 494         if (initCode.length() != 0 || initBlocks.length() != 0) {

 495             initTAs.addAll(c.getInitTypeAttributes());
 496             List<Attribute.TypeCompound> initTAlist = initTAs.toList();
 497             for (JCTree t : methodDefs) {
 498                 normalizeMethod((JCMethodDecl)t, initCode.toList(), initBlocks.toList(), initTAlist);
 499             }
 500         }
 501         // If there are class initializers, create a <clinit> method
 502         // that contains them as its body.
 503         if (clinitCode.length() != 0) {
 504             MethodSymbol clinit = new MethodSymbol(
 505                 STATIC | (c.flags() & STRICTFP),
 506                 names.clinit,
 507                 new MethodType(
 508                     List.nil(), syms.voidType,
 509                     List.nil(), syms.methodClass),
 510                 c);
 511             c.members().enter(clinit);
 512             List<JCStatement> clinitStats = clinitCode.toList();
 513             JCBlock block = make.at(clinitStats.head.pos()).Block(0, clinitStats);
 514             block.endpos = TreeInfo.endPos(clinitStats.last());
 515             methodDefs.append(make.MethodDef(clinit, block));
 516 
 517             if (!clinitTAs.isEmpty())
 518                 clinit.appendUniqueTypeAttributes(clinitTAs.toList());

 541 
 542     /** Check a constant value and report if it is a string that is
 543      *  too large.
 544      */
 545     private void checkStringConstant(DiagnosticPosition pos, Object constValue) {
 546         if (nerrs != 0 || // only complain about a long string once
 547             constValue == null ||
 548             !(constValue instanceof String str) ||
 549             str.length() < PoolWriter.MAX_STRING_LENGTH)
 550             return;
 551         log.error(pos, Errors.LimitString);
 552         nerrs++;
 553     }
 554 
 555     /** Insert instance initializer code into constructors prior to the super() call.
 556      *  @param md        The tree potentially representing a
 557      *                   constructor's definition.
 558      *  @param initCode  The list of instance initializer statements.
 559      *  @param initTAs  Type annotations from the initializer expression.
 560      */
 561     void normalizeMethod(JCMethodDecl md, List<JCStatement> initCode, List<JCStatement> initBlocks,  List<TypeCompound> initTAs) {
 562         if (TreeInfo.isConstructor(md) && TreeInfo.hasConstructorCall(md, names._super)) {
 563             // We are seeing a constructor that has a super() call.
 564             // Find the super() invocation and append the given initializer code.
 565             if (md.sym.owner.isValueClass() || md.sym.owner.hasStrict()) {
 566                 rewriteInitializersIfNeeded(md, initCode);
 567                 md.body.stats = initCode.appendList(md.body.stats);
 568                 TreeInfo.mapSuperCalls(md.body, supercall -> make.Block(0, initBlocks.prepend(supercall)));
 569             } else {
 570                 TreeInfo.mapSuperCalls(md.body, supercall -> make.Block(0, initCode.prepend(supercall)));
 571             }
 572 
 573             if (md.body.endpos == Position.NOPOS)
 574                 md.body.endpos = TreeInfo.endPos(md.body.stats.last());
 575 
 576             md.sym.appendUniqueTypeAttributes(initTAs);
 577         }
 578     }
 579 
 580     void rewriteInitializersIfNeeded(JCMethodDecl md, List<JCStatement> initCode) {
 581         if (lower.initializerOuterThis.containsKey(md.sym.owner)) {
 582             InitializerVisitor initializerVisitor = new InitializerVisitor(md, lower.initializerOuterThis.get(md.sym.owner));
 583             for (JCStatement init : initCode) {
 584                 initializerVisitor.scan(init);
 585             }
 586         }
 587     }
 588 
 589     public static class InitializerVisitor extends TreeScanner {
 590         JCMethodDecl md;
 591         Set<JCExpression> exprSet;
 592 
 593         public InitializerVisitor(JCMethodDecl md, Set<JCExpression> exprSet) {
 594             this.md = md;
 595             this.exprSet = exprSet;
 596         }
 597 
 598         @Override
 599         public void visitTree(JCTree tree) {}
 600 
 601         @Override
 602         public void visitIdent(JCIdent tree) {
 603             if (exprSet.contains(tree)) {
 604                 for (JCVariableDecl param: md.params) {
 605                     if (param.name == tree.name &&
 606                             ((param.sym.flags_field & (MANDATED | NOOUTERTHIS)) == (MANDATED | NOOUTERTHIS))) {
 607                         tree.sym = param.sym;
 608                     }
 609                 }
 610             }
 611         }
 612     }
 613 
 614 /* ************************************************************************
 615  * Traversal methods
 616  *************************************************************************/
 617 
 618     /** Visitor argument: The current environment.
 619      */
 620     Env<GenContext> env;
 621 
 622     /** Visitor argument: The expected type (prototype).
 623      */
 624     Type pt;
 625 
 626     /** Visitor result: The item representing the computed value.
 627      */
 628     Item result;
 629 
 630     /** Visitor method: generate code for a definition, catching and reporting
 631      *  any completion failures.
 632      *  @param tree    The definition to be visited.
 633      *  @param env     The environment current at the definition.

 978             // Count up extra parameters
 979             if (meth.isConstructor()) {
 980                 extras++;
 981                 if (meth.enclClass().isInner() &&
 982                     !meth.enclClass().isStatic()) {
 983                     extras++;
 984                 }
 985             } else if ((tree.mods.flags & STATIC) == 0) {
 986                 extras++;
 987             }
 988             //      System.err.println("Generating " + meth + " in " + meth.owner); //DEBUG
 989             if (Code.width(types.erasure(env.enclMethod.sym.type).getParameterTypes()) + extras >
 990                 ClassFile.MAX_PARAMETERS) {
 991                 log.error(tree.pos(), Errors.LimitParameters);
 992                 nerrs++;
 993             }
 994 
 995             else if (tree.body != null) {
 996                 // Create a new code structure and initialize it.
 997                 int startpcCrt = initCode(tree, env, fatcode);
 998                 Set<VarSymbol> prevUnsetFields = code.currentUnsetFields;
 999                 if (meth.isConstructor()) {
1000                     code.currentUnsetFields = unsetFieldsInfo.getUnsetFields(env.enclClass.sym, tree.body);
1001                     code.initialUnsetFields = unsetFieldsInfo.getUnsetFields(env.enclClass.sym, tree.body);
1002                 }
1003 
1004                 try {
1005                     genStat(tree.body, env);
1006                 } catch (CodeSizeOverflow e) {
1007                     // Failed due to code limit, try again with jsr/ret
1008                     startpcCrt = initCode(tree, env, fatcode);
1009                     genStat(tree.body, env);
1010                 } finally {
1011                     code.currentUnsetFields = prevUnsetFields;
1012                 }
1013 
1014                 if (code.state.stacksize != 0) {
1015                     log.error(tree.body.pos(), Errors.StackSimError(tree.sym));
1016                     throw new AssertionError();
1017                 }
1018 
1019                 // If last statement could complete normally, insert a
1020                 // return at the end.
1021                 if (code.isAlive()) {
1022                     code.statBegin(TreeInfo.endPos(tree.body));
1023                     if (env.enclMethod == null ||
1024                         env.enclMethod.sym.type.getReturnType().hasTag(VOID)) {
1025                         code.emitop0(return_);
1026                     } else {
1027                         // sometime dead code seems alive (4415991);
1028                         // generate a small loop instead
1029                         int startpc = code.entryPoint();
1030                         CondItem c = items.makeCondItem(goto_);
1031                         code.resolve(c.jumpTrue(), startpc);

1060 
1061                 // Fill in type annotation positions for exception parameters
1062                 code.fillExceptionParameterPositions();
1063             }
1064         }
1065 
1066         private int initCode(JCMethodDecl tree, Env<GenContext> env, boolean fatcode) {
1067             MethodSymbol meth = tree.sym;
1068 
1069             // Create a new code structure.
1070             meth.code = code = new Code(meth,
1071                                         fatcode,
1072                                         lineDebugInfo ? toplevel.lineMap : null,
1073                                         varDebugInfo,
1074                                         stackMap,
1075                                         debugCode,
1076                                         genCrt ? new CRTable(tree, env.toplevel.endPositions)
1077                                                : null,
1078                                         syms,
1079                                         types,
1080                                         poolWriter,
1081                                         generateAssertUnsetFieldsFrame);
1082             items = new Items(poolWriter, code, syms, types);
1083             if (code.debugCode) {
1084                 System.err.println(meth + " for body " + tree);
1085             }
1086 
1087             // If method is not static, create a new local variable address
1088             // for `this'.
1089             if ((tree.mods.flags & STATIC) == 0) {
1090                 Type selfType = meth.owner.type;
1091                 if (meth.isConstructor() && selfType != syms.objectType)
1092                     selfType = UninitializedType.uninitializedThis(selfType);
1093                 code.setDefined(
1094                         code.newLocal(
1095                             new VarSymbol(FINAL, names._this, selfType, meth.owner)));
1096             }
1097 
1098             // Mark all parameters as defined from the beginning of
1099             // the method.
1100             for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
1101                 checkDimension(l.head.pos(), l.head.sym.type);

1197     public void visitForLoop(JCForLoop tree) {
1198         int limit = code.nextreg;
1199         genStats(tree.init, env);
1200         genLoop(tree, tree.body, tree.cond, tree.step, true);
1201         code.endScopes(limit);
1202     }
1203     //where
1204         /** Generate code for a loop.
1205          *  @param loop       The tree representing the loop.
1206          *  @param body       The loop's body.
1207          *  @param cond       The loop's controlling condition.
1208          *  @param step       "Step" statements to be inserted at end of
1209          *                    each iteration.
1210          *  @param testFirst  True if the loop test belongs before the body.
1211          */
1212         private void genLoop(JCStatement loop,
1213                              JCStatement body,
1214                              JCExpression cond,
1215                              List<JCExpressionStatement> step,
1216                              boolean testFirst) {
1217             Set<VarSymbol> prevCodeUnsetFields = code.currentUnsetFields;
1218             try {
1219                 genLoopHelper(loop, body, cond, step, testFirst);
1220             } finally {
1221                 code.currentUnsetFields = prevCodeUnsetFields;
1222             }
1223         }
1224 
1225         private void genLoopHelper(JCStatement loop,
1226                              JCStatement body,
1227                              JCExpression cond,
1228                              List<JCExpressionStatement> step,
1229                              boolean testFirst) {
1230             Env<GenContext> loopEnv = env.dup(loop, new GenContext());
1231             int startpc = code.entryPoint();
1232             if (testFirst) { //while or for loop
1233                 CondItem c;
1234                 if (cond != null) {
1235                     code.statBegin(cond.pos);
1236                     Assert.check(code.isStatementStart());
1237                     c = genCond(TreeInfo.skipParens(cond), CRT_FLOW_CONTROLLER);
1238                 } else {
1239                     c = items.makeCondItem(goto_);
1240                 }
1241                 Chain loopDone = c.jumpFalse();
1242                 code.resolve(c.trueJumps);
1243                 Assert.check(code.isStatementStart());
1244                 genStat(body, loopEnv, CRT_STATEMENT | CRT_FLOW_TARGET);
1245                 code.resolve(loopEnv.info.cont);
1246                 genStats(step, loopEnv);
1247                 code.resolve(code.branch(goto_), startpc);
1248                 code.resolve(loopDone);
1249             } else {

1276     }
1277 
1278     public void visitLabelled(JCLabeledStatement tree) {
1279         Env<GenContext> localEnv = env.dup(tree, new GenContext());
1280         genStat(tree.body, localEnv, CRT_STATEMENT);
1281         Chain exit = localEnv.info.exit;
1282         if (exit != null) {
1283             code.resolve(exit);
1284             exit.state.defined.excludeFrom(code.nextreg);
1285         }
1286     }
1287 
1288     public void visitSwitch(JCSwitch tree) {
1289         handleSwitch(tree, tree.selector, tree.cases, tree.patternSwitch);
1290     }
1291 
1292     @Override
1293     public void visitSwitchExpression(JCSwitchExpression tree) {
1294         code.resolvePending();
1295         boolean prevInCondSwitchExpression = inCondSwitchExpression;
1296         Set<VarSymbol> prevCodeUnsetFields = code.currentUnsetFields;
1297         try {
1298             inCondSwitchExpression = false;
1299             doHandleSwitchExpression(tree);
1300         } finally {
1301             inCondSwitchExpression = prevInCondSwitchExpression;
1302             code.currentUnsetFields = prevCodeUnsetFields;
1303         }
1304         result = items.makeStackItem(pt);
1305     }
1306 
1307     private void doHandleSwitchExpression(JCSwitchExpression tree) {
1308         List<LocalItem> prevStackBeforeSwitchExpression = stackBeforeSwitchExpression;
1309         LocalItem prevSwitchResult = switchResult;
1310         int limit = code.nextreg;
1311         try {
1312             stackBeforeSwitchExpression = List.nil();
1313             switchResult = null;
1314             if (hasTry(tree)) {
1315                 //if the switch expression contains try-catch, the catch handlers need to have
1316                 //an empty stack. So stash whole stack to local variables, and restore it before
1317                 //breaks:
1318                 while (code.state.stacksize > 0) {
1319                     Type type = code.state.peek();
1320                     Name varName = names.fromString(target.syntheticNameChar() +
1321                                                     "stack" +
1322                                                     target.syntheticNameChar() +

1358                     hasTry = true;
1359                 }
1360 
1361                 @Override
1362                 public void visitClassDef(JCClassDecl tree) {
1363                 }
1364 
1365                 @Override
1366                 public void visitLambda(JCLambda tree) {
1367                 }
1368             };
1369 
1370             HasTryScanner hasTryScanner = new HasTryScanner();
1371 
1372             hasTryScanner.scan(tree);
1373             return hasTryScanner.hasTry;
1374         }
1375 
1376     private void handleSwitch(JCTree swtch, JCExpression selector, List<JCCase> cases,
1377                               boolean patternSwitch) {
1378         Set<VarSymbol> prevCodeUnsetFields = code.currentUnsetFields;
1379         try {
1380             handleSwitchHelper(swtch, selector, cases, patternSwitch);
1381         } finally {
1382             code.currentUnsetFields = prevCodeUnsetFields;
1383         }
1384     }
1385 
1386     void handleSwitchHelper(JCTree swtch, JCExpression selector, List<JCCase> cases,
1387                       boolean patternSwitch) {
1388         int limit = code.nextreg;
1389         Assert.check(!selector.type.hasTag(CLASS));
1390         int switchStart = patternSwitch ? code.entryPoint() : -1;
1391         int startpcCrt = genCrt ? code.curCP() : 0;
1392         Assert.check(code.isStatementStart());
1393         Item sel = genExpr(selector, syms.intType);
1394         if (cases.isEmpty()) {
1395             // We are seeing:  switch <sel> {}
1396             sel.load().drop();
1397             if (genCrt)
1398                 code.crt.put(TreeInfo.skipParens(selector),
1399                         CRT_FLOW_CONTROLLER, startpcCrt, code.curCP());
1400         } else {
1401             // We are seeing a nonempty switch.
1402             sel.load();
1403             if (genCrt)
1404                 code.crt.put(TreeInfo.skipParens(selector),
1405                         CRT_FLOW_CONTROLLER, startpcCrt, code.curCP());
1406             Env<GenContext> switchEnv = env.dup(swtch, new GenContext());
1407             switchEnv.info.isSwitch = true;
1408 
1409             // Compute number of labels and minimum and maximum label values.
1410             // For each case, store its label in an array.
1411             int lo = Integer.MAX_VALUE;  // minimum label.
1412             int hi = Integer.MIN_VALUE;  // maximum label.
1413             int nlabels = 0;               // number of labels.
1414 
1415             int[] labels = new int[cases.length()];  // the label array.
1416             int defaultIndex = -1;     // the index of the default clause.
1417 
1418             List<JCCase> l = cases;
1419             for (int i = 0; i < labels.length; i++) {
1420                 if (l.head.labels.head instanceof JCConstantCaseLabel constLabel) {
1421                     Assert.check(l.head.labels.size() == 1);
1422                     int val = ((Number) constLabel.expr.type.constValue()).intValue();
1423                     labels[i] = val;
1424                     if (val < lo) lo = val;
1425                     if (hi < val) hi = val;
1426                     nlabels++;
1427                 } else {
1428                     Assert.check(defaultIndex == -1);
1429                     defaultIndex = i;
1430                 }
1431                 l = l.tail;
1432             }
1433 
1434             // Determine whether to issue a tableswitch or a lookupswitch
1435             // instruction.
1436             long table_space_cost = 4 + ((long) hi - lo + 1); // words
1437             long table_time_cost = 3; // comparisons
1438             long lookup_space_cost = 3 + 2 * (long) nlabels;
1439             long lookup_time_cost = nlabels;
1440             int opcode =
1441                     nlabels > 0 &&
1442                             table_space_cost + 3 * table_time_cost <=
1443                                     lookup_space_cost + 3 * lookup_time_cost
1444                             ?
1445                             tableswitch : lookupswitch;
1446 
1447             int startpc = code.curCP();    // the position of the selector operation
1448             code.emitop0(opcode);
1449             code.align(4);
1450             int tableBase = code.curCP();  // the start of the jump table
1451             int[] offsets = null;          // a table of offsets for a lookupswitch
1452             code.emit4(-1);                // leave space for default offset
1453             if (opcode == tableswitch) {
1454                 code.emit4(lo);            // minimum label
1455                 code.emit4(hi);            // maximum label
1456                 for (long i = lo; i <= hi; i++) {  // leave space for jump table
1457                     code.emit4(-1);
1458                 }
1459             } else {
1460                 code.emit4(nlabels);    // number of labels
1461                 for (int i = 0; i < nlabels; i++) {
1462                     code.emit4(-1); code.emit4(-1); // leave space for lookup table
1463                 }
1464                 offsets = new int[labels.length];
1465             }
1466             Code.State stateSwitch = code.state.dup();
1467             code.markDead();
1468 
1469             // For each case do:
1470             l = cases;
1471             for (int i = 0; i < labels.length; i++) {
1472                 JCCase c = l.head;
1473                 l = l.tail;
1474 
1475                 int pc = code.entryPoint(stateSwitch);
1476                 // Insert offset directly into code or else into the
1477                 // offsets table.
1478                 if (i != defaultIndex) {
1479                     if (opcode == tableswitch) {
1480                         code.put4(
1481                                 tableBase + 4 * (labels[i] - lo + 3),
1482                                 pc - startpc);
1483                     } else {
1484                         offsets[i] = pc - startpc;
1485                     }
1486                 } else {
1487                     code.put4(tableBase, pc - startpc);
1488                 }
1489 
1490                 // Generate code for the statements in this case.
1491                 genStats(c.stats, switchEnv, CRT_FLOW_TARGET);
1492             }
1493 
1494             if (switchEnv.info.cont != null) {
1495                 Assert.check(patternSwitch);
1496                 code.resolve(switchEnv.info.cont, switchStart);
1497             }
1498 
1499             // Resolve all breaks.
1500             Chain exit = switchEnv.info.exit;
1501             if  (exit != null) {
1502                 code.resolve(exit);

1516                     if (code.get4(t) == -1)
1517                         code.put4(t, defaultOffset);
1518                 }
1519             } else {
1520                 // Sort non-default offsets and copy into lookup table.
1521                 if (defaultIndex >= 0)
1522                     for (int i = defaultIndex; i < labels.length - 1; i++) {
1523                         labels[i] = labels[i+1];
1524                         offsets[i] = offsets[i+1];
1525                     }
1526                 if (nlabels > 0)
1527                     qsort2(labels, offsets, 0, nlabels - 1);
1528                 for (int i = 0; i < nlabels; i++) {
1529                     int caseidx = tableBase + 8 * (i + 1);
1530                     code.put4(caseidx, labels[i]);
1531                     code.put4(caseidx + 4, offsets[i]);
1532                 }
1533             }
1534 
1535             if (swtch instanceof JCSwitchExpression) {
1536                 // Emit line position for the end of a switch expression
1537                 code.statBegin(TreeInfo.endPos(swtch));
1538             }
1539         }
1540         code.endScopes(limit);
1541     }
1542 //where
1543         /** Sort (int) arrays of keys and values
1544          */
1545        static void qsort2(int[] keys, int[] values, int lo, int hi) {
1546             int i = lo;
1547             int j = hi;
1548             int pivot = keys[(i+j)/2];
1549             do {
1550                 while (keys[i] < pivot) i++;
1551                 while (pivot < keys[j]) j--;
1552                 if (i <= j) {
1553                     int temp1 = keys[i];
1554                     keys[i] = keys[j];
1555                     keys[j] = temp1;
1556                     int temp2 = values[i];
1557                     values[i] = values[j];

1620             @Override
1621             void afterBody() {
1622                 if (tree.finalizer != null && (tree.finalizer.flags & BODY_ONLY_FINALIZE) != 0) {
1623                     //for body-only finally, remove the GenFinalizer after try body
1624                     //so that the finally is not generated to catch bodies:
1625                     tryEnv.info.finalize = null;
1626                 }
1627             }
1628 
1629         };
1630         tryEnv.info.gaps = new ListBuffer<>();
1631         genTry(tree.body, tree.catchers, tryEnv);
1632     }
1633     //where
1634         /** Generate code for a try or synchronized statement
1635          *  @param body      The body of the try or synchronized statement.
1636          *  @param catchers  The list of catch clauses.
1637          *  @param env       The current environment of the body.
1638          */
1639         void genTry(JCTree body, List<JCCatch> catchers, Env<GenContext> env) {
1640             Set<VarSymbol> prevCodeUnsetFields = code.currentUnsetFields;
1641             try {
1642                 genTryHelper(body, catchers, env);
1643             } finally {
1644                 code.currentUnsetFields = prevCodeUnsetFields;
1645             }
1646         }
1647 
1648         void genTryHelper(JCTree body, List<JCCatch> catchers, Env<GenContext> env) {
1649             int limit = code.nextreg;
1650             int startpc = code.curCP();
1651             Code.State stateTry = code.state.dup();
1652             genStat(body, env, CRT_BLOCK);
1653             int endpc = code.curCP();
1654             List<Integer> gaps = env.info.gaps.toList();
1655             code.statBegin(TreeInfo.endPos(body));
1656             genFinalizer(env);
1657             code.statBegin(TreeInfo.endPos(env.tree));
1658             Chain exitChain;
1659             boolean actualTry = env.tree.hasTag(TRY);
1660             if (startpc == endpc && actualTry) {
1661                 exitChain = code.branch(dontgoto);
1662             } else {
1663                 exitChain = code.branch(goto_);
1664             }
1665             endFinalizerGap(env);
1666             env.info.finalize.afterBody();
1667             boolean hasFinalizer =
1668                     env.info.finalize != null &&
1669                             env.info.finalize.hasFinalizer();
1670             if (startpc != endpc) for (List<JCCatch> l = catchers; l.nonEmpty(); l = l.tail) {
1671                 // start off with exception on stack
1672                 code.entryPoint(stateTry, l.head.param.sym.type);
1673                 genCatch(l.head, env, startpc, endpc, gaps);
1674                 genFinalizer(env);
1675                 if (hasFinalizer || l.tail.nonEmpty()) {
1676                     code.statBegin(TreeInfo.endPos(env.tree));
1677                     exitChain = Code.mergeChains(exitChain,
1678                             code.branch(goto_));
1679                 }
1680                 endFinalizerGap(env);
1681             }
1682             if (hasFinalizer && (startpc != endpc || !actualTry)) {
1683                 // Create a new register segment to avoid allocating
1684                 // the same variables in finalizers and other statements.
1685                 code.newRegSegment();
1686 
1687                 // Add a catch-all clause.
1688 
1689                 // start off with exception on stack
1690                 int catchallpc = code.entryPoint(stateTry, syms.throwableType);
1691 
1692                 // Register all exception ranges for catch all clause.
1693                 // The range of the catch all clause is from the beginning
1694                 // of the try or synchronized block until the present
1695                 // code pointer excluding all gaps in the current
1696                 // environment's GenContext.
1697                 int startseg = startpc;
1698                 while (env.info.gaps.nonEmpty()) {
1699                     int endseg = env.info.gaps.next().intValue();
1700                     registerCatch(body.pos(), startseg, endseg,
1701                             catchallpc, 0);
1702                     startseg = env.info.gaps.next().intValue();
1703                 }
1704                 code.statBegin(TreeInfo.finalizerPos(env.tree, PosKind.FIRST_STAT_POS));
1705                 code.markStatBegin();
1706 
1707                 Item excVar = makeTemp(syms.throwableType);
1708                 excVar.store();
1709                 genFinalizer(env);
1710                 code.resolvePending();
1711                 code.statBegin(TreeInfo.finalizerPos(env.tree, PosKind.END_POS));
1712                 code.markStatBegin();
1713 
1714                 excVar.load();
1715                 registerCatch(body.pos(), startseg,
1716                         env.info.gaps.next().intValue(),
1717                         catchallpc, 0);
1718                 code.emitop0(athrow);
1719                 code.markDead();
1720 
1721                 // If there are jsr's to this finalizer, ...
1722                 if (env.info.cont != null) {
1723                     // Resolve all jsr's.
1724                     code.resolve(env.info.cont);
1725 
1726                     // Mark statement line number
1727                     code.statBegin(TreeInfo.finalizerPos(env.tree, PosKind.FIRST_STAT_POS));
1728                     code.markStatBegin();
1729 
1730                     // Save return address.
1731                     LocalItem retVar = makeTemp(syms.throwableType);
1732                     retVar.store();
1733 
1734                     // Generate finalizer code.
1735                     env.info.finalize.genLast();
1736 
1737                     // Return.

1840         /** Register a catch clause in the "Exceptions" code-attribute.
1841          */
1842         void registerCatch(DiagnosticPosition pos,
1843                            int startpc, int endpc,
1844                            int handler_pc, int catch_type) {
1845             char startpc1 = (char)startpc;
1846             char endpc1 = (char)endpc;
1847             char handler_pc1 = (char)handler_pc;
1848             if (startpc1 == startpc &&
1849                 endpc1 == endpc &&
1850                 handler_pc1 == handler_pc) {
1851                 code.addCatch(startpc1, endpc1, handler_pc1,
1852                               (char)catch_type);
1853             } else {
1854                 log.error(pos, Errors.LimitCodeTooLargeForTryStmt);
1855                 nerrs++;
1856             }
1857         }
1858 
1859     public void visitIf(JCIf tree) {
1860         Set<VarSymbol> prevCodeUnsetFields = code.currentUnsetFields;
1861         try {
1862             visitIfHelper(tree);
1863         } finally {
1864             code.currentUnsetFields = prevCodeUnsetFields;
1865         }
1866     }
1867 
1868     public void visitIfHelper(JCIf tree) {
1869         int limit = code.nextreg;
1870         Chain thenExit = null;
1871         Assert.check(code.isStatementStart());
1872         CondItem c = genCond(TreeInfo.skipParens(tree.cond),
1873                 CRT_FLOW_CONTROLLER);
1874         Chain elseChain = c.jumpFalse();
1875         Assert.check(code.isStatementStart());
1876         if (!c.isFalse()) {
1877             code.resolve(c.trueJumps);
1878             genStat(tree.thenpart, env, CRT_STATEMENT | CRT_FLOW_TARGET);
1879             thenExit = code.branch(goto_);
1880         }
1881         if (elseChain != null) {
1882             code.resolve(elseChain);
1883             if (tree.elsepart != null) {
1884                 genStat(tree.elsepart, env,CRT_STATEMENT | CRT_FLOW_TARGET);
1885             }
1886         }
1887         code.resolve(thenExit);
1888         code.endScopes(limit);
1889         Assert.check(code.isStatementStart());
1890     }
1891 
1892     public void visitExec(JCExpressionStatement tree) {
1893         // Optimize x++ to ++x and x-- to --x.

2180                 nerrs++;
2181             }
2182             int elemcode = Code.arraycode(elemtype);
2183             if (elemcode == 0 || (elemcode == 1 && ndims == 1)) {
2184                 code.emitAnewarray(makeRef(pos, elemtype), type);
2185             } else if (elemcode == 1) {
2186                 code.emitMultianewarray(ndims, makeRef(pos, type), type);
2187             } else {
2188                 code.emitNewarray(elemcode, type);
2189             }
2190             return items.makeStackItem(type);
2191         }
2192 
2193     public void visitParens(JCParens tree) {
2194         result = genExpr(tree.expr, tree.expr.type);
2195     }
2196 
2197     public void visitAssign(JCAssign tree) {
2198         Item l = genExpr(tree.lhs, tree.lhs.type);
2199         genExpr(tree.rhs, tree.lhs.type).load();
2200         Set<VarSymbol> tmpUnsetSymbols = unsetFieldsInfo.getUnsetFields(env.enclClass.sym, tree);
2201         code.currentUnsetFields = tmpUnsetSymbols != null ? tmpUnsetSymbols : code.currentUnsetFields;
2202         if (tree.rhs.type.hasTag(BOT)) {
2203             /* This is just a case of widening reference conversion that per 5.1.5 simply calls
2204                for "regarding a reference as having some other type in a manner that can be proved
2205                correct at compile time."
2206             */
2207             code.state.forceStackTop(tree.lhs.type);
2208         }
2209         result = items.makeAssignItem(l);
2210     }
2211 
2212     public void visitAssignop(JCAssignOp tree) {
2213         OperatorSymbol operator = tree.operator;
2214         Item l;
2215         if (operator.opcode == string_add) {
2216             l = concat.makeConcat(tree);
2217         } else {
2218             // Generate code for first expression
2219             l = genExpr(tree.lhs, tree.lhs.type);
2220 
2221             // If we have an increment of -32768 to +32767 of a local

2460             items.makeThisItem().load();
2461             sym = binaryQualifier(sym, env.enclClass.type);
2462             result = items.makeMemberItem(sym, nonVirtualForPrivateAccess(sym));
2463         }
2464     }
2465 
2466     //where
2467     private boolean nonVirtualForPrivateAccess(Symbol sym) {
2468         boolean useVirtual = target.hasVirtualPrivateInvoke() &&
2469                              !disableVirtualizedPrivateInvoke;
2470         return !useVirtual && ((sym.flags() & PRIVATE) != 0);
2471     }
2472 
2473     public void visitSelect(JCFieldAccess tree) {
2474         Symbol sym = tree.sym;
2475 
2476         if (tree.name == names._class) {
2477             code.emitLdc((LoadableConstant)checkDimension(tree.pos(), tree.selected.type));
2478             result = items.makeStackItem(pt);
2479             return;
2480         }
2481 
2482         Symbol ssym = TreeInfo.symbol(tree.selected);
2483 
2484         // Are we selecting via super?
2485         boolean selectSuper =
2486             ssym != null && (ssym.kind == TYP || ssym.name == names._super);
2487 
2488         // Are we accessing a member of the superclass in an access method
2489         // resulting from a qualified super?
2490         boolean accessSuper = isAccessSuper(env.enclMethod);
2491 
2492         Item base = (selectSuper)
2493             ? items.makeSuperItem()
2494             : genExpr(tree.selected, tree.selected.type);
2495 
2496         if (sym.kind == VAR && ((VarSymbol) sym).getConstValue() != null) {
2497             // We are seeing a variable that is constant but its selecting
2498             // expression is not.
2499             if ((sym.flags() & STATIC) != 0) {
2500                 if (!selectSuper && (ssym == null || ssym.kind != TYP))
< prev index next >