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
60 * <p><b>This is NOT part of any supported API.
61 * If you write code that depends on this, you do so at your own risk.
62 * This code and its internal interfaces are subject to change or
63 * deletion without notice.</b>
64 */
65 public class Gen extends JCTree.Visitor {
66 protected static final Context.Key<Gen> genKey = new Context.Key<>();
67
68 private final Log log;
69 private final Symtab syms;
70 private final Check chk;
71 private final Resolve rs;
72 private final TreeMaker make;
73 private final Names names;
74 private final Target target;
75 private final String accessDollar;
76 private final Types types;
77 private final Lower lower;
78 private final Annotate annotate;
79 private final StringConcat concat;
80
81 /** Format of stackmap tables to be generated. */
82 private final Code.StackMapFormat stackMap;
83
84 /** A type that serves as the expected type for all method expressions.
85 */
86 private final Type methodType;
87
88 public static Gen instance(Context context) {
89 Gen instance = context.get(genKey);
90 if (instance == null)
91 instance = new Gen(context);
92 return instance;
93 }
94
95 /** Constant pool writer, set by genClass.
96 */
97 final PoolWriter poolWriter;
98
99 @SuppressWarnings("this-escape")
100 protected Gen(Context context) {
101 context.put(genKey, this);
102
103 names = Names.instance(context);
104 log = Log.instance(context);
105 syms = Symtab.instance(context);
106 chk = Check.instance(context);
107 rs = Resolve.instance(context);
108 make = TreeMaker.instance(context);
109 target = Target.instance(context);
110 types = Types.instance(context);
111 concat = StringConcat.instance(context);
112
113 methodType = new MethodType(null, null, null, syms.methodClass);
114 accessDollar = "access" + target.syntheticNameChar();
115 lower = Lower.instance(context);
116
117 Options options = Options.instance(context);
118 lineDebugInfo =
119 options.isUnset(G_CUSTOM) ||
120 options.isSet(G_CUSTOM, "lines");
121 varDebugInfo =
122 options.isUnset(G_CUSTOM)
123 ? options.isSet(G)
124 : options.isSet(G_CUSTOM, "vars");
125 genCrt = options.isSet(XJCOV);
126 debugCode = options.isSet("debug.code");
127 disableVirtualizedPrivateInvoke = options.isSet("disableVirtualizedPrivateInvoke");
128 poolWriter = new PoolWriter(types, names);
129
130 // ignore cldc because we cannot have both stackmap formats
131 this.stackMap = StackMapFormat.JSR202;
132 annotate = Annotate.instance(context);
133 qualifiedSymbolCache = new HashMap<>();
134 }
135
136 /** Switches
137 */
138 private final boolean lineDebugInfo;
139 private final boolean varDebugInfo;
140 private final boolean genCrt;
141 private final boolean debugCode;
142 private boolean disableVirtualizedPrivateInvoke;
143
144 /** Code buffer, set by genMethod.
145 */
146 private Code code;
147
148 /** Items structure, set by genMethod.
149 */
150 private Items items;
151
152 /** Environment for symbol lookup, set by genClass
153 */
154 private Env<AttrContext> attrEnv;
155
156 /** The top level tree.
157 */
158 private JCCompilationUnit toplevel;
159
160 /** The number of code-gen errors in this class.
161 */
162 private int nerrs = 0;
401 boolean hasFinally(JCTree target, Env<GenContext> env) {
402 while (env.tree != target) {
403 if (env.tree.hasTag(TRY) && env.info.finalize.hasFinalizer())
404 return true;
405 env = env.next;
406 }
407 return false;
408 }
409
410 /* ************************************************************************
411 * Normalizing class-members.
412 *************************************************************************/
413
414 /** Distribute member initializer code into constructors and {@code <clinit>}
415 * method.
416 * @param defs The list of class member declarations.
417 * @param c The enclosing class.
418 */
419 List<JCTree> normalizeDefs(List<JCTree> defs, ClassSymbol c) {
420 ListBuffer<JCStatement> initCode = new ListBuffer<>();
421 ListBuffer<Attribute.TypeCompound> initTAs = new ListBuffer<>();
422 ListBuffer<JCStatement> clinitCode = new ListBuffer<>();
423 ListBuffer<Attribute.TypeCompound> clinitTAs = new ListBuffer<>();
424 ListBuffer<JCTree> methodDefs = new ListBuffer<>();
425 // Sort definitions into three listbuffers:
426 // - initCode for instance initializers
427 // - clinitCode for class initializers
428 // - methodDefs for method definitions
429 for (List<JCTree> l = defs; l.nonEmpty(); l = l.tail) {
430 JCTree def = l.head;
431 switch (def.getTag()) {
432 case BLOCK:
433 JCBlock block = (JCBlock)def;
434 if ((block.flags & STATIC) != 0)
435 clinitCode.append(block);
436 else if ((block.flags & SYNTHETIC) == 0)
437 initCode.append(block);
438 break;
439 case METHODDEF:
440 methodDefs.append(def);
441 break;
442 case VARDEF:
443 JCVariableDecl vdef = (JCVariableDecl) def;
444 VarSymbol sym = vdef.sym;
445 checkDimension(vdef.pos(), sym.type);
446 if (vdef.init != null) {
447 if ((sym.flags() & STATIC) == 0) {
448 // Always initialize instance variables.
449 JCStatement init = make.at(vdef.pos()).
450 Assignment(sym, vdef.init);
451 initCode.append(init);
452 init.endpos = vdef.endpos;
453 initTAs.addAll(getAndRemoveNonFieldTAs(sym));
454 } else if (sym.getConstValue() == null) {
455 // Initialize class (static) variables only if
456 // they are not compile-time constants.
457 JCStatement init = make.at(vdef.pos).
458 Assignment(sym, vdef.init);
459 clinitCode.append(init);
460 init.endpos = vdef.endpos;
461 clinitTAs.addAll(getAndRemoveNonFieldTAs(sym));
462 } else {
463 checkStringConstant(vdef.init.pos(), sym.getConstValue());
464 /* if the init contains a reference to an external class, add it to the
465 * constant's pool
466 */
467 vdef.init.accept(classReferenceVisitor);
468 }
469 }
470 break;
471 default:
472 Assert.error();
473 }
474 }
475 // Insert any instance initializers into all constructors.
476 if (initCode.length() != 0) {
477 List<JCStatement> inits = initCode.toList();
478 initTAs.addAll(c.getInitTypeAttributes());
479 List<Attribute.TypeCompound> initTAlist = initTAs.toList();
480 for (JCTree t : methodDefs) {
481 normalizeMethod((JCMethodDecl)t, inits, initTAlist);
482 }
483 }
484 // If there are class initializers, create a <clinit> method
485 // that contains them as its body.
486 if (clinitCode.length() != 0) {
487 MethodSymbol clinit = new MethodSymbol(
488 STATIC | (c.flags() & STRICTFP),
489 names.clinit,
490 new MethodType(
491 List.nil(), syms.voidType,
492 List.nil(), syms.methodClass),
493 c);
494 c.members().enter(clinit);
495 List<JCStatement> clinitStats = clinitCode.toList();
496 JCBlock block = make.at(clinitStats.head.pos()).Block(0, clinitStats);
497 block.bracePos = TreeInfo.endPos(clinitStats.last());
498 methodDefs.append(make.MethodDef(clinit, block));
499
500 if (!clinitTAs.isEmpty())
501 clinit.appendUniqueTypeAttributes(clinitTAs.toList());
524
525 /** Check a constant value and report if it is a string that is
526 * too large.
527 */
528 private void checkStringConstant(DiagnosticPosition pos, Object constValue) {
529 if (nerrs != 0 || // only complain about a long string once
530 constValue == null ||
531 !(constValue instanceof String str) ||
532 str.length() < PoolWriter.MAX_STRING_LENGTH)
533 return;
534 log.error(pos, Errors.LimitString);
535 nerrs++;
536 }
537
538 /** Insert instance initializer code into constructors prior to the super() call.
539 * @param md The tree potentially representing a
540 * constructor's definition.
541 * @param initCode The list of instance initializer statements.
542 * @param initTAs Type annotations from the initializer expression.
543 */
544 void normalizeMethod(JCMethodDecl md, List<JCStatement> initCode, List<TypeCompound> initTAs) {
545 if (TreeInfo.isConstructor(md) && TreeInfo.hasConstructorCall(md, names._super)) {
546 // We are seeing a constructor that has a super() call.
547 // Find the super() invocation and append the given initializer code.
548 TreeInfo.mapSuperCalls(md.body, supercall -> make.Block(0, initCode.prepend(supercall)));
549
550 if (md.body.bracePos == Position.NOPOS)
551 md.body.bracePos = TreeInfo.endPos(md.body.stats.last());
552
553 md.sym.appendUniqueTypeAttributes(initTAs);
554 }
555 }
556
557 /* ************************************************************************
558 * Traversal methods
559 *************************************************************************/
560
561 /** Visitor argument: The current environment.
562 */
563 Env<GenContext> env;
564
565 /** Visitor argument: The expected type (prototype).
566 */
567 Type pt;
568
569 /** Visitor result: The item representing the computed value.
570 */
571 Item result;
572
573 /** Visitor method: generate code for a definition, catching and reporting
574 * any completion failures.
575 * @param tree The definition to be visited.
576 * @param env The environment current at the definition.
933 // Count up extra parameters
934 if (meth.isConstructor()) {
935 extras++;
936 if (meth.enclClass().isInner() &&
937 !meth.enclClass().isStatic()) {
938 extras++;
939 }
940 } else if ((tree.mods.flags & STATIC) == 0) {
941 extras++;
942 }
943 // System.err.println("Generating " + meth + " in " + meth.owner); //DEBUG
944 if (Code.width(types.erasure(env.enclMethod.sym.type).getParameterTypes()) + extras >
945 ClassFile.MAX_PARAMETERS) {
946 log.error(tree.pos(), Errors.LimitParameters);
947 nerrs++;
948 }
949
950 else if (tree.body != null) {
951 // Create a new code structure and initialize it.
952 int startpcCrt = initCode(tree, env, fatcode);
953
954 try {
955 genStat(tree.body, env);
956 } catch (CodeSizeOverflow e) {
957 // Failed due to code limit, try again with jsr/ret
958 startpcCrt = initCode(tree, env, fatcode);
959 genStat(tree.body, env);
960 }
961
962 if (code.state.stacksize != 0) {
963 log.error(tree.body.pos(), Errors.StackSimError(tree.sym));
964 throw new AssertionError();
965 }
966
967 // If last statement could complete normally, insert a
968 // return at the end.
969 if (code.isAlive()) {
970 code.statBegin(TreeInfo.endPos(tree.body));
971 if (env.enclMethod == null ||
972 env.enclMethod.sym.type.getReturnType().hasTag(VOID)) {
973 code.emitop0(return_);
974 } else {
975 // sometime dead code seems alive (4415991);
976 // generate a small loop instead
977 int startpc = code.entryPoint();
978 CondItem c = items.makeCondItem(goto_);
979 code.resolve(c.jumpTrue(), startpc);
1007 code.compressCatchTable();
1008
1009 // Fill in type annotation positions for exception parameters
1010 code.fillExceptionParameterPositions();
1011 }
1012 }
1013
1014 private int initCode(JCMethodDecl tree, Env<GenContext> env, boolean fatcode) {
1015 MethodSymbol meth = tree.sym;
1016
1017 // Create a new code structure.
1018 meth.code = code = new Code(meth,
1019 fatcode,
1020 lineDebugInfo ? toplevel.lineMap : null,
1021 varDebugInfo,
1022 stackMap,
1023 debugCode,
1024 genCrt ? new CRTable(tree) : null,
1025 syms,
1026 types,
1027 poolWriter);
1028 items = new Items(poolWriter, code, syms, types);
1029 if (code.debugCode) {
1030 System.err.println(meth + " for body " + tree);
1031 }
1032
1033 // If method is not static, create a new local variable address
1034 // for `this'.
1035 if ((tree.mods.flags & STATIC) == 0) {
1036 Type selfType = meth.owner.type;
1037 if (meth.isConstructor() && selfType != syms.objectType)
1038 selfType = UninitializedType.uninitializedThis(selfType);
1039 code.setDefined(
1040 code.newLocal(
1041 new VarSymbol(FINAL, names._this, selfType, meth.owner)));
1042 }
1043
1044 // Mark all parameters as defined from the beginning of
1045 // the method.
1046 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
1047 checkDimension(l.head.pos(), l.head.sym.type);
1143 public void visitForLoop(JCForLoop tree) {
1144 int limit = code.nextreg;
1145 genStats(tree.init, env);
1146 genLoop(tree, tree.body, tree.cond, tree.step, true);
1147 code.endScopes(limit);
1148 }
1149 //where
1150 /** Generate code for a loop.
1151 * @param loop The tree representing the loop.
1152 * @param body The loop's body.
1153 * @param cond The loop's controlling condition.
1154 * @param step "Step" statements to be inserted at end of
1155 * each iteration.
1156 * @param testFirst True if the loop test belongs before the body.
1157 */
1158 private void genLoop(JCStatement loop,
1159 JCStatement body,
1160 JCExpression cond,
1161 List<JCExpressionStatement> step,
1162 boolean testFirst) {
1163 Env<GenContext> loopEnv = env.dup(loop, new GenContext());
1164 int startpc = code.entryPoint();
1165 if (testFirst) { //while or for loop
1166 CondItem c;
1167 if (cond != null) {
1168 code.statBegin(cond.pos);
1169 Assert.check(code.isStatementStart());
1170 c = genCond(TreeInfo.skipParens(cond), CRT_FLOW_CONTROLLER);
1171 } else {
1172 c = items.makeCondItem(goto_);
1173 }
1174 Chain loopDone = c.jumpFalse();
1175 code.resolve(c.trueJumps);
1176 Assert.check(code.isStatementStart());
1177 genStat(body, loopEnv, CRT_STATEMENT | CRT_FLOW_TARGET);
1178 code.resolve(loopEnv.info.cont);
1179 genStats(step, loopEnv);
1180 code.resolve(code.branch(goto_), startpc);
1181 code.resolve(loopDone);
1182 } else {
1201 }
1202
1203 public void visitForeachLoop(JCEnhancedForLoop tree) {
1204 throw new AssertionError(); // should have been removed by Lower.
1205 }
1206
1207 public void visitLabelled(JCLabeledStatement tree) {
1208 Env<GenContext> localEnv = env.dup(tree, new GenContext());
1209 genStat(tree.body, localEnv, CRT_STATEMENT);
1210 code.resolve(localEnv.info.exit);
1211 }
1212
1213 public void visitSwitch(JCSwitch tree) {
1214 handleSwitch(tree, tree.selector, tree.cases, tree.patternSwitch);
1215 }
1216
1217 @Override
1218 public void visitSwitchExpression(JCSwitchExpression tree) {
1219 code.resolvePending();
1220 boolean prevInCondSwitchExpression = inCondSwitchExpression;
1221 try {
1222 inCondSwitchExpression = false;
1223 doHandleSwitchExpression(tree);
1224 } finally {
1225 inCondSwitchExpression = prevInCondSwitchExpression;
1226 }
1227 result = items.makeStackItem(pt);
1228 }
1229
1230 private void doHandleSwitchExpression(JCSwitchExpression tree) {
1231 List<LocalItem> prevStackBeforeSwitchExpression = stackBeforeSwitchExpression;
1232 LocalItem prevSwitchResult = switchResult;
1233 int limit = code.nextreg;
1234 try {
1235 stackBeforeSwitchExpression = List.nil();
1236 switchResult = null;
1237 if (hasTry(tree)) {
1238 //if the switch expression contains try-catch, the catch handlers need to have
1239 //an empty stack. So stash whole stack to local variables, and restore it before
1240 //breaks:
1241 while (code.state.stacksize > 0) {
1242 Type type = code.state.peek();
1243 Name varName = names.fromString(target.syntheticNameChar() +
1244 "stack" +
1245 target.syntheticNameChar() +
1281 hasTry = true;
1282 }
1283
1284 @Override
1285 public void visitClassDef(JCClassDecl tree) {
1286 }
1287
1288 @Override
1289 public void visitLambda(JCLambda tree) {
1290 }
1291 };
1292
1293 HasTryScanner hasTryScanner = new HasTryScanner();
1294
1295 hasTryScanner.scan(tree);
1296 return hasTryScanner.hasTry;
1297 }
1298
1299 private void handleSwitch(JCTree swtch, JCExpression selector, List<JCCase> cases,
1300 boolean patternSwitch) {
1301 int limit = code.nextreg;
1302 Assert.check(!selector.type.hasTag(CLASS));
1303 int switchStart = patternSwitch ? code.entryPoint() : -1;
1304 int startpcCrt = genCrt ? code.curCP() : 0;
1305 Assert.check(code.isStatementStart());
1306 Item sel = genExpr(selector, syms.intType);
1307 if (cases.isEmpty()) {
1308 // We are seeing: switch <sel> {}
1309 sel.load().drop();
1310 if (genCrt)
1311 code.crt.put(TreeInfo.skipParens(selector),
1312 CRT_FLOW_CONTROLLER, startpcCrt, code.curCP());
1313 } else {
1314 // We are seeing a nonempty switch.
1315 sel.load();
1316 if (genCrt)
1317 code.crt.put(TreeInfo.skipParens(selector),
1318 CRT_FLOW_CONTROLLER, startpcCrt, code.curCP());
1319 Env<GenContext> switchEnv = env.dup(swtch, new GenContext());
1320 switchEnv.info.isSwitch = true;
1321
1322 // Compute number of labels and minimum and maximum label values.
1323 // For each case, store its label in an array.
1324 int lo = Integer.MAX_VALUE; // minimum label.
1325 int hi = Integer.MIN_VALUE; // maximum label.
1326 int nlabels = 0; // number of labels.
1327
1328 int[] labels = new int[cases.length()]; // the label array.
1329 int defaultIndex = -1; // the index of the default clause.
1330
1331 List<JCCase> l = cases;
1332 for (int i = 0; i < labels.length; i++) {
1333 if (l.head.labels.head instanceof JCConstantCaseLabel constLabel) {
1334 Assert.check(l.head.labels.size() == 1);
1335 int val = ((Number) constLabel.expr.type.constValue()).intValue();
1336 labels[i] = val;
1337 if (val < lo) lo = val;
1338 if (hi < val) hi = val;
1339 nlabels++;
1340 } else {
1341 Assert.check(defaultIndex == -1);
1342 defaultIndex = i;
1343 }
1344 l = l.tail;
1345 }
1346
1347 // Determine whether to issue a tableswitch or a lookupswitch
1348 // instruction.
1349 long table_space_cost = 4 + ((long) hi - lo + 1); // words
1350 long table_time_cost = 3; // comparisons
1351 long lookup_space_cost = 3 + 2 * (long) nlabels;
1352 long lookup_time_cost = nlabels;
1353 int opcode =
1354 nlabels > 0 &&
1355 table_space_cost + 3 * table_time_cost <=
1356 lookup_space_cost + 3 * lookup_time_cost
1357 ?
1358 tableswitch : lookupswitch;
1359
1360 int startpc = code.curCP(); // the position of the selector operation
1361 code.emitop0(opcode);
1362 code.align(4);
1363 int tableBase = code.curCP(); // the start of the jump table
1364 int[] offsets = null; // a table of offsets for a lookupswitch
1365 code.emit4(-1); // leave space for default offset
1366 if (opcode == tableswitch) {
1367 code.emit4(lo); // minimum label
1368 code.emit4(hi); // maximum label
1369 for (long i = lo; i <= hi; i++) { // leave space for jump table
1370 code.emit4(-1);
1371 }
1372 } else {
1373 code.emit4(nlabels); // number of labels
1374 for (int i = 0; i < nlabels; i++) {
1375 code.emit4(-1); code.emit4(-1); // leave space for lookup table
1376 }
1377 offsets = new int[labels.length];
1378 }
1379 Code.State stateSwitch = code.state.dup();
1380 code.markDead();
1381
1382 // For each case do:
1383 l = cases;
1384 for (int i = 0; i < labels.length; i++) {
1385 JCCase c = l.head;
1386 l = l.tail;
1387
1388 int pc = code.entryPoint(stateSwitch);
1389 // Insert offset directly into code or else into the
1390 // offsets table.
1391 if (i != defaultIndex) {
1392 if (opcode == tableswitch) {
1393 code.put4(
1394 tableBase + 4 * (labels[i] - lo + 3),
1395 pc - startpc);
1396 } else {
1397 offsets[i] = pc - startpc;
1398 }
1399 } else {
1400 code.put4(tableBase, pc - startpc);
1401 }
1402
1403 // Generate code for the statements in this case.
1404 genStats(c.stats, switchEnv, CRT_FLOW_TARGET);
1405 }
1406
1407 if (switchEnv.info.cont != null) {
1408 Assert.check(patternSwitch);
1409 code.resolve(switchEnv.info.cont, switchStart);
1410 }
1411
1412 // Resolve all breaks.
1413 code.resolve(switchEnv.info.exit);
1414
1415 // If we have not set the default offset, we do so now.
1425 if (code.get4(t) == -1)
1426 code.put4(t, defaultOffset);
1427 }
1428 } else {
1429 // Sort non-default offsets and copy into lookup table.
1430 if (defaultIndex >= 0)
1431 for (int i = defaultIndex; i < labels.length - 1; i++) {
1432 labels[i] = labels[i+1];
1433 offsets[i] = offsets[i+1];
1434 }
1435 if (nlabels > 0)
1436 qsort2(labels, offsets, 0, nlabels - 1);
1437 for (int i = 0; i < nlabels; i++) {
1438 int caseidx = tableBase + 8 * (i + 1);
1439 code.put4(caseidx, labels[i]);
1440 code.put4(caseidx + 4, offsets[i]);
1441 }
1442 }
1443
1444 if (swtch instanceof JCSwitchExpression) {
1445 // Emit line position for the end of a switch expression
1446 code.statBegin(TreeInfo.endPos(swtch));
1447 }
1448 }
1449 code.endScopes(limit);
1450 }
1451 //where
1452 /** Sort (int) arrays of keys and values
1453 */
1454 static void qsort2(int[] keys, int[] values, int lo, int hi) {
1455 int i = lo;
1456 int j = hi;
1457 int pivot = keys[(i+j)/2];
1458 do {
1459 while (keys[i] < pivot) i++;
1460 while (pivot < keys[j]) j--;
1461 if (i <= j) {
1462 int temp1 = keys[i];
1463 keys[i] = keys[j];
1464 keys[j] = temp1;
1465 int temp2 = values[i];
1466 values[i] = values[j];
1529 @Override
1530 void afterBody() {
1531 if (tree.finalizer != null && (tree.finalizer.flags & BODY_ONLY_FINALIZE) != 0) {
1532 //for body-only finally, remove the GenFinalizer after try body
1533 //so that the finally is not generated to catch bodies:
1534 tryEnv.info.finalize = null;
1535 }
1536 }
1537
1538 };
1539 tryEnv.info.gaps = new ListBuffer<>();
1540 genTry(tree.body, tree.catchers, tryEnv);
1541 }
1542 //where
1543 /** Generate code for a try or synchronized statement
1544 * @param body The body of the try or synchronized statement.
1545 * @param catchers The list of catch clauses.
1546 * @param env The current environment of the body.
1547 */
1548 void genTry(JCTree body, List<JCCatch> catchers, Env<GenContext> env) {
1549 int limit = code.nextreg;
1550 int startpc = code.curCP();
1551 Code.State stateTry = code.state.dup();
1552 genStat(body, env, CRT_BLOCK);
1553 int endpc = code.curCP();
1554 List<Integer> gaps = env.info.gaps.toList();
1555 code.statBegin(TreeInfo.endPos(body));
1556 genFinalizer(env);
1557 code.statBegin(TreeInfo.endPos(env.tree));
1558 Chain exitChain;
1559 boolean actualTry = env.tree.hasTag(TRY);
1560 if (startpc == endpc && actualTry) {
1561 exitChain = code.branch(dontgoto);
1562 } else {
1563 exitChain = code.branch(goto_);
1564 }
1565 endFinalizerGap(env);
1566 env.info.finalize.afterBody();
1567 boolean hasFinalizer =
1568 env.info.finalize != null &&
1569 env.info.finalize.hasFinalizer();
1570 if (startpc != endpc) for (List<JCCatch> l = catchers; l.nonEmpty(); l = l.tail) {
1571 // start off with exception on stack
1572 code.entryPoint(stateTry, l.head.param.sym.type);
1573 genCatch(l.head, env, startpc, endpc, gaps);
1574 genFinalizer(env);
1575 if (hasFinalizer || l.tail.nonEmpty()) {
1576 code.statBegin(TreeInfo.endPos(env.tree));
1577 exitChain = Code.mergeChains(exitChain,
1578 code.branch(goto_));
1579 }
1580 endFinalizerGap(env);
1581 }
1582 if (hasFinalizer && (startpc != endpc || !actualTry)) {
1583 // Create a new register segment to avoid allocating
1584 // the same variables in finalizers and other statements.
1585 code.newRegSegment();
1586
1587 // Add a catch-all clause.
1588
1589 // start off with exception on stack
1590 int catchallpc = code.entryPoint(stateTry, syms.throwableType);
1591
1592 // Register all exception ranges for catch all clause.
1593 // The range of the catch all clause is from the beginning
1594 // of the try or synchronized block until the present
1595 // code pointer excluding all gaps in the current
1596 // environment's GenContext.
1597 int startseg = startpc;
1598 while (env.info.gaps.nonEmpty()) {
1599 int endseg = env.info.gaps.next().intValue();
1600 registerCatch(body.pos(), startseg, endseg,
1601 catchallpc, 0);
1602 startseg = env.info.gaps.next().intValue();
1603 }
1604 code.statBegin(TreeInfo.finalizerPos(env.tree, PosKind.FIRST_STAT_POS));
1605 code.markStatBegin();
1606
1607 Item excVar = makeTemp(syms.throwableType);
1608 excVar.store();
1609 genFinalizer(env);
1610 code.resolvePending();
1611 code.statBegin(TreeInfo.finalizerPos(env.tree, PosKind.END_POS));
1612 code.markStatBegin();
1613
1614 excVar.load();
1615 registerCatch(body.pos(), startseg,
1616 env.info.gaps.next().intValue(),
1617 catchallpc, 0);
1618 code.emitop0(athrow);
1619 code.markDead();
1620
1621 // If there are jsr's to this finalizer, ...
1622 if (env.info.cont != null) {
1623 // Resolve all jsr's.
1624 code.resolve(env.info.cont);
1625
1626 // Mark statement line number
1627 code.statBegin(TreeInfo.finalizerPos(env.tree, PosKind.FIRST_STAT_POS));
1628 code.markStatBegin();
1629
1630 // Save return address.
1631 LocalItem retVar = makeTemp(syms.throwableType);
1632 retVar.store();
1633
1634 // Generate finalizer code.
1635 env.info.finalize.genLast();
1636
1637 // Return.
1740 /** Register a catch clause in the "Exceptions" code-attribute.
1741 */
1742 void registerCatch(DiagnosticPosition pos,
1743 int startpc, int endpc,
1744 int handler_pc, int catch_type) {
1745 char startpc1 = (char)startpc;
1746 char endpc1 = (char)endpc;
1747 char handler_pc1 = (char)handler_pc;
1748 if (startpc1 == startpc &&
1749 endpc1 == endpc &&
1750 handler_pc1 == handler_pc) {
1751 code.addCatch(startpc1, endpc1, handler_pc1,
1752 (char)catch_type);
1753 } else {
1754 log.error(pos, Errors.LimitCodeTooLargeForTryStmt);
1755 nerrs++;
1756 }
1757 }
1758
1759 public void visitIf(JCIf tree) {
1760 int limit = code.nextreg;
1761 Chain thenExit = null;
1762 Assert.check(code.isStatementStart());
1763 CondItem c = genCond(TreeInfo.skipParens(tree.cond),
1764 CRT_FLOW_CONTROLLER);
1765 Chain elseChain = c.jumpFalse();
1766 Assert.check(code.isStatementStart());
1767 if (!c.isFalse()) {
1768 code.resolve(c.trueJumps);
1769 genStat(tree.thenpart, env, CRT_STATEMENT | CRT_FLOW_TARGET);
1770 thenExit = code.branch(goto_);
1771 }
1772 if (elseChain != null) {
1773 code.resolve(elseChain);
1774 if (tree.elsepart != null) {
1775 genStat(tree.elsepart, env,CRT_STATEMENT | CRT_FLOW_TARGET);
1776 }
1777 }
1778 code.resolve(thenExit);
1779 code.endScopes(limit);
1780 Assert.check(code.isStatementStart());
1781 }
1782
1783 public void visitExec(JCExpressionStatement tree) {
1784 // Optimize x++ to ++x and x-- to --x.
2068 nerrs++;
2069 }
2070 int elemcode = Code.arraycode(elemtype);
2071 if (elemcode == 0 || (elemcode == 1 && ndims == 1)) {
2072 code.emitAnewarray(makeRef(pos, elemtype), type);
2073 } else if (elemcode == 1) {
2074 code.emitMultianewarray(ndims, makeRef(pos, type), type);
2075 } else {
2076 code.emitNewarray(elemcode, type);
2077 }
2078 return items.makeStackItem(type);
2079 }
2080
2081 public void visitParens(JCParens tree) {
2082 result = genExpr(tree.expr, tree.expr.type);
2083 }
2084
2085 public void visitAssign(JCAssign tree) {
2086 Item l = genExpr(tree.lhs, tree.lhs.type);
2087 genExpr(tree.rhs, tree.lhs.type).load();
2088 if (tree.rhs.type.hasTag(BOT)) {
2089 /* This is just a case of widening reference conversion that per 5.1.5 simply calls
2090 for "regarding a reference as having some other type in a manner that can be proved
2091 correct at compile time."
2092 */
2093 code.state.forceStackTop(tree.lhs.type);
2094 }
2095 result = items.makeAssignItem(l);
2096 }
2097
2098 public void visitAssignop(JCAssignOp tree) {
2099 OperatorSymbol operator = tree.operator;
2100 Item l;
2101 if (operator.opcode == string_add) {
2102 l = concat.makeConcat(tree);
2103 } else {
2104 // Generate code for first expression
2105 l = genExpr(tree.lhs, tree.lhs.type);
2106
2107 // If we have an increment of -32768 to +32767 of a local
2346 items.makeThisItem().load();
2347 sym = binaryQualifier(sym, env.enclClass.type);
2348 result = items.makeMemberItem(sym, nonVirtualForPrivateAccess(sym));
2349 }
2350 }
2351
2352 //where
2353 private boolean nonVirtualForPrivateAccess(Symbol sym) {
2354 boolean useVirtual = target.hasVirtualPrivateInvoke() &&
2355 !disableVirtualizedPrivateInvoke;
2356 return !useVirtual && ((sym.flags() & PRIVATE) != 0);
2357 }
2358
2359 public void visitSelect(JCFieldAccess tree) {
2360 Symbol sym = tree.sym;
2361
2362 if (tree.name == names._class) {
2363 code.emitLdc((LoadableConstant)checkDimension(tree.pos(), tree.selected.type));
2364 result = items.makeStackItem(pt);
2365 return;
2366 }
2367
2368 Symbol ssym = TreeInfo.symbol(tree.selected);
2369
2370 // Are we selecting via super?
2371 boolean selectSuper =
2372 ssym != null && (ssym.kind == TYP || ssym.name == names._super);
2373
2374 // Are we accessing a member of the superclass in an access method
2375 // resulting from a qualified super?
2376 boolean accessSuper = isAccessSuper(env.enclMethod);
2377
2378 Item base = (selectSuper)
2379 ? items.makeSuperItem()
2380 : genExpr(tree.selected, tree.selected.type);
2381
2382 if (sym.kind == VAR && ((VarSymbol) sym).getConstValue() != null) {
2383 // We are seeing a variable that is constant but its selecting
2384 // expression is not.
2385 if ((sym.flags() & STATIC) != 0) {
2386 if (!selectSuper && (ssym == null || ssym.kind != TYP))
|
1 /*
2 * Copyright (c) 1999, 2026, 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
60 * <p><b>This is NOT part of any supported API.
61 * If you write code that depends on this, you do so at your own risk.
62 * This code and its internal interfaces are subject to change or
63 * deletion without notice.</b>
64 */
65 public class Gen extends JCTree.Visitor {
66 protected static final Context.Key<Gen> genKey = new Context.Key<>();
67
68 private final Log log;
69 private final Symtab syms;
70 private final Check chk;
71 private final Resolve rs;
72 private final TreeMaker make;
73 private final Names names;
74 private final Target target;
75 private final String accessDollar;
76 private final Types types;
77 private final Lower lower;
78 private final Annotate annotate;
79 private final StringConcat concat;
80 private final LocalProxyVarsGen localProxyVarsGen;
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 localProxyVarsGen = LocalProxyVarsGen.instance(context);
116
117 methodType = new MethodType(null, null, null, syms.methodClass);
118 accessDollar = "access" + target.syntheticNameChar();
119 lower = Lower.instance(context);
120
121 Options options = Options.instance(context);
122 lineDebugInfo =
123 options.isUnset(G_CUSTOM) ||
124 options.isSet(G_CUSTOM, "lines");
125 varDebugInfo =
126 options.isUnset(G_CUSTOM)
127 ? options.isSet(G)
128 : options.isSet(G_CUSTOM, "vars");
129 genCrt = options.isSet(XJCOV);
130 debugCode = options.isSet("debug.code");
131 disableVirtualizedPrivateInvoke = options.isSet("disableVirtualizedPrivateInvoke");
132 poolWriter = new PoolWriter(types, names);
133 unsetFieldsInfo = UnsetFieldsInfo.instance(context);
134
135 // ignore cldc because we cannot have both stackmap formats
136 this.stackMap = StackMapFormat.JSR202;
137 annotate = Annotate.instance(context);
138 qualifiedSymbolCache = new HashMap<>();
139 Preview preview = Preview.instance(context);
140 Source source = Source.instance(context);
141 allowValueClasses = (!preview.isPreview(Source.Feature.VALUE_CLASSES) || preview.isEnabled()) &&
142 Source.Feature.VALUE_CLASSES.allowedInSource(source);
143 }
144
145 /** Switches
146 */
147 private final boolean lineDebugInfo;
148 private final boolean varDebugInfo;
149 private final boolean genCrt;
150 private final boolean debugCode;
151 private boolean disableVirtualizedPrivateInvoke;
152 private final boolean allowValueClasses;
153
154 /** Code buffer, set by genMethod.
155 */
156 private Code code;
157
158 /** Items structure, set by genMethod.
159 */
160 private Items items;
161
162 /** Environment for symbol lookup, set by genClass
163 */
164 private Env<AttrContext> attrEnv;
165
166 /** The top level tree.
167 */
168 private JCCompilationUnit toplevel;
169
170 /** The number of code-gen errors in this class.
171 */
172 private int nerrs = 0;
411 boolean hasFinally(JCTree target, Env<GenContext> env) {
412 while (env.tree != target) {
413 if (env.tree.hasTag(TRY) && env.info.finalize.hasFinalizer())
414 return true;
415 env = env.next;
416 }
417 return false;
418 }
419
420 /* ************************************************************************
421 * Normalizing class-members.
422 *************************************************************************/
423
424 /** Distribute member initializer code into constructors and {@code <clinit>}
425 * method.
426 * @param defs The list of class member declarations.
427 * @param c The enclosing class.
428 */
429 List<JCTree> normalizeDefs(List<JCTree> defs, ClassSymbol c) {
430 ListBuffer<JCStatement> initCode = new ListBuffer<>();
431 // only used for value classes
432 ListBuffer<JCStatement> initBlocks = new ListBuffer<>();
433 ListBuffer<Attribute.TypeCompound> initTAs = new ListBuffer<>();
434 ListBuffer<JCStatement> clinitCode = new ListBuffer<>();
435 ListBuffer<Attribute.TypeCompound> clinitTAs = new ListBuffer<>();
436 ListBuffer<JCTree> methodDefs = new ListBuffer<>();
437 // Sort definitions into three listbuffers:
438 // - initCode for instance initializers
439 // - clinitCode for class initializers
440 // - methodDefs for method definitions
441 for (List<JCTree> l = defs; l.nonEmpty(); l = l.tail) {
442 JCTree def = l.head;
443 switch (def.getTag()) {
444 case BLOCK:
445 JCBlock block = (JCBlock)def;
446 if ((block.flags & STATIC) != 0)
447 clinitCode.append(block);
448 else if ((block.flags & SYNTHETIC) == 0) {
449 if (c.isValueClass()) {
450 initBlocks.append(block);
451 } else {
452 initCode.append(block);
453 }
454 }
455 break;
456 case METHODDEF:
457 methodDefs.append(def);
458 break;
459 case VARDEF:
460 JCVariableDecl vdef = (JCVariableDecl) def;
461 VarSymbol sym = vdef.sym;
462 checkDimension(vdef.pos(), sym.type);
463 if (vdef.init != null) {
464 if ((sym.flags() & STATIC) == 0) {
465 // Always initialize instance variables.
466 JCStatement init = make.at(vdef.pos()).
467 Assignment(sym, vdef.init);
468 initCode.append(init);
469 init.endpos = vdef.endpos;
470 initTAs.addAll(getAndRemoveNonFieldTAs(sym));
471 } else if (sym.getConstValue() == null) {
472 // Initialize class (static) variables only if
473 // they are not compile-time constants.
474 JCStatement init = make.at(vdef.pos).
475 Assignment(sym, vdef.init);
476 clinitCode.append(init);
477 init.endpos = vdef.endpos;
478 clinitTAs.addAll(getAndRemoveNonFieldTAs(sym));
479 } else {
480 checkStringConstant(vdef.init.pos(), sym.getConstValue());
481 /* if the init contains a reference to an external class, add it to the
482 * constant's pool
483 */
484 vdef.init.accept(classReferenceVisitor);
485 }
486 }
487 break;
488 default:
489 Assert.error();
490 }
491 }
492 // Insert any instance initializers into all constructors.
493 if (initCode.length() != 0 || initBlocks.length() != 0) {
494 initTAs.addAll(c.getInitTypeAttributes());
495 List<Attribute.TypeCompound> initTAlist = initTAs.toList();
496 for (JCTree t : methodDefs) {
497 normalizeMethod((JCMethodDecl)t, initCode.toList(), initBlocks.toList(), initTAlist);
498 }
499 }
500 // If there are class initializers, create a <clinit> method
501 // that contains them as its body.
502 if (clinitCode.length() != 0) {
503 MethodSymbol clinit = new MethodSymbol(
504 STATIC | (c.flags() & STRICTFP),
505 names.clinit,
506 new MethodType(
507 List.nil(), syms.voidType,
508 List.nil(), syms.methodClass),
509 c);
510 c.members().enter(clinit);
511 List<JCStatement> clinitStats = clinitCode.toList();
512 JCBlock block = make.at(clinitStats.head.pos()).Block(0, clinitStats);
513 block.bracePos = TreeInfo.endPos(clinitStats.last());
514 methodDefs.append(make.MethodDef(clinit, block));
515
516 if (!clinitTAs.isEmpty())
517 clinit.appendUniqueTypeAttributes(clinitTAs.toList());
540
541 /** Check a constant value and report if it is a string that is
542 * too large.
543 */
544 private void checkStringConstant(DiagnosticPosition pos, Object constValue) {
545 if (nerrs != 0 || // only complain about a long string once
546 constValue == null ||
547 !(constValue instanceof String str) ||
548 str.length() < PoolWriter.MAX_STRING_LENGTH)
549 return;
550 log.error(pos, Errors.LimitString);
551 nerrs++;
552 }
553
554 /** Insert instance initializer code into constructors prior to the super() call.
555 * @param md The tree potentially representing a
556 * constructor's definition.
557 * @param initCode The list of instance initializer statements.
558 * @param initTAs Type annotations from the initializer expression.
559 */
560 void normalizeMethod(JCMethodDecl md, List<JCStatement> initCode, List<JCStatement> initBlocks, List<TypeCompound> initTAs) {
561 Set<Symbol> fieldsWithInits;
562 List<JCStatement> inits;
563 if ((fieldsWithInits = localProxyVarsGen.initializersAlreadyInConst.get(md)) != null) {
564 ListBuffer<JCStatement> newInitCode = new ListBuffer<>();
565 for (JCStatement init : initCode) {
566 Symbol sym = ((JCIdent)((JCAssign)((JCExpressionStatement)init).expr).lhs).sym;
567 if (!fieldsWithInits.contains(sym)) {
568 newInitCode.add(init);
569 }
570 }
571 inits = newInitCode.toList();
572 localProxyVarsGen.initializersAlreadyInConst.remove(md);
573 } else {
574 inits = initCode;
575 }
576 if (TreeInfo.isConstructor(md) && TreeInfo.hasConstructorCall(md, names._super)) {
577 // We are seeing a constructor that has a super() call.
578 // Find the super() invocation and append the given initializer code.
579 if (allowValueClasses & (md.sym.owner.isValueClass() || ((md.sym.owner.flags_field & RECORD) != 0))) {
580 rewriteInitializersIfNeeded(md, inits);
581 md.body.stats = inits.appendList(md.body.stats);
582 TreeInfo.mapSuperCalls(md.body, supercall -> make.Block(0, initBlocks.prepend(supercall)));
583 } else {
584 TreeInfo.mapSuperCalls(md.body, supercall -> make.Block(0, inits.prepend(supercall)));
585 }
586
587 if (md.body.bracePos == Position.NOPOS)
588 md.body.bracePos = TreeInfo.endPos(md.body.stats.last());
589
590 md.sym.appendUniqueTypeAttributes(initTAs);
591 }
592 }
593
594 void rewriteInitializersIfNeeded(JCMethodDecl md, List<JCStatement> initCode) {
595 if (lower.initializerOuterThis.containsKey(md.sym.owner)) {
596 InitializerVisitor initializerVisitor = new InitializerVisitor(md, lower.initializerOuterThis.get(md.sym.owner));
597 for (JCStatement init : initCode) {
598 initializerVisitor.scan(init);
599 }
600 }
601 }
602
603 public static class InitializerVisitor extends TreeScanner {
604 JCMethodDecl md;
605 Set<JCExpression> exprSet;
606
607 public InitializerVisitor(JCMethodDecl md, Set<JCExpression> exprSet) {
608 this.md = md;
609 this.exprSet = exprSet;
610 }
611
612 @Override
613 public void visitTree(JCTree tree) {}
614
615 @Override
616 public void visitIdent(JCIdent tree) {
617 if (exprSet.contains(tree)) {
618 for (JCVariableDecl param: md.params) {
619 if (param.name == tree.name &&
620 ((param.sym.flags_field & (MANDATED | NOOUTERTHIS)) == (MANDATED | NOOUTERTHIS))) {
621 tree.sym = param.sym;
622 }
623 }
624 }
625 }
626 }
627
628 /* ************************************************************************
629 * Traversal methods
630 *************************************************************************/
631
632 /** Visitor argument: The current environment.
633 */
634 Env<GenContext> env;
635
636 /** Visitor argument: The expected type (prototype).
637 */
638 Type pt;
639
640 /** Visitor result: The item representing the computed value.
641 */
642 Item result;
643
644 /** Visitor method: generate code for a definition, catching and reporting
645 * any completion failures.
646 * @param tree The definition to be visited.
647 * @param env The environment current at the definition.
1004 // Count up extra parameters
1005 if (meth.isConstructor()) {
1006 extras++;
1007 if (meth.enclClass().isInner() &&
1008 !meth.enclClass().isStatic()) {
1009 extras++;
1010 }
1011 } else if ((tree.mods.flags & STATIC) == 0) {
1012 extras++;
1013 }
1014 // System.err.println("Generating " + meth + " in " + meth.owner); //DEBUG
1015 if (Code.width(types.erasure(env.enclMethod.sym.type).getParameterTypes()) + extras >
1016 ClassFile.MAX_PARAMETERS) {
1017 log.error(tree.pos(), Errors.LimitParameters);
1018 nerrs++;
1019 }
1020
1021 else if (tree.body != null) {
1022 // Create a new code structure and initialize it.
1023 int startpcCrt = initCode(tree, env, fatcode);
1024 Set<VarSymbol> prevUnsetFields = code.currentUnsetFields;
1025 if (meth.isConstructor()) {
1026 code.currentUnsetFields = unsetFieldsInfo.getUnsetFields(env.enclClass.sym, tree.body);
1027 code.initialUnsetFields = unsetFieldsInfo.getUnsetFields(env.enclClass.sym, tree.body);
1028 }
1029
1030 try {
1031 genStat(tree.body, env);
1032 } catch (CodeSizeOverflow e) {
1033 // Failed due to code limit, try again with jsr/ret
1034 startpcCrt = initCode(tree, env, fatcode);
1035 genStat(tree.body, env);
1036 } finally {
1037 code.currentUnsetFields = prevUnsetFields;
1038 }
1039
1040 if (code.state.stacksize != 0) {
1041 log.error(tree.body.pos(), Errors.StackSimError(tree.sym));
1042 throw new AssertionError();
1043 }
1044
1045 // If last statement could complete normally, insert a
1046 // return at the end.
1047 if (code.isAlive()) {
1048 code.statBegin(TreeInfo.endPos(tree.body));
1049 if (env.enclMethod == null ||
1050 env.enclMethod.sym.type.getReturnType().hasTag(VOID)) {
1051 code.emitop0(return_);
1052 } else {
1053 // sometime dead code seems alive (4415991);
1054 // generate a small loop instead
1055 int startpc = code.entryPoint();
1056 CondItem c = items.makeCondItem(goto_);
1057 code.resolve(c.jumpTrue(), startpc);
1085 code.compressCatchTable();
1086
1087 // Fill in type annotation positions for exception parameters
1088 code.fillExceptionParameterPositions();
1089 }
1090 }
1091
1092 private int initCode(JCMethodDecl tree, Env<GenContext> env, boolean fatcode) {
1093 MethodSymbol meth = tree.sym;
1094
1095 // Create a new code structure.
1096 meth.code = code = new Code(meth,
1097 fatcode,
1098 lineDebugInfo ? toplevel.lineMap : null,
1099 varDebugInfo,
1100 stackMap,
1101 debugCode,
1102 genCrt ? new CRTable(tree) : null,
1103 syms,
1104 types,
1105 poolWriter,
1106 allowValueClasses);
1107 items = new Items(poolWriter, code, syms, types);
1108 if (code.debugCode) {
1109 System.err.println(meth + " for body " + tree);
1110 }
1111
1112 // If method is not static, create a new local variable address
1113 // for `this'.
1114 if ((tree.mods.flags & STATIC) == 0) {
1115 Type selfType = meth.owner.type;
1116 if (meth.isConstructor() && selfType != syms.objectType)
1117 selfType = UninitializedType.uninitializedThis(selfType);
1118 code.setDefined(
1119 code.newLocal(
1120 new VarSymbol(FINAL, names._this, selfType, meth.owner)));
1121 }
1122
1123 // Mark all parameters as defined from the beginning of
1124 // the method.
1125 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
1126 checkDimension(l.head.pos(), l.head.sym.type);
1222 public void visitForLoop(JCForLoop tree) {
1223 int limit = code.nextreg;
1224 genStats(tree.init, env);
1225 genLoop(tree, tree.body, tree.cond, tree.step, true);
1226 code.endScopes(limit);
1227 }
1228 //where
1229 /** Generate code for a loop.
1230 * @param loop The tree representing the loop.
1231 * @param body The loop's body.
1232 * @param cond The loop's controlling condition.
1233 * @param step "Step" statements to be inserted at end of
1234 * each iteration.
1235 * @param testFirst True if the loop test belongs before the body.
1236 */
1237 private void genLoop(JCStatement loop,
1238 JCStatement body,
1239 JCExpression cond,
1240 List<JCExpressionStatement> step,
1241 boolean testFirst) {
1242 Set<VarSymbol> prevCodeUnsetFields = code.currentUnsetFields;
1243 try {
1244 genLoopHelper(loop, body, cond, step, testFirst);
1245 } finally {
1246 code.currentUnsetFields = prevCodeUnsetFields;
1247 }
1248 }
1249
1250 private void genLoopHelper(JCStatement loop,
1251 JCStatement body,
1252 JCExpression cond,
1253 List<JCExpressionStatement> step,
1254 boolean testFirst) {
1255 Env<GenContext> loopEnv = env.dup(loop, new GenContext());
1256 int startpc = code.entryPoint();
1257 if (testFirst) { //while or for loop
1258 CondItem c;
1259 if (cond != null) {
1260 code.statBegin(cond.pos);
1261 Assert.check(code.isStatementStart());
1262 c = genCond(TreeInfo.skipParens(cond), CRT_FLOW_CONTROLLER);
1263 } else {
1264 c = items.makeCondItem(goto_);
1265 }
1266 Chain loopDone = c.jumpFalse();
1267 code.resolve(c.trueJumps);
1268 Assert.check(code.isStatementStart());
1269 genStat(body, loopEnv, CRT_STATEMENT | CRT_FLOW_TARGET);
1270 code.resolve(loopEnv.info.cont);
1271 genStats(step, loopEnv);
1272 code.resolve(code.branch(goto_), startpc);
1273 code.resolve(loopDone);
1274 } else {
1293 }
1294
1295 public void visitForeachLoop(JCEnhancedForLoop tree) {
1296 throw new AssertionError(); // should have been removed by Lower.
1297 }
1298
1299 public void visitLabelled(JCLabeledStatement tree) {
1300 Env<GenContext> localEnv = env.dup(tree, new GenContext());
1301 genStat(tree.body, localEnv, CRT_STATEMENT);
1302 code.resolve(localEnv.info.exit);
1303 }
1304
1305 public void visitSwitch(JCSwitch tree) {
1306 handleSwitch(tree, tree.selector, tree.cases, tree.patternSwitch);
1307 }
1308
1309 @Override
1310 public void visitSwitchExpression(JCSwitchExpression tree) {
1311 code.resolvePending();
1312 boolean prevInCondSwitchExpression = inCondSwitchExpression;
1313 Set<VarSymbol> prevCodeUnsetFields = code.currentUnsetFields;
1314 try {
1315 inCondSwitchExpression = false;
1316 doHandleSwitchExpression(tree);
1317 } finally {
1318 inCondSwitchExpression = prevInCondSwitchExpression;
1319 code.currentUnsetFields = prevCodeUnsetFields;
1320 }
1321 result = items.makeStackItem(pt);
1322 }
1323
1324 private void doHandleSwitchExpression(JCSwitchExpression tree) {
1325 List<LocalItem> prevStackBeforeSwitchExpression = stackBeforeSwitchExpression;
1326 LocalItem prevSwitchResult = switchResult;
1327 int limit = code.nextreg;
1328 try {
1329 stackBeforeSwitchExpression = List.nil();
1330 switchResult = null;
1331 if (hasTry(tree)) {
1332 //if the switch expression contains try-catch, the catch handlers need to have
1333 //an empty stack. So stash whole stack to local variables, and restore it before
1334 //breaks:
1335 while (code.state.stacksize > 0) {
1336 Type type = code.state.peek();
1337 Name varName = names.fromString(target.syntheticNameChar() +
1338 "stack" +
1339 target.syntheticNameChar() +
1375 hasTry = true;
1376 }
1377
1378 @Override
1379 public void visitClassDef(JCClassDecl tree) {
1380 }
1381
1382 @Override
1383 public void visitLambda(JCLambda tree) {
1384 }
1385 };
1386
1387 HasTryScanner hasTryScanner = new HasTryScanner();
1388
1389 hasTryScanner.scan(tree);
1390 return hasTryScanner.hasTry;
1391 }
1392
1393 private void handleSwitch(JCTree swtch, JCExpression selector, List<JCCase> cases,
1394 boolean patternSwitch) {
1395 Set<VarSymbol> prevCodeUnsetFields = code.currentUnsetFields;
1396 try {
1397 handleSwitchHelper(swtch, selector, cases, patternSwitch);
1398 } finally {
1399 code.currentUnsetFields = prevCodeUnsetFields;
1400 }
1401 }
1402
1403 void handleSwitchHelper(JCTree swtch, JCExpression selector, List<JCCase> cases,
1404 boolean patternSwitch) {
1405 int limit = code.nextreg;
1406 Assert.check(!selector.type.hasTag(CLASS));
1407 int switchStart = patternSwitch ? code.entryPoint() : -1;
1408 int startpcCrt = genCrt ? code.curCP() : 0;
1409 Assert.check(code.isStatementStart());
1410 Item sel = genExpr(selector, syms.intType);
1411 if (cases.isEmpty()) {
1412 // We are seeing: switch <sel> {}
1413 sel.load().drop();
1414 if (genCrt)
1415 code.crt.put(TreeInfo.skipParens(selector),
1416 CRT_FLOW_CONTROLLER, startpcCrt, code.curCP());
1417 } else {
1418 // We are seeing a nonempty switch.
1419 sel.load();
1420 if (genCrt)
1421 code.crt.put(TreeInfo.skipParens(selector),
1422 CRT_FLOW_CONTROLLER, startpcCrt, code.curCP());
1423 Env<GenContext> switchEnv = env.dup(swtch, new GenContext());
1424 switchEnv.info.isSwitch = true;
1425
1426 // Compute number of labels and minimum and maximum label values.
1427 // For each case, store its label in an array.
1428 int lo = Integer.MAX_VALUE; // minimum label.
1429 int hi = Integer.MIN_VALUE; // maximum label.
1430 int nlabels = 0; // number of labels.
1431
1432 int[] labels = new int[cases.length()]; // the label array.
1433 int defaultIndex = -1; // the index of the default clause.
1434
1435 List<JCCase> l = cases;
1436 for (int i = 0; i < labels.length; i++) {
1437 if (l.head.labels.head instanceof JCConstantCaseLabel constLabel) {
1438 Assert.check(l.head.labels.size() == 1);
1439 int val = ((Number) constLabel.expr.type.constValue()).intValue();
1440 labels[i] = val;
1441 if (val < lo) lo = val;
1442 if (hi < val) hi = val;
1443 nlabels++;
1444 } else {
1445 Assert.check(defaultIndex == -1);
1446 defaultIndex = i;
1447 }
1448 l = l.tail;
1449 }
1450
1451 // Determine whether to issue a tableswitch or a lookupswitch
1452 // instruction.
1453 long table_space_cost = 4 + ((long) hi - lo + 1); // words
1454 long table_time_cost = 3; // comparisons
1455 long lookup_space_cost = 3 + 2 * (long) nlabels;
1456 long lookup_time_cost = nlabels;
1457 int opcode =
1458 nlabels > 0 &&
1459 table_space_cost + 3 * table_time_cost <=
1460 lookup_space_cost + 3 * lookup_time_cost
1461 ?
1462 tableswitch : lookupswitch;
1463
1464 int startpc = code.curCP(); // the position of the selector operation
1465 code.emitop0(opcode);
1466 code.align(4);
1467 int tableBase = code.curCP(); // the start of the jump table
1468 int[] offsets = null; // a table of offsets for a lookupswitch
1469 code.emit4(-1); // leave space for default offset
1470 if (opcode == tableswitch) {
1471 code.emit4(lo); // minimum label
1472 code.emit4(hi); // maximum label
1473 for (long i = lo; i <= hi; i++) { // leave space for jump table
1474 code.emit4(-1);
1475 }
1476 } else {
1477 code.emit4(nlabels); // number of labels
1478 for (int i = 0; i < nlabels; i++) {
1479 code.emit4(-1); code.emit4(-1); // leave space for lookup table
1480 }
1481 offsets = new int[labels.length];
1482 }
1483 Code.State stateSwitch = code.state.dup();
1484 code.markDead();
1485
1486 // For each case do:
1487 l = cases;
1488 for (int i = 0; i < labels.length; i++) {
1489 JCCase c = l.head;
1490 l = l.tail;
1491
1492 int pc = code.entryPoint(stateSwitch);
1493 // Insert offset directly into code or else into the
1494 // offsets table.
1495 if (i != defaultIndex) {
1496 if (opcode == tableswitch) {
1497 code.put4(
1498 tableBase + 4 * (labels[i] - lo + 3),
1499 pc - startpc);
1500 } else {
1501 offsets[i] = pc - startpc;
1502 }
1503 } else {
1504 code.put4(tableBase, pc - startpc);
1505 }
1506
1507 // Generate code for the statements in this case.
1508 genStats(c.stats, switchEnv, CRT_FLOW_TARGET);
1509 }
1510
1511 if (switchEnv.info.cont != null) {
1512 Assert.check(patternSwitch);
1513 code.resolve(switchEnv.info.cont, switchStart);
1514 }
1515
1516 // Resolve all breaks.
1517 code.resolve(switchEnv.info.exit);
1518
1519 // If we have not set the default offset, we do so now.
1529 if (code.get4(t) == -1)
1530 code.put4(t, defaultOffset);
1531 }
1532 } else {
1533 // Sort non-default offsets and copy into lookup table.
1534 if (defaultIndex >= 0)
1535 for (int i = defaultIndex; i < labels.length - 1; i++) {
1536 labels[i] = labels[i+1];
1537 offsets[i] = offsets[i+1];
1538 }
1539 if (nlabels > 0)
1540 qsort2(labels, offsets, 0, nlabels - 1);
1541 for (int i = 0; i < nlabels; i++) {
1542 int caseidx = tableBase + 8 * (i + 1);
1543 code.put4(caseidx, labels[i]);
1544 code.put4(caseidx + 4, offsets[i]);
1545 }
1546 }
1547
1548 if (swtch instanceof JCSwitchExpression) {
1549 // Emit line position for the end of a switch expression
1550 code.statBegin(TreeInfo.endPos(swtch));
1551 }
1552 }
1553 code.endScopes(limit);
1554 }
1555 //where
1556 /** Sort (int) arrays of keys and values
1557 */
1558 static void qsort2(int[] keys, int[] values, int lo, int hi) {
1559 int i = lo;
1560 int j = hi;
1561 int pivot = keys[(i+j)/2];
1562 do {
1563 while (keys[i] < pivot) i++;
1564 while (pivot < keys[j]) j--;
1565 if (i <= j) {
1566 int temp1 = keys[i];
1567 keys[i] = keys[j];
1568 keys[j] = temp1;
1569 int temp2 = values[i];
1570 values[i] = values[j];
1633 @Override
1634 void afterBody() {
1635 if (tree.finalizer != null && (tree.finalizer.flags & BODY_ONLY_FINALIZE) != 0) {
1636 //for body-only finally, remove the GenFinalizer after try body
1637 //so that the finally is not generated to catch bodies:
1638 tryEnv.info.finalize = null;
1639 }
1640 }
1641
1642 };
1643 tryEnv.info.gaps = new ListBuffer<>();
1644 genTry(tree.body, tree.catchers, tryEnv);
1645 }
1646 //where
1647 /** Generate code for a try or synchronized statement
1648 * @param body The body of the try or synchronized statement.
1649 * @param catchers The list of catch clauses.
1650 * @param env The current environment of the body.
1651 */
1652 void genTry(JCTree body, List<JCCatch> catchers, Env<GenContext> env) {
1653 Set<VarSymbol> prevCodeUnsetFields = code.currentUnsetFields;
1654 try {
1655 genTryHelper(body, catchers, env);
1656 } finally {
1657 code.currentUnsetFields = prevCodeUnsetFields;
1658 }
1659 }
1660
1661 void genTryHelper(JCTree body, List<JCCatch> catchers, Env<GenContext> env) {
1662 int limit = code.nextreg;
1663 int startpc = code.curCP();
1664 Code.State stateTry = code.state.dup();
1665 genStat(body, env, CRT_BLOCK);
1666 int endpc = code.curCP();
1667 List<Integer> gaps = env.info.gaps.toList();
1668 code.statBegin(TreeInfo.endPos(body));
1669 genFinalizer(env);
1670 code.statBegin(TreeInfo.endPos(env.tree));
1671 Chain exitChain;
1672 boolean actualTry = env.tree.hasTag(TRY);
1673 if (startpc == endpc && actualTry) {
1674 exitChain = code.branch(dontgoto);
1675 } else {
1676 exitChain = code.branch(goto_);
1677 }
1678 endFinalizerGap(env);
1679 env.info.finalize.afterBody();
1680 boolean hasFinalizer =
1681 env.info.finalize != null &&
1682 env.info.finalize.hasFinalizer();
1683 if (startpc != endpc) for (List<JCCatch> l = catchers; l.nonEmpty(); l = l.tail) {
1684 // start off with exception on stack
1685 code.entryPoint(stateTry, l.head.param.sym.type);
1686 genCatch(l.head, env, startpc, endpc, gaps);
1687 genFinalizer(env);
1688 if (hasFinalizer || l.tail.nonEmpty()) {
1689 code.statBegin(TreeInfo.endPos(env.tree));
1690 exitChain = Code.mergeChains(exitChain,
1691 code.branch(goto_));
1692 }
1693 endFinalizerGap(env);
1694 }
1695 if (hasFinalizer && (startpc != endpc || !actualTry)) {
1696 // Create a new register segment to avoid allocating
1697 // the same variables in finalizers and other statements.
1698 code.newRegSegment();
1699
1700 // Add a catch-all clause.
1701
1702 // start off with exception on stack
1703 int catchallpc = code.entryPoint(stateTry, syms.throwableType);
1704
1705 // Register all exception ranges for catch all clause.
1706 // The range of the catch all clause is from the beginning
1707 // of the try or synchronized block until the present
1708 // code pointer excluding all gaps in the current
1709 // environment's GenContext.
1710 int startseg = startpc;
1711 while (env.info.gaps.nonEmpty()) {
1712 int endseg = env.info.gaps.next().intValue();
1713 registerCatch(body.pos(), startseg, endseg,
1714 catchallpc, 0);
1715 startseg = env.info.gaps.next().intValue();
1716 }
1717 code.statBegin(TreeInfo.finalizerPos(env.tree, PosKind.FIRST_STAT_POS));
1718 code.markStatBegin();
1719
1720 Item excVar = makeTemp(syms.throwableType);
1721 excVar.store();
1722 genFinalizer(env);
1723 code.resolvePending();
1724 code.statBegin(TreeInfo.finalizerPos(env.tree, PosKind.END_POS));
1725 code.markStatBegin();
1726
1727 excVar.load();
1728 registerCatch(body.pos(), startseg,
1729 env.info.gaps.next().intValue(),
1730 catchallpc, 0);
1731 code.emitop0(athrow);
1732 code.markDead();
1733
1734 // If there are jsr's to this finalizer, ...
1735 if (env.info.cont != null) {
1736 // Resolve all jsr's.
1737 code.resolve(env.info.cont);
1738
1739 // Mark statement line number
1740 code.statBegin(TreeInfo.finalizerPos(env.tree, PosKind.FIRST_STAT_POS));
1741 code.markStatBegin();
1742
1743 // Save return address.
1744 LocalItem retVar = makeTemp(syms.throwableType);
1745 retVar.store();
1746
1747 // Generate finalizer code.
1748 env.info.finalize.genLast();
1749
1750 // Return.
1853 /** Register a catch clause in the "Exceptions" code-attribute.
1854 */
1855 void registerCatch(DiagnosticPosition pos,
1856 int startpc, int endpc,
1857 int handler_pc, int catch_type) {
1858 char startpc1 = (char)startpc;
1859 char endpc1 = (char)endpc;
1860 char handler_pc1 = (char)handler_pc;
1861 if (startpc1 == startpc &&
1862 endpc1 == endpc &&
1863 handler_pc1 == handler_pc) {
1864 code.addCatch(startpc1, endpc1, handler_pc1,
1865 (char)catch_type);
1866 } else {
1867 log.error(pos, Errors.LimitCodeTooLargeForTryStmt);
1868 nerrs++;
1869 }
1870 }
1871
1872 public void visitIf(JCIf tree) {
1873 Set<VarSymbol> prevCodeUnsetFields = code.currentUnsetFields;
1874 try {
1875 visitIfHelper(tree);
1876 } finally {
1877 code.currentUnsetFields = prevCodeUnsetFields;
1878 }
1879 }
1880
1881 public void visitIfHelper(JCIf tree) {
1882 int limit = code.nextreg;
1883 Chain thenExit = null;
1884 Assert.check(code.isStatementStart());
1885 CondItem c = genCond(TreeInfo.skipParens(tree.cond),
1886 CRT_FLOW_CONTROLLER);
1887 Chain elseChain = c.jumpFalse();
1888 Assert.check(code.isStatementStart());
1889 if (!c.isFalse()) {
1890 code.resolve(c.trueJumps);
1891 genStat(tree.thenpart, env, CRT_STATEMENT | CRT_FLOW_TARGET);
1892 thenExit = code.branch(goto_);
1893 }
1894 if (elseChain != null) {
1895 code.resolve(elseChain);
1896 if (tree.elsepart != null) {
1897 genStat(tree.elsepart, env,CRT_STATEMENT | CRT_FLOW_TARGET);
1898 }
1899 }
1900 code.resolve(thenExit);
1901 code.endScopes(limit);
1902 Assert.check(code.isStatementStart());
1903 }
1904
1905 public void visitExec(JCExpressionStatement tree) {
1906 // Optimize x++ to ++x and x-- to --x.
2190 nerrs++;
2191 }
2192 int elemcode = Code.arraycode(elemtype);
2193 if (elemcode == 0 || (elemcode == 1 && ndims == 1)) {
2194 code.emitAnewarray(makeRef(pos, elemtype), type);
2195 } else if (elemcode == 1) {
2196 code.emitMultianewarray(ndims, makeRef(pos, type), type);
2197 } else {
2198 code.emitNewarray(elemcode, type);
2199 }
2200 return items.makeStackItem(type);
2201 }
2202
2203 public void visitParens(JCParens tree) {
2204 result = genExpr(tree.expr, tree.expr.type);
2205 }
2206
2207 public void visitAssign(JCAssign tree) {
2208 Item l = genExpr(tree.lhs, tree.lhs.type);
2209 genExpr(tree.rhs, tree.lhs.type).load();
2210 Set<VarSymbol> tmpUnsetSymbols = unsetFieldsInfo.getUnsetFields(env.enclClass.sym, tree);
2211 code.currentUnsetFields = tmpUnsetSymbols != null ? tmpUnsetSymbols : code.currentUnsetFields;
2212 if (tree.rhs.type.hasTag(BOT)) {
2213 /* This is just a case of widening reference conversion that per 5.1.5 simply calls
2214 for "regarding a reference as having some other type in a manner that can be proved
2215 correct at compile time."
2216 */
2217 code.state.forceStackTop(tree.lhs.type);
2218 }
2219 result = items.makeAssignItem(l);
2220 }
2221
2222 public void visitAssignop(JCAssignOp tree) {
2223 OperatorSymbol operator = tree.operator;
2224 Item l;
2225 if (operator.opcode == string_add) {
2226 l = concat.makeConcat(tree);
2227 } else {
2228 // Generate code for first expression
2229 l = genExpr(tree.lhs, tree.lhs.type);
2230
2231 // If we have an increment of -32768 to +32767 of a local
2470 items.makeThisItem().load();
2471 sym = binaryQualifier(sym, env.enclClass.type);
2472 result = items.makeMemberItem(sym, nonVirtualForPrivateAccess(sym));
2473 }
2474 }
2475
2476 //where
2477 private boolean nonVirtualForPrivateAccess(Symbol sym) {
2478 boolean useVirtual = target.hasVirtualPrivateInvoke() &&
2479 !disableVirtualizedPrivateInvoke;
2480 return !useVirtual && ((sym.flags() & PRIVATE) != 0);
2481 }
2482
2483 public void visitSelect(JCFieldAccess tree) {
2484 Symbol sym = tree.sym;
2485
2486 if (tree.name == names._class) {
2487 code.emitLdc((LoadableConstant)checkDimension(tree.pos(), tree.selected.type));
2488 result = items.makeStackItem(pt);
2489 return;
2490 }
2491
2492 Symbol ssym = TreeInfo.symbol(tree.selected);
2493
2494 // Are we selecting via super?
2495 boolean selectSuper =
2496 ssym != null && (ssym.kind == TYP || ssym.name == names._super);
2497
2498 // Are we accessing a member of the superclass in an access method
2499 // resulting from a qualified super?
2500 boolean accessSuper = isAccessSuper(env.enclMethod);
2501
2502 Item base = (selectSuper)
2503 ? items.makeSuperItem()
2504 : genExpr(tree.selected, tree.selected.type);
2505
2506 if (sym.kind == VAR && ((VarSymbol) sym).getConstValue() != null) {
2507 // We are seeing a variable that is constant but its selecting
2508 // expression is not.
2509 if ((sym.flags() & STATIC) != 0) {
2510 if (!selectSuper && (ssym == null || ssym.kind != TYP))
|