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