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