< prev index next >

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

Print this page

  61  *  <p><b>This is NOT part of any supported API.
  62  *  If you write code that depends on this, you do so at your own risk.
  63  *  This code and its internal interfaces are subject to change or
  64  *  deletion without notice.</b>
  65  */
  66 public class Gen extends JCTree.Visitor {
  67     protected static final Context.Key<Gen> genKey = new Context.Key<>();
  68 
  69     private final Log log;
  70     private final Symtab syms;
  71     private final Check chk;
  72     private final Resolve rs;
  73     private final TreeMaker make;
  74     private final Names names;
  75     private final Target target;
  76     private final String accessDollar;
  77     private final Types types;
  78     private final Lower lower;
  79     private final Annotate annotate;
  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.bracePos = 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.bracePos == Position.NOPOS)
 557                 md.body.bracePos = 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.

 939             // Count up extra parameters
 940             if (meth.isConstructor()) {
 941                 extras++;
 942                 if (meth.enclClass().isInner() &&
 943                     !meth.enclClass().isStatic()) {
 944                     extras++;
 945                 }
 946             } else if ((tree.mods.flags & STATIC) == 0) {
 947                 extras++;
 948             }
 949             //      System.err.println("Generating " + meth + " in " + meth.owner); //DEBUG
 950             if (Code.width(types.erasure(env.enclMethod.sym.type).getParameterTypes()) + extras >
 951                 ClassFile.MAX_PARAMETERS) {
 952                 log.error(tree.pos(), Errors.LimitParameters);
 953                 nerrs++;
 954             }
 955 
 956             else if (tree.body != null) {
 957                 // Create a new code structure and initialize it.
 958                 int startpcCrt = initCode(tree, env, fatcode);





 959 
 960                 try {
 961                     genStat(tree.body, env);
 962                 } catch (CodeSizeOverflow e) {
 963                     // Failed due to code limit, try again with jsr/ret
 964                     startpcCrt = initCode(tree, env, fatcode);
 965                     genStat(tree.body, env);


 966                 }
 967 
 968                 if (code.state.stacksize != 0) {
 969                     log.error(tree.body.pos(), Errors.StackSimError(tree.sym));
 970                     throw new AssertionError();
 971                 }
 972 
 973                 // If last statement could complete normally, insert a
 974                 // return at the end.
 975                 if (code.isAlive()) {
 976                     code.statBegin(TreeInfo.endPos(tree.body));
 977                     if (env.enclMethod == null ||
 978                         env.enclMethod.sym.type.getReturnType().hasTag(VOID)) {
 979                         code.emitop0(return_);
 980                     } else {
 981                         // sometime dead code seems alive (4415991);
 982                         // generate a small loop instead
 983                         int startpc = code.entryPoint();
 984                         CondItem c = items.makeCondItem(goto_);
 985                         code.resolve(c.jumpTrue(), startpc);

1014 
1015                 // Fill in type annotation positions for exception parameters
1016                 code.fillExceptionParameterPositions();
1017             }
1018         }
1019 
1020         private int initCode(JCMethodDecl tree, Env<GenContext> env, boolean fatcode) {
1021             MethodSymbol meth = tree.sym;
1022 
1023             // Create a new code structure.
1024             meth.code = code = new Code(meth,
1025                                         fatcode,
1026                                         lineDebugInfo ? toplevel.lineMap : null,
1027                                         varDebugInfo,
1028                                         stackMap,
1029                                         debugCode,
1030                                         genCrt ? new CRTable(tree, env.toplevel.endPositions)
1031                                                : null,
1032                                         syms,
1033                                         types,
1034                                         poolWriter);

1035             items = new Items(poolWriter, code, syms, types);
1036             if (code.debugCode) {
1037                 System.err.println(meth + " for body " + tree);
1038             }
1039 
1040             // If method is not static, create a new local variable address
1041             // for `this'.
1042             if ((tree.mods.flags & STATIC) == 0) {
1043                 Type selfType = meth.owner.type;
1044                 if (meth.isConstructor() && selfType != syms.objectType)
1045                     selfType = UninitializedType.uninitializedThis(selfType);
1046                 code.setDefined(
1047                         code.newLocal(
1048                             new VarSymbol(FINAL, names._this, selfType, meth.owner)));
1049             }
1050 
1051             // Mark all parameters as defined from the beginning of
1052             // the method.
1053             for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
1054                 checkDimension(l.head.pos(), l.head.sym.type);

1150     public void visitForLoop(JCForLoop tree) {
1151         int limit = code.nextreg;
1152         genStats(tree.init, env);
1153         genLoop(tree, tree.body, tree.cond, tree.step, true);
1154         code.endScopes(limit);
1155     }
1156     //where
1157         /** Generate code for a loop.
1158          *  @param loop       The tree representing the loop.
1159          *  @param body       The loop's body.
1160          *  @param cond       The loop's controlling condition.
1161          *  @param step       "Step" statements to be inserted at end of
1162          *                    each iteration.
1163          *  @param testFirst  True if the loop test belongs before the body.
1164          */
1165         private void genLoop(JCStatement loop,
1166                              JCStatement body,
1167                              JCExpression cond,
1168                              List<JCExpressionStatement> step,
1169                              boolean testFirst) {













1170             Env<GenContext> loopEnv = env.dup(loop, new GenContext());
1171             int startpc = code.entryPoint();
1172             if (testFirst) { //while or for loop
1173                 CondItem c;
1174                 if (cond != null) {
1175                     code.statBegin(cond.pos);
1176                     Assert.check(code.isStatementStart());
1177                     c = genCond(TreeInfo.skipParens(cond), CRT_FLOW_CONTROLLER);
1178                 } else {
1179                     c = items.makeCondItem(goto_);
1180                 }
1181                 Chain loopDone = c.jumpFalse();
1182                 code.resolve(c.trueJumps);
1183                 Assert.check(code.isStatementStart());
1184                 genStat(body, loopEnv, CRT_STATEMENT | CRT_FLOW_TARGET);
1185                 code.resolve(loopEnv.info.cont);
1186                 genStats(step, loopEnv);
1187                 code.resolve(code.branch(goto_), startpc);
1188                 code.resolve(loopDone);
1189             } else {

1208         }
1209 
1210     public void visitForeachLoop(JCEnhancedForLoop tree) {
1211         throw new AssertionError(); // should have been removed by Lower.
1212     }
1213 
1214     public void visitLabelled(JCLabeledStatement tree) {
1215         Env<GenContext> localEnv = env.dup(tree, new GenContext());
1216         genStat(tree.body, localEnv, CRT_STATEMENT);
1217         code.resolve(localEnv.info.exit);
1218     }
1219 
1220     public void visitSwitch(JCSwitch tree) {
1221         handleSwitch(tree, tree.selector, tree.cases, tree.patternSwitch);
1222     }
1223 
1224     @Override
1225     public void visitSwitchExpression(JCSwitchExpression tree) {
1226         code.resolvePending();
1227         boolean prevInCondSwitchExpression = inCondSwitchExpression;

1228         try {
1229             inCondSwitchExpression = false;
1230             doHandleSwitchExpression(tree);
1231         } finally {
1232             inCondSwitchExpression = prevInCondSwitchExpression;

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

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










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

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.

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


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

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

  61  *  <p><b>This is NOT part of any supported API.
  62  *  If you write code that depends on this, you do so at your own risk.
  63  *  This code and its internal interfaces are subject to change or
  64  *  deletion without notice.</b>
  65  */
  66 public class Gen extends JCTree.Visitor {
  67     protected static final Context.Key<Gen> genKey = new Context.Key<>();
  68 
  69     private final Log log;
  70     private final Symtab syms;
  71     private final Check chk;
  72     private final Resolve rs;
  73     private final TreeMaker make;
  74     private final Names names;
  75     private final Target target;
  76     private final String accessDollar;
  77     private final Types types;
  78     private final Lower lower;
  79     private final Annotate annotate;
  80     private final StringConcat concat;
  81     private final LocalProxyVarsGen localProxyVarsGen;
  82 
  83     /** Format of stackmap tables to be generated. */
  84     private final Code.StackMapFormat stackMap;
  85 
  86     /** A type that serves as the expected type for all method expressions.
  87      */
  88     private final Type methodType;
  89 
  90     public static Gen instance(Context context) {
  91         Gen instance = context.get(genKey);
  92         if (instance == null)
  93             instance = new Gen(context);
  94         return instance;
  95     }
  96 
  97     /** Constant pool writer, set by genClass.
  98      */
  99     final PoolWriter poolWriter;
 100 
 101     private final UnsetFieldsInfo unsetFieldsInfo;
 102 
 103     @SuppressWarnings("this-escape")
 104     protected Gen(Context context) {
 105         context.put(genKey, this);
 106 
 107         names = Names.instance(context);
 108         log = Log.instance(context);
 109         syms = Symtab.instance(context);
 110         chk = Check.instance(context);
 111         rs = Resolve.instance(context);
 112         make = TreeMaker.instance(context);
 113         target = Target.instance(context);
 114         types = Types.instance(context);
 115         concat = StringConcat.instance(context);
 116         localProxyVarsGen = LocalProxyVarsGen.instance(context);
 117 
 118         methodType = new MethodType(null, null, null, syms.methodClass);
 119         accessDollar = "access" + target.syntheticNameChar();
 120         lower = Lower.instance(context);
 121 
 122         Options options = Options.instance(context);
 123         lineDebugInfo =
 124             options.isUnset(G_CUSTOM) ||
 125             options.isSet(G_CUSTOM, "lines");
 126         varDebugInfo =
 127             options.isUnset(G_CUSTOM)
 128             ? options.isSet(G)
 129             : options.isSet(G_CUSTOM, "vars");
 130         genCrt = options.isSet(XJCOV);
 131         debugCode = options.isSet("debug.code");
 132         disableVirtualizedPrivateInvoke = options.isSet("disableVirtualizedPrivateInvoke");
 133         poolWriter = new PoolWriter(types, names);
 134         unsetFieldsInfo = UnsetFieldsInfo.instance(context);
 135 
 136         // ignore cldc because we cannot have both stackmap formats
 137         this.stackMap = StackMapFormat.JSR202;
 138         annotate = Annotate.instance(context);
 139         qualifiedSymbolCache = new HashMap<>();
 140         Preview preview = Preview.instance(context);
 141         Source source = Source.instance(context);
 142         allowValueClasses = (!preview.isPreview(Source.Feature.VALUE_CLASSES) || preview.isEnabled()) &&
 143                 Source.Feature.VALUE_CLASSES.allowedInSource(source);
 144     }
 145 
 146     /** Switches
 147      */
 148     private final boolean lineDebugInfo;
 149     private final boolean varDebugInfo;
 150     private final boolean genCrt;
 151     private final boolean debugCode;
 152     private boolean disableVirtualizedPrivateInvoke;
 153     private final boolean allowValueClasses;
 154 
 155     /** Code buffer, set by genMethod.
 156      */
 157     private Code code;
 158 
 159     /** Items structure, set by genMethod.
 160      */
 161     private Items items;
 162 
 163     /** Environment for symbol lookup, set by genClass
 164      */
 165     private Env<AttrContext> attrEnv;
 166 
 167     /** The top level tree.
 168      */
 169     private JCCompilationUnit toplevel;
 170 
 171     /** The number of code-gen errors in this class.
 172      */
 173     private int nerrs = 0;

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

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

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

1010             // Count up extra parameters
1011             if (meth.isConstructor()) {
1012                 extras++;
1013                 if (meth.enclClass().isInner() &&
1014                     !meth.enclClass().isStatic()) {
1015                     extras++;
1016                 }
1017             } else if ((tree.mods.flags & STATIC) == 0) {
1018                 extras++;
1019             }
1020             //      System.err.println("Generating " + meth + " in " + meth.owner); //DEBUG
1021             if (Code.width(types.erasure(env.enclMethod.sym.type).getParameterTypes()) + extras >
1022                 ClassFile.MAX_PARAMETERS) {
1023                 log.error(tree.pos(), Errors.LimitParameters);
1024                 nerrs++;
1025             }
1026 
1027             else if (tree.body != null) {
1028                 // Create a new code structure and initialize it.
1029                 int startpcCrt = initCode(tree, env, fatcode);
1030                 Set<VarSymbol> prevUnsetFields = code.currentUnsetFields;
1031                 if (meth.isConstructor()) {
1032                     code.currentUnsetFields = unsetFieldsInfo.getUnsetFields(env.enclClass.sym, tree.body);
1033                     code.initialUnsetFields = unsetFieldsInfo.getUnsetFields(env.enclClass.sym, tree.body);
1034                 }
1035 
1036                 try {
1037                     genStat(tree.body, env);
1038                 } catch (CodeSizeOverflow e) {
1039                     // Failed due to code limit, try again with jsr/ret
1040                     startpcCrt = initCode(tree, env, fatcode);
1041                     genStat(tree.body, env);
1042                 } finally {
1043                     code.currentUnsetFields = prevUnsetFields;
1044                 }
1045 
1046                 if (code.state.stacksize != 0) {
1047                     log.error(tree.body.pos(), Errors.StackSimError(tree.sym));
1048                     throw new AssertionError();
1049                 }
1050 
1051                 // If last statement could complete normally, insert a
1052                 // return at the end.
1053                 if (code.isAlive()) {
1054                     code.statBegin(TreeInfo.endPos(tree.body));
1055                     if (env.enclMethod == null ||
1056                         env.enclMethod.sym.type.getReturnType().hasTag(VOID)) {
1057                         code.emitop0(return_);
1058                     } else {
1059                         // sometime dead code seems alive (4415991);
1060                         // generate a small loop instead
1061                         int startpc = code.entryPoint();
1062                         CondItem c = items.makeCondItem(goto_);
1063                         code.resolve(c.jumpTrue(), startpc);

1092 
1093                 // Fill in type annotation positions for exception parameters
1094                 code.fillExceptionParameterPositions();
1095             }
1096         }
1097 
1098         private int initCode(JCMethodDecl tree, Env<GenContext> env, boolean fatcode) {
1099             MethodSymbol meth = tree.sym;
1100 
1101             // Create a new code structure.
1102             meth.code = code = new Code(meth,
1103                                         fatcode,
1104                                         lineDebugInfo ? toplevel.lineMap : null,
1105                                         varDebugInfo,
1106                                         stackMap,
1107                                         debugCode,
1108                                         genCrt ? new CRTable(tree, env.toplevel.endPositions)
1109                                                : null,
1110                                         syms,
1111                                         types,
1112                                         poolWriter,
1113                                         allowValueClasses);
1114             items = new Items(poolWriter, code, syms, types);
1115             if (code.debugCode) {
1116                 System.err.println(meth + " for body " + tree);
1117             }
1118 
1119             // If method is not static, create a new local variable address
1120             // for `this'.
1121             if ((tree.mods.flags & STATIC) == 0) {
1122                 Type selfType = meth.owner.type;
1123                 if (meth.isConstructor() && selfType != syms.objectType)
1124                     selfType = UninitializedType.uninitializedThis(selfType);
1125                 code.setDefined(
1126                         code.newLocal(
1127                             new VarSymbol(FINAL, names._this, selfType, meth.owner)));
1128             }
1129 
1130             // Mark all parameters as defined from the beginning of
1131             // the method.
1132             for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
1133                 checkDimension(l.head.pos(), l.head.sym.type);

1229     public void visitForLoop(JCForLoop tree) {
1230         int limit = code.nextreg;
1231         genStats(tree.init, env);
1232         genLoop(tree, tree.body, tree.cond, tree.step, true);
1233         code.endScopes(limit);
1234     }
1235     //where
1236         /** Generate code for a loop.
1237          *  @param loop       The tree representing the loop.
1238          *  @param body       The loop's body.
1239          *  @param cond       The loop's controlling condition.
1240          *  @param step       "Step" statements to be inserted at end of
1241          *                    each iteration.
1242          *  @param testFirst  True if the loop test belongs before the body.
1243          */
1244         private void genLoop(JCStatement loop,
1245                              JCStatement body,
1246                              JCExpression cond,
1247                              List<JCExpressionStatement> step,
1248                              boolean testFirst) {
1249             Set<VarSymbol> prevCodeUnsetFields = code.currentUnsetFields;
1250             try {
1251                 genLoopHelper(loop, body, cond, step, testFirst);
1252             } finally {
1253                 code.currentUnsetFields = prevCodeUnsetFields;
1254             }
1255         }
1256 
1257         private void genLoopHelper(JCStatement loop,
1258                              JCStatement body,
1259                              JCExpression cond,
1260                              List<JCExpressionStatement> step,
1261                              boolean testFirst) {
1262             Env<GenContext> loopEnv = env.dup(loop, new GenContext());
1263             int startpc = code.entryPoint();
1264             if (testFirst) { //while or for loop
1265                 CondItem c;
1266                 if (cond != null) {
1267                     code.statBegin(cond.pos);
1268                     Assert.check(code.isStatementStart());
1269                     c = genCond(TreeInfo.skipParens(cond), CRT_FLOW_CONTROLLER);
1270                 } else {
1271                     c = items.makeCondItem(goto_);
1272                 }
1273                 Chain loopDone = c.jumpFalse();
1274                 code.resolve(c.trueJumps);
1275                 Assert.check(code.isStatementStart());
1276                 genStat(body, loopEnv, CRT_STATEMENT | CRT_FLOW_TARGET);
1277                 code.resolve(loopEnv.info.cont);
1278                 genStats(step, loopEnv);
1279                 code.resolve(code.branch(goto_), startpc);
1280                 code.resolve(loopDone);
1281             } else {

1300         }
1301 
1302     public void visitForeachLoop(JCEnhancedForLoop tree) {
1303         throw new AssertionError(); // should have been removed by Lower.
1304     }
1305 
1306     public void visitLabelled(JCLabeledStatement tree) {
1307         Env<GenContext> localEnv = env.dup(tree, new GenContext());
1308         genStat(tree.body, localEnv, CRT_STATEMENT);
1309         code.resolve(localEnv.info.exit);
1310     }
1311 
1312     public void visitSwitch(JCSwitch tree) {
1313         handleSwitch(tree, tree.selector, tree.cases, tree.patternSwitch);
1314     }
1315 
1316     @Override
1317     public void visitSwitchExpression(JCSwitchExpression tree) {
1318         code.resolvePending();
1319         boolean prevInCondSwitchExpression = inCondSwitchExpression;
1320         Set<VarSymbol> prevCodeUnsetFields = code.currentUnsetFields;
1321         try {
1322             inCondSwitchExpression = false;
1323             doHandleSwitchExpression(tree);
1324         } finally {
1325             inCondSwitchExpression = prevInCondSwitchExpression;
1326             code.currentUnsetFields = prevCodeUnsetFields;
1327         }
1328         result = items.makeStackItem(pt);
1329     }
1330 
1331     private void doHandleSwitchExpression(JCSwitchExpression tree) {
1332         List<LocalItem> prevStackBeforeSwitchExpression = stackBeforeSwitchExpression;
1333         LocalItem prevSwitchResult = switchResult;
1334         int limit = code.nextreg;
1335         try {
1336             stackBeforeSwitchExpression = List.nil();
1337             switchResult = null;
1338             if (hasTry(tree)) {
1339                 //if the switch expression contains try-catch, the catch handlers need to have
1340                 //an empty stack. So stash whole stack to local variables, and restore it before
1341                 //breaks:
1342                 while (code.state.stacksize > 0) {
1343                     Type type = code.state.peek();
1344                     Name varName = names.fromString(target.syntheticNameChar() +
1345                                                     "stack" +
1346                                                     target.syntheticNameChar() +

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

1536                     if (code.get4(t) == -1)
1537                         code.put4(t, defaultOffset);
1538                 }
1539             } else {
1540                 // Sort non-default offsets and copy into lookup table.
1541                 if (defaultIndex >= 0)
1542                     for (int i = defaultIndex; i < labels.length - 1; i++) {
1543                         labels[i] = labels[i+1];
1544                         offsets[i] = offsets[i+1];
1545                     }
1546                 if (nlabels > 0)
1547                     qsort2(labels, offsets, 0, nlabels - 1);
1548                 for (int i = 0; i < nlabels; i++) {
1549                     int caseidx = tableBase + 8 * (i + 1);
1550                     code.put4(caseidx, labels[i]);
1551                     code.put4(caseidx + 4, offsets[i]);
1552                 }
1553             }
1554 
1555             if (swtch instanceof JCSwitchExpression) {
1556                 // Emit line position for the end of a switch expression
1557                 code.statBegin(TreeInfo.endPos(swtch));
1558             }
1559         }
1560         code.endScopes(limit);
1561     }
1562 //where
1563         /** Sort (int) arrays of keys and values
1564          */
1565        static void qsort2(int[] keys, int[] values, int lo, int hi) {
1566             int i = lo;
1567             int j = hi;
1568             int pivot = keys[(i+j)/2];
1569             do {
1570                 while (keys[i] < pivot) i++;
1571                 while (pivot < keys[j]) j--;
1572                 if (i <= j) {
1573                     int temp1 = keys[i];
1574                     keys[i] = keys[j];
1575                     keys[j] = temp1;
1576                     int temp2 = values[i];
1577                     values[i] = values[j];

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

1860         /** Register a catch clause in the "Exceptions" code-attribute.
1861          */
1862         void registerCatch(DiagnosticPosition pos,
1863                            int startpc, int endpc,
1864                            int handler_pc, int catch_type) {
1865             char startpc1 = (char)startpc;
1866             char endpc1 = (char)endpc;
1867             char handler_pc1 = (char)handler_pc;
1868             if (startpc1 == startpc &&
1869                 endpc1 == endpc &&
1870                 handler_pc1 == handler_pc) {
1871                 code.addCatch(startpc1, endpc1, handler_pc1,
1872                               (char)catch_type);
1873             } else {
1874                 log.error(pos, Errors.LimitCodeTooLargeForTryStmt);
1875                 nerrs++;
1876             }
1877         }
1878 
1879     public void visitIf(JCIf tree) {
1880         Set<VarSymbol> prevCodeUnsetFields = code.currentUnsetFields;
1881         try {
1882             visitIfHelper(tree);
1883         } finally {
1884             code.currentUnsetFields = prevCodeUnsetFields;
1885         }
1886     }
1887 
1888     public void visitIfHelper(JCIf tree) {
1889         int limit = code.nextreg;
1890         Chain thenExit = null;
1891         Assert.check(code.isStatementStart());
1892         CondItem c = genCond(TreeInfo.skipParens(tree.cond),
1893                 CRT_FLOW_CONTROLLER);
1894         Chain elseChain = c.jumpFalse();
1895         Assert.check(code.isStatementStart());
1896         if (!c.isFalse()) {
1897             code.resolve(c.trueJumps);
1898             genStat(tree.thenpart, env, CRT_STATEMENT | CRT_FLOW_TARGET);
1899             thenExit = code.branch(goto_);
1900         }
1901         if (elseChain != null) {
1902             code.resolve(elseChain);
1903             if (tree.elsepart != null) {
1904                 genStat(tree.elsepart, env,CRT_STATEMENT | CRT_FLOW_TARGET);
1905             }
1906         }
1907         code.resolve(thenExit);
1908         code.endScopes(limit);
1909         Assert.check(code.isStatementStart());
1910     }
1911 
1912     public void visitExec(JCExpressionStatement tree) {
1913         // Optimize x++ to ++x and x-- to --x.

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

2477             items.makeThisItem().load();
2478             sym = binaryQualifier(sym, env.enclClass.type);
2479             result = items.makeMemberItem(sym, nonVirtualForPrivateAccess(sym));
2480         }
2481     }
2482 
2483     //where
2484     private boolean nonVirtualForPrivateAccess(Symbol sym) {
2485         boolean useVirtual = target.hasVirtualPrivateInvoke() &&
2486                              !disableVirtualizedPrivateInvoke;
2487         return !useVirtual && ((sym.flags() & PRIVATE) != 0);
2488     }
2489 
2490     public void visitSelect(JCFieldAccess tree) {
2491         Symbol sym = tree.sym;
2492 
2493         if (tree.name == names._class) {
2494             code.emitLdc((LoadableConstant)checkDimension(tree.pos(), tree.selected.type));
2495             result = items.makeStackItem(pt);
2496             return;
2497         }
2498 
2499         Symbol ssym = TreeInfo.symbol(tree.selected);
2500 
2501         // Are we selecting via super?
2502         boolean selectSuper =
2503             ssym != null && (ssym.kind == TYP || ssym.name == names._super);
2504 
2505         // Are we accessing a member of the superclass in an access method
2506         // resulting from a qualified super?
2507         boolean accessSuper = isAccessSuper(env.enclMethod);
2508 
2509         Item base = (selectSuper)
2510             ? items.makeSuperItem()
2511             : genExpr(tree.selected, tree.selected.type);
2512 
2513         if (sym.kind == VAR && ((VarSymbol) sym).getConstValue() != null) {
2514             // We are seeing a variable that is constant but its selecting
2515             // expression is not.
2516             if ((sym.flags() & STATIC) != 0) {
2517                 if (!selectSuper && (ssym == null || ssym.kind != TYP))
< prev index next >