1 /*
2 * Copyright (c) 1999, 2026, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26 package com.sun.tools.javac.jvm;
27
28 import java.util.HashMap;
29 import java.util.Map;
30 import java.util.Set;
31
32 import com.sun.tools.javac.jvm.PoolConstant.LoadableConstant;
33 import com.sun.tools.javac.tree.TreeInfo.PosKind;
34 import com.sun.tools.javac.util.*;
35 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
36 import com.sun.tools.javac.util.List;
37 import com.sun.tools.javac.code.*;
38 import com.sun.tools.javac.code.Attribute.TypeCompound;
39 import com.sun.tools.javac.code.Symbol.VarSymbol;
40 import com.sun.tools.javac.comp.*;
41 import com.sun.tools.javac.tree.*;
42
43 import com.sun.tools.javac.code.Symbol.*;
44 import com.sun.tools.javac.code.Type.*;
45 import com.sun.tools.javac.jvm.Code.*;
46 import com.sun.tools.javac.jvm.Items.*;
47 import com.sun.tools.javac.resources.CompilerProperties.Errors;
48 import com.sun.tools.javac.tree.JCTree.*;
49
50 import static com.sun.tools.javac.code.Flags.*;
51 import static com.sun.tools.javac.code.Kinds.Kind.*;
52 import static com.sun.tools.javac.code.TypeTag.*;
53 import static com.sun.tools.javac.jvm.ByteCodes.*;
54 import static com.sun.tools.javac.jvm.CRTFlags.*;
55 import static com.sun.tools.javac.main.Option.*;
56 import static com.sun.tools.javac.tree.JCTree.Tag.*;
57
58 /** This pass maps flat Java (i.e. without inner classes) to bytecodes.
59 *
60 * <p><b>This is NOT part of any supported API.
61 * If you write code that depends on this, you do so at your own risk.
62 * This code and its internal interfaces are subject to change or
63 * deletion without notice.</b>
64 */
65 public class Gen extends JCTree.Visitor {
66 protected static final Context.Key<Gen> genKey = new Context.Key<>();
67
68 private final Log log;
69 private final Symtab syms;
70 private final Check chk;
71 private final Resolve rs;
72 private final TreeMaker make;
73 private final Names names;
74 private final Target target;
75 private final String accessDollar;
76 private final Types types;
77 private final Lower lower;
78 private final Annotate annotate;
79 private final StringConcat concat;
80 private final LocalProxyVarsGen localProxyVarsGen;
81
82 /** Format of stackmap tables to be generated. */
83 private final Code.StackMapFormat stackMap;
84
85 /** A type that serves as the expected type for all method expressions.
86 */
87 private final Type methodType;
88
89 public static Gen instance(Context context) {
90 Gen instance = context.get(genKey);
91 if (instance == null)
92 instance = new Gen(context);
93 return instance;
94 }
95
96 /** Constant pool writer, set by genClass.
97 */
98 final PoolWriter poolWriter;
99
100 private final UnsetFieldsInfo unsetFieldsInfo;
101
102 @SuppressWarnings("this-escape")
103 protected Gen(Context context) {
104 context.put(genKey, this);
105
106 names = Names.instance(context);
107 log = Log.instance(context);
108 syms = Symtab.instance(context);
109 chk = Check.instance(context);
110 rs = Resolve.instance(context);
111 make = TreeMaker.instance(context);
112 target = Target.instance(context);
113 types = Types.instance(context);
114 concat = StringConcat.instance(context);
115 localProxyVarsGen = LocalProxyVarsGen.instance(context);
116
117 methodType = new MethodType(null, null, null, syms.methodClass);
118 accessDollar = "access" + target.syntheticNameChar();
119 lower = Lower.instance(context);
120
121 Options options = Options.instance(context);
122 lineDebugInfo =
123 options.isUnset(G_CUSTOM) ||
124 options.isSet(G_CUSTOM, "lines");
125 varDebugInfo =
126 options.isUnset(G_CUSTOM)
127 ? options.isSet(G)
128 : options.isSet(G_CUSTOM, "vars");
129 genCrt = options.isSet(XJCOV);
130 debugCode = options.isSet("debug.code");
131 disableVirtualizedPrivateInvoke = options.isSet("disableVirtualizedPrivateInvoke");
132 poolWriter = new PoolWriter(types, names);
133 unsetFieldsInfo = UnsetFieldsInfo.instance(context);
134
135 // ignore cldc because we cannot have both stackmap formats
136 this.stackMap = StackMapFormat.JSR202;
137 annotate = Annotate.instance(context);
138 qualifiedSymbolCache = new HashMap<>();
139 Preview preview = Preview.instance(context);
140 Source source = Source.instance(context);
141 allowValueClasses = (!preview.isPreview(Source.Feature.VALUE_CLASSES) || preview.isEnabled()) &&
142 Source.Feature.VALUE_CLASSES.allowedInSource(source);
143 }
144
145 /** Switches
146 */
147 private final boolean lineDebugInfo;
148 private final boolean varDebugInfo;
149 private final boolean genCrt;
150 private final boolean debugCode;
151 private boolean disableVirtualizedPrivateInvoke;
152 private final boolean allowValueClasses;
153
154 /** Code buffer, set by genMethod.
155 */
156 private Code code;
157
158 /** Items structure, set by genMethod.
159 */
160 private Items items;
161
162 /** Environment for symbol lookup, set by genClass
163 */
164 private Env<AttrContext> attrEnv;
165
166 /** The top level tree.
167 */
168 private JCCompilationUnit toplevel;
169
170 /** The number of code-gen errors in this class.
171 */
172 private int nerrs = 0;
173
174 boolean inCondSwitchExpression;
175 Chain switchExpressionTrueChain;
176 Chain switchExpressionFalseChain;
177 List<LocalItem> stackBeforeSwitchExpression;
178 LocalItem switchResult;
179 PatternMatchingCatchConfiguration patternMatchingCatchConfiguration =
180 new PatternMatchingCatchConfiguration(Set.of(), null, null, null);
181
182 /** Cache the symbol to reflect the qualifying type.
183 * key: corresponding type
184 * value: qualified symbol
185 */
186 Map<Type, Symbol> qualifiedSymbolCache;
187
188 /** Generate code to load an integer constant.
189 * @param n The integer to be loaded.
190 */
191 void loadIntConst(int n) {
192 items.makeImmediateItem(syms.intType, n).load();
193 }
194
195 /** The opcode that loads a zero constant of a given type code.
196 * @param tc The given type code (@see ByteCode).
197 */
198 public static int zero(int tc) {
199 switch(tc) {
200 case INTcode: case BYTEcode: case SHORTcode: case CHARcode:
201 return iconst_0;
202 case LONGcode:
203 return lconst_0;
204 case FLOATcode:
205 return fconst_0;
206 case DOUBLEcode:
207 return dconst_0;
208 default:
209 throw new AssertionError("zero");
210 }
211 }
212
213 /** The opcode that loads a one constant of a given type code.
214 * @param tc The given type code (@see ByteCode).
215 */
216 public static int one(int tc) {
217 return zero(tc) + 1;
218 }
219
220 /** Generate code to load -1 of the given type code (either int or long).
221 * @param tc The given type code (@see ByteCode).
222 */
223 void emitMinusOne(int tc) {
224 if (tc == LONGcode) {
225 items.makeImmediateItem(syms.longType, Long.valueOf(-1)).load();
226 } else {
227 code.emitop0(iconst_m1);
228 }
229 }
230
231 /** Construct a symbol to reflect the qualifying type that should
232 * appear in the byte code as per JLS 13.1.
233 *
234 * For {@literal target >= 1.2}: Clone a method with the qualifier as owner (except
235 * for those cases where we need to work around VM bugs).
236 *
237 * For {@literal target <= 1.1}: If qualified variable or method is defined in a
238 * non-accessible class, clone it with the qualifier class as owner.
239 *
240 * @param sym The accessed symbol
241 * @param site The qualifier's type.
242 */
243 Symbol binaryQualifier(Symbol sym, Type site) {
244
245 if (site.hasTag(ARRAY)) {
246 if (sym == syms.lengthVar ||
247 sym.owner != syms.arrayClass)
248 return sym;
249 // array clone can be qualified by the array type in later targets
250 Symbol qualifier;
251 if ((qualifier = qualifiedSymbolCache.get(site)) == null) {
252 qualifier = new ClassSymbol(Flags.PUBLIC, site.tsym.name, site, syms.noSymbol);
253 qualifiedSymbolCache.put(site, qualifier);
254 }
255 return sym.clone(qualifier);
256 }
257
258 if (sym.owner == site.tsym ||
259 (sym.flags() & (STATIC | SYNTHETIC)) == (STATIC | SYNTHETIC)) {
260 return sym;
261 }
262
263 // leave alone methods inherited from Object
264 // JLS 13.1.
265 if (sym.owner == syms.objectType.tsym)
266 return sym;
267
268 return sym.clone(site.tsym);
269 }
270
271 /** Insert a reference to given type in the constant pool,
272 * checking for an array with too many dimensions;
273 * return the reference's index.
274 * @param type The type for which a reference is inserted.
275 */
276 int makeRef(DiagnosticPosition pos, Type type) {
277 return poolWriter.putClass(checkDimension(pos, type));
278 }
279
280 /** Check if the given type is an array with too many dimensions.
281 */
282 private Type checkDimension(DiagnosticPosition pos, Type t) {
283 checkDimensionInternal(pos, t);
284 return t;
285 }
286
287 private void checkDimensionInternal(DiagnosticPosition pos, Type t) {
288 switch (t.getTag()) {
289 case METHOD:
290 checkDimension(pos, t.getReturnType());
291 for (List<Type> args = t.getParameterTypes(); args.nonEmpty(); args = args.tail)
292 checkDimension(pos, args.head);
293 break;
294 case ARRAY:
295 if (types.dimensions(t) > ClassFile.MAX_DIMENSIONS) {
296 log.error(pos, Errors.LimitDimensions);
297 nerrs++;
298 }
299 break;
300 default:
301 break;
302 }
303 }
304
305 /** Create a temporary variable.
306 * @param type The variable's type.
307 */
308 LocalItem makeTemp(Type type) {
309 VarSymbol v = new VarSymbol(Flags.SYNTHETIC,
310 names.empty,
311 type,
312 env.enclMethod.sym);
313 code.newLocal(v);
314 return items.makeLocalItem(v);
315 }
316
317 /** Generate code to call a non-private method or constructor.
318 * @param pos Position to be used for error reporting.
319 * @param site The type of which the method is a member.
320 * @param name The method's name.
321 * @param argtypes The method's argument types.
322 * @param isStatic A flag that indicates whether we call a
323 * static or instance method.
324 */
325 void callMethod(DiagnosticPosition pos,
326 Type site, Name name, List<Type> argtypes,
327 boolean isStatic) {
328 Symbol msym = rs.
329 resolveInternalMethod(pos, attrEnv, site, name, argtypes, null);
330 if (isStatic) items.makeStaticItem(msym).invoke();
331 else items.makeMemberItem(msym, name == names.init).invoke();
332 }
333
334 /** Is the given method definition an access method
335 * resulting from a qualified super? This is signified by an odd
336 * access code.
337 */
338 private boolean isAccessSuper(JCMethodDecl enclMethod) {
339 return
340 (enclMethod.mods.flags & SYNTHETIC) != 0 &&
341 isOddAccessName(enclMethod.name);
342 }
343
344 /** Does given name start with "access$" and end in an odd digit?
345 */
346 private boolean isOddAccessName(Name name) {
347 final String string = name.toString();
348 return
349 string.startsWith(accessDollar) &&
350 (string.charAt(string.length() - 1) & 1) != 0;
351 }
352
353 /* ************************************************************************
354 * Non-local exits
355 *************************************************************************/
356
357 /** Generate code to invoke the finalizer associated with given
358 * environment.
359 * Any calls to finalizers are appended to the environments `cont' chain.
360 * Mark beginning of gap in catch all range for finalizer.
361 */
362 void genFinalizer(Env<GenContext> env) {
363 if (code.isAlive() && env.info.finalize != null)
364 env.info.finalize.gen();
365 }
366
367 /** Generate code to call all finalizers of structures aborted by
368 * a non-local
369 * exit. Return target environment of the non-local exit.
370 * @param target The tree representing the structure that's aborted
371 * @param env The environment current at the non-local exit.
372 */
373 Env<GenContext> unwind(JCTree target, Env<GenContext> env) {
374 Env<GenContext> env1 = env;
375 while (true) {
376 genFinalizer(env1);
377 if (env1.tree == target) break;
378 env1 = env1.next;
379 }
380 return env1;
381 }
382
383 /** Mark end of gap in catch-all range for finalizer.
384 * @param env the environment which might contain the finalizer
385 * (if it does, env.info.gaps != null).
386 */
387 void endFinalizerGap(Env<GenContext> env) {
388 if (env.info.gaps != null && env.info.gaps.length() % 2 == 1)
389 env.info.gaps.append(code.curCP());
390 }
391
392 /** Mark end of all gaps in catch-all ranges for finalizers of environments
393 * lying between, and including to two environments.
394 * @param from the most deeply nested environment to mark
395 * @param to the least deeply nested environment to mark
396 */
397 void endFinalizerGaps(Env<GenContext> from, Env<GenContext> to) {
398 Env<GenContext> last = null;
399 while (last != to) {
400 endFinalizerGap(from);
401 last = from;
402 from = from.next;
403 }
404 }
405
406 /** Do any of the structures aborted by a non-local exit have
407 * finalizers that require an empty stack?
408 * @param target The tree representing the structure that's aborted
409 * @param env The environment current at the non-local exit.
410 */
411 boolean hasFinally(JCTree target, Env<GenContext> env) {
412 while (env.tree != target) {
413 if (env.tree.hasTag(TRY) && env.info.finalize.hasFinalizer())
414 return true;
415 env = env.next;
416 }
417 return false;
418 }
419
420 /* ************************************************************************
421 * Normalizing class-members.
422 *************************************************************************/
423
424 /** Distribute member initializer code into constructors and {@code <clinit>}
425 * method.
426 * @param defs The list of class member declarations.
427 * @param c The enclosing class.
428 */
429 List<JCTree> normalizeDefs(List<JCTree> defs, ClassSymbol c) {
430 ListBuffer<JCStatement> initCode = new ListBuffer<>();
431 // only used for value classes
432 ListBuffer<JCStatement> initBlocks = new ListBuffer<>();
433 ListBuffer<Attribute.TypeCompound> initTAs = new ListBuffer<>();
434 ListBuffer<JCStatement> clinitCode = new ListBuffer<>();
435 ListBuffer<Attribute.TypeCompound> clinitTAs = new ListBuffer<>();
436 ListBuffer<JCTree> methodDefs = new ListBuffer<>();
437 // Sort definitions into three listbuffers:
438 // - initCode for instance initializers
439 // - clinitCode for class initializers
440 // - methodDefs for method definitions
441 for (List<JCTree> l = defs; l.nonEmpty(); l = l.tail) {
442 JCTree def = l.head;
443 switch (def.getTag()) {
444 case BLOCK:
445 JCBlock block = (JCBlock)def;
446 if ((block.flags & STATIC) != 0)
447 clinitCode.append(block);
448 else if ((block.flags & SYNTHETIC) == 0) {
449 if (c.isValueClass()) {
450 initBlocks.append(block);
451 } else {
452 initCode.append(block);
453 }
454 }
455 break;
456 case METHODDEF:
457 methodDefs.append(def);
458 break;
459 case VARDEF:
460 JCVariableDecl vdef = (JCVariableDecl) def;
461 VarSymbol sym = vdef.sym;
462 checkDimension(vdef.pos(), sym.type);
463 if (vdef.init != null) {
464 if ((sym.flags() & STATIC) == 0) {
465 // Always initialize instance variables.
466 JCStatement init = make.at(vdef.pos()).
467 Assignment(sym, vdef.init);
468 initCode.append(init);
469 init.endpos = vdef.endpos;
470 initTAs.addAll(getAndRemoveNonFieldTAs(sym));
471 } else if (sym.getConstValue() == null) {
472 // Initialize class (static) variables only if
473 // they are not compile-time constants.
474 JCStatement init = make.at(vdef.pos).
475 Assignment(sym, vdef.init);
476 clinitCode.append(init);
477 init.endpos = vdef.endpos;
478 clinitTAs.addAll(getAndRemoveNonFieldTAs(sym));
479 } else {
480 checkStringConstant(vdef.init.pos(), sym.getConstValue());
481 /* if the init contains a reference to an external class, add it to the
482 * constant's pool
483 */
484 vdef.init.accept(classReferenceVisitor);
485 }
486 }
487 break;
488 default:
489 Assert.error();
490 }
491 }
492 // Insert any instance initializers into all constructors.
493 if (initCode.length() != 0 || initBlocks.length() != 0) {
494 initTAs.addAll(c.getInitTypeAttributes());
495 List<Attribute.TypeCompound> initTAlist = initTAs.toList();
496 for (JCTree t : methodDefs) {
497 normalizeMethod((JCMethodDecl)t, initCode.toList(), initBlocks.toList(), initTAlist);
498 }
499 }
500 // If there are class initializers, create a <clinit> method
501 // that contains them as its body.
502 if (clinitCode.length() != 0) {
503 MethodSymbol clinit = new MethodSymbol(
504 STATIC | (c.flags() & STRICTFP),
505 names.clinit,
506 new MethodType(
507 List.nil(), syms.voidType,
508 List.nil(), syms.methodClass),
509 c);
510 c.members().enter(clinit);
511 List<JCStatement> clinitStats = clinitCode.toList();
512 JCBlock block = make.at(clinitStats.head.pos()).Block(0, clinitStats);
513 block.bracePos = TreeInfo.endPos(clinitStats.last());
514 methodDefs.append(make.MethodDef(clinit, block));
515
516 if (!clinitTAs.isEmpty())
517 clinit.appendUniqueTypeAttributes(clinitTAs.toList());
518 if (!c.getClassInitTypeAttributes().isEmpty())
519 clinit.appendUniqueTypeAttributes(c.getClassInitTypeAttributes());
520 }
521 // Return all method definitions.
522 return methodDefs.toList();
523 }
524
525 private List<Attribute.TypeCompound> getAndRemoveNonFieldTAs(VarSymbol sym) {
526 List<TypeCompound> tas = sym.getRawTypeAttributes();
527 ListBuffer<Attribute.TypeCompound> fieldTAs = new ListBuffer<>();
528 ListBuffer<Attribute.TypeCompound> nonfieldTAs = new ListBuffer<>();
529 for (TypeCompound ta : tas) {
530 Assert.check(ta.getPosition().type != TargetType.UNKNOWN);
531 if (ta.getPosition().type == TargetType.FIELD) {
532 fieldTAs.add(ta);
533 } else {
534 nonfieldTAs.add(ta);
535 }
536 }
537 sym.setTypeAttributes(fieldTAs.toList());
538 return nonfieldTAs.toList();
539 }
540
541 /** Check a constant value and report if it is a string that is
542 * too large.
543 */
544 private void checkStringConstant(DiagnosticPosition pos, Object constValue) {
545 if (nerrs != 0 || // only complain about a long string once
546 constValue == null ||
547 !(constValue instanceof String str) ||
548 str.length() < PoolWriter.MAX_STRING_LENGTH)
549 return;
550 log.error(pos, Errors.LimitString);
551 nerrs++;
552 }
553
554 /** Insert instance initializer code into constructors prior to the super() call.
555 * @param md The tree potentially representing a
556 * constructor's definition.
557 * @param initCode The list of instance initializer statements.
558 * @param initTAs Type annotations from the initializer expression.
559 */
560 void normalizeMethod(JCMethodDecl md, List<JCStatement> initCode, List<JCStatement> initBlocks, List<TypeCompound> initTAs) {
561 Set<Symbol> fieldsWithInits;
562 List<JCStatement> inits;
563 if ((fieldsWithInits = localProxyVarsGen.initializersAlreadyInConst.get(md)) != null) {
564 ListBuffer<JCStatement> newInitCode = new ListBuffer<>();
565 for (JCStatement init : initCode) {
566 Symbol sym = ((JCIdent)((JCAssign)((JCExpressionStatement)init).expr).lhs).sym;
567 if (!fieldsWithInits.contains(sym)) {
568 newInitCode.add(init);
569 }
570 }
571 inits = newInitCode.toList();
572 localProxyVarsGen.initializersAlreadyInConst.remove(md);
573 } else {
574 inits = initCode;
575 }
576 if (TreeInfo.isConstructor(md) && TreeInfo.hasConstructorCall(md, names._super)) {
577 // We are seeing a constructor that has a super() call.
578 // Find the super() invocation and append the given initializer code.
579 if (allowValueClasses & (md.sym.owner.isValueClass() || ((md.sym.owner.flags_field & RECORD) != 0))) {
580 rewriteInitializersIfNeeded(md, inits);
581 md.body.stats = inits.appendList(md.body.stats);
582 TreeInfo.mapSuperCalls(md.body, supercall -> make.Block(0, initBlocks.prepend(supercall)));
583 } else {
584 TreeInfo.mapSuperCalls(md.body, supercall -> make.Block(0, inits.prepend(supercall)));
585 }
586
587 if (md.body.bracePos == Position.NOPOS)
588 md.body.bracePos = TreeInfo.endPos(md.body.stats.last());
589
590 md.sym.appendUniqueTypeAttributes(initTAs);
591 }
592 }
593
594 void rewriteInitializersIfNeeded(JCMethodDecl md, List<JCStatement> initCode) {
595 if (lower.initializerOuterThis.containsKey(md.sym.owner)) {
596 InitializerVisitor initializerVisitor = new InitializerVisitor(md, lower.initializerOuterThis.get(md.sym.owner));
597 for (JCStatement init : initCode) {
598 initializerVisitor.scan(init);
599 }
600 }
601 }
602
603 public static class InitializerVisitor extends TreeScanner {
604 JCMethodDecl md;
605 Set<JCExpression> exprSet;
606
607 public InitializerVisitor(JCMethodDecl md, Set<JCExpression> exprSet) {
608 this.md = md;
609 this.exprSet = exprSet;
610 }
611
612 @Override
613 public void visitTree(JCTree tree) {}
614
615 @Override
616 public void visitIdent(JCIdent tree) {
617 if (exprSet.contains(tree)) {
618 for (JCVariableDecl param: md.params) {
619 if (param.name == tree.name &&
620 ((param.sym.flags_field & (MANDATED | NOOUTERTHIS)) == (MANDATED | NOOUTERTHIS))) {
621 tree.sym = param.sym;
622 }
623 }
624 }
625 }
626 }
627
628 /* ************************************************************************
629 * Traversal methods
630 *************************************************************************/
631
632 /** Visitor argument: The current environment.
633 */
634 Env<GenContext> env;
635
636 /** Visitor argument: The expected type (prototype).
637 */
638 Type pt;
639
640 /** Visitor result: The item representing the computed value.
641 */
642 Item result;
643
644 /** Visitor method: generate code for a definition, catching and reporting
645 * any completion failures.
646 * @param tree The definition to be visited.
647 * @param env The environment current at the definition.
648 */
649 public void genDef(JCTree tree, Env<GenContext> env) {
650 Env<GenContext> prevEnv = this.env;
651 try {
652 this.env = env;
653 tree.accept(this);
654 } catch (CompletionFailure ex) {
655 chk.completionError(tree.pos(), ex);
656 } finally {
657 this.env = prevEnv;
658 }
659 }
660
661 /** Derived visitor method: check whether CharacterRangeTable
662 * should be emitted, if so, put a new entry into CRTable
663 * and call method to generate bytecode.
664 * If not, just call method to generate bytecode.
665 * @see #genStat(JCTree, Env)
666 *
667 * @param tree The tree to be visited.
668 * @param env The environment to use.
669 * @param crtFlags The CharacterRangeTable flags
670 * indicating type of the entry.
671 */
672 public void genStat(JCTree tree, Env<GenContext> env, int crtFlags) {
673 if (!genCrt) {
674 genStat(tree, env);
675 return;
676 }
677 int startpc = code.curCP();
678 genStat(tree, env);
679 if (tree.hasTag(Tag.BLOCK)) crtFlags |= CRT_BLOCK;
680 code.crt.put(tree, crtFlags, startpc, code.curCP());
681 }
682
683 /** Derived visitor method: generate code for a statement.
684 */
685 public void genStat(JCTree tree, Env<GenContext> env) {
686 if (code.isAlive()) {
687 code.statBegin(tree.pos);
688 genDef(tree, env);
689 } else if (env.info.isSwitch && tree.hasTag(VARDEF)) {
690 // variables whose declarations are in a switch
691 // can be used even if the decl is unreachable.
692 code.newLocal(((JCVariableDecl) tree).sym);
693 }
694 }
695
696 /** Derived visitor method: check whether CharacterRangeTable
697 * should be emitted, if so, put a new entry into CRTable
698 * and call method to generate bytecode.
699 * If not, just call method to generate bytecode.
700 * @see #genStats(List, Env)
701 *
702 * @param trees The list of trees to be visited.
703 * @param env The environment to use.
704 * @param crtFlags The CharacterRangeTable flags
705 * indicating type of the entry.
706 */
707 public void genStats(List<JCStatement> trees, Env<GenContext> env, int crtFlags) {
708 if (!genCrt) {
709 genStats(trees, env);
710 return;
711 }
712 if (trees.length() == 1) { // mark one statement with the flags
713 genStat(trees.head, env, crtFlags | CRT_STATEMENT);
714 } else {
715 int startpc = code.curCP();
716 genStats(trees, env);
717 code.crt.put(trees, crtFlags, startpc, code.curCP());
718 }
719 }
720
721 /** Derived visitor method: generate code for a list of statements.
722 */
723 public void genStats(List<? extends JCTree> trees, Env<GenContext> env) {
724 for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
725 genStat(l.head, env, CRT_STATEMENT);
726 }
727
728 /** Derived visitor method: check whether CharacterRangeTable
729 * should be emitted, if so, put a new entry into CRTable
730 * and call method to generate bytecode.
731 * If not, just call method to generate bytecode.
732 * @see #genCond(JCTree,boolean)
733 *
734 * @param tree The tree to be visited.
735 * @param crtFlags The CharacterRangeTable flags
736 * indicating type of the entry.
737 */
738 public CondItem genCond(JCTree tree, int crtFlags) {
739 if (!genCrt) return genCond(tree, false);
740 int startpc = code.curCP();
741 CondItem item = genCond(tree, (crtFlags & CRT_FLOW_CONTROLLER) != 0);
742 code.crt.put(tree, crtFlags, startpc, code.curCP());
743 return item;
744 }
745
746 /** Derived visitor method: generate code for a boolean
747 * expression in a control-flow context.
748 * @param _tree The expression to be visited.
749 * @param markBranches The flag to indicate that the condition is
750 * a flow controller so produced conditions
751 * should contain a proper tree to generate
752 * CharacterRangeTable branches for them.
753 */
754 public CondItem genCond(JCTree _tree, boolean markBranches) {
755 JCTree inner_tree = TreeInfo.skipParens(_tree);
756 if (inner_tree.hasTag(CONDEXPR)) {
757 JCConditional tree = (JCConditional)inner_tree;
758 CondItem cond = genCond(tree.cond, CRT_FLOW_CONTROLLER);
759 if (cond.isTrue()) {
760 code.resolve(cond.trueJumps);
761 CondItem result = genCond(tree.truepart, CRT_FLOW_TARGET);
762 if (markBranches) result.tree = tree.truepart;
763 return result;
764 }
765 if (cond.isFalse()) {
766 code.resolve(cond.falseJumps);
767 CondItem result = genCond(tree.falsepart, CRT_FLOW_TARGET);
768 if (markBranches) result.tree = tree.falsepart;
769 return result;
770 }
771 Chain secondJumps = cond.jumpFalse();
772 code.resolve(cond.trueJumps);
773 CondItem first = genCond(tree.truepart, CRT_FLOW_TARGET);
774 if (markBranches) first.tree = tree.truepart;
775 Chain falseJumps = first.jumpFalse();
776 code.resolve(first.trueJumps);
777 Chain trueJumps = code.branch(goto_);
778 code.resolve(secondJumps);
779 CondItem second = genCond(tree.falsepart, CRT_FLOW_TARGET);
780 CondItem result = items.makeCondItem(second.opcode,
781 Code.mergeChains(trueJumps, second.trueJumps),
782 Code.mergeChains(falseJumps, second.falseJumps));
783 if (markBranches) result.tree = tree.falsepart;
784 return result;
785 } else if (inner_tree.hasTag(SWITCH_EXPRESSION)) {
786 code.resolvePending();
787
788 boolean prevInCondSwitchExpression = inCondSwitchExpression;
789 Chain prevSwitchExpressionTrueChain = switchExpressionTrueChain;
790 Chain prevSwitchExpressionFalseChain = switchExpressionFalseChain;
791 try {
792 inCondSwitchExpression = true;
793 switchExpressionTrueChain = null;
794 switchExpressionFalseChain = null;
795 try {
796 doHandleSwitchExpression((JCSwitchExpression) inner_tree);
797 } catch (CompletionFailure ex) {
798 chk.completionError(_tree.pos(), ex);
799 code.state.stacksize = 1;
800 }
801 CondItem result = items.makeCondItem(goto_,
802 switchExpressionTrueChain,
803 switchExpressionFalseChain);
804 if (markBranches) result.tree = _tree;
805 return result;
806 } finally {
807 inCondSwitchExpression = prevInCondSwitchExpression;
808 switchExpressionTrueChain = prevSwitchExpressionTrueChain;
809 switchExpressionFalseChain = prevSwitchExpressionFalseChain;
810 }
811 } else if (inner_tree.hasTag(LETEXPR) && ((LetExpr) inner_tree).needsCond) {
812 code.resolvePending();
813
814 LetExpr tree = (LetExpr) inner_tree;
815 int limit = code.nextreg;
816 int prevLetExprStart = code.setLetExprStackPos(code.state.stacksize);
817 try {
818 genStats(tree.defs, env);
819 } finally {
820 code.setLetExprStackPos(prevLetExprStart);
821 }
822 CondItem result = genCond(tree.expr, markBranches);
823 code.endScopes(limit);
824 //make sure variables defined in the let expression are not included
825 //in the defined variables for jumps that go outside of this let
826 //expression:
827 undefineVariablesInChain(result.falseJumps, limit);
828 undefineVariablesInChain(result.trueJumps, limit);
829 return result;
830 } else {
831 CondItem result = genExpr(_tree, syms.booleanType).mkCond();
832 if (markBranches) result.tree = _tree;
833 return result;
834 }
835 }
836 //where:
837 private void undefineVariablesInChain(Chain toClear, int limit) {
838 while (toClear != null) {
839 toClear.state.defined.excludeFrom(limit);
840 toClear = toClear.next;
841 }
842 }
843
844 public Code getCode() {
845 return code;
846 }
847
848 public Items getItems() {
849 return items;
850 }
851
852 public Env<AttrContext> getAttrEnv() {
853 return attrEnv;
854 }
855
856 /** Visitor class for expressions which might be constant expressions.
857 * This class is a subset of TreeScanner. Intended to visit trees pruned by
858 * Lower as long as constant expressions looking for references to any
859 * ClassSymbol. Any such reference will be added to the constant pool so
860 * automated tools can detect class dependencies better.
861 */
862 class ClassReferenceVisitor extends JCTree.Visitor {
863
864 @Override
865 public void visitTree(JCTree tree) {}
866
867 @Override
868 public void visitBinary(JCBinary tree) {
869 tree.lhs.accept(this);
870 tree.rhs.accept(this);
871 }
872
873 @Override
874 public void visitSelect(JCFieldAccess tree) {
875 if (tree.selected.type.hasTag(CLASS)) {
876 makeRef(tree.selected.pos(), tree.selected.type);
877 }
878 }
879
880 @Override
881 public void visitIdent(JCIdent tree) {
882 if (tree.sym.owner instanceof ClassSymbol classSymbol) {
883 poolWriter.putClass(classSymbol);
884 }
885 }
886
887 @Override
888 public void visitConditional(JCConditional tree) {
889 tree.cond.accept(this);
890 tree.truepart.accept(this);
891 tree.falsepart.accept(this);
892 }
893
894 @Override
895 public void visitUnary(JCUnary tree) {
896 tree.arg.accept(this);
897 }
898
899 @Override
900 public void visitParens(JCParens tree) {
901 tree.expr.accept(this);
902 }
903
904 @Override
905 public void visitTypeCast(JCTypeCast tree) {
906 tree.expr.accept(this);
907 }
908 }
909
910 private ClassReferenceVisitor classReferenceVisitor = new ClassReferenceVisitor();
911
912 /** Visitor method: generate code for an expression, catching and reporting
913 * any completion failures.
914 * @param tree The expression to be visited.
915 * @param pt The expression's expected type (proto-type).
916 */
917 public Item genExpr(JCTree tree, Type pt) {
918 if (!code.isAlive()) {
919 return items.makeStackItem(pt);
920 }
921
922 Type prevPt = this.pt;
923 try {
924 if (tree.type.constValue() != null) {
925 // Short circuit any expressions which are constants
926 tree.accept(classReferenceVisitor);
927 checkStringConstant(tree.pos(), tree.type.constValue());
928 Symbol sym = TreeInfo.symbol(tree);
929 if (sym != null && isConstantDynamic(sym)) {
930 result = items.makeDynamicItem(sym);
931 } else {
932 result = items.makeImmediateItem(tree.type, tree.type.constValue());
933 }
934 } else {
935 this.pt = pt;
936 tree.accept(this);
937 }
938 return result.coerce(pt);
939 } catch (CompletionFailure ex) {
940 chk.completionError(tree.pos(), ex);
941 code.state.stacksize = 1;
942 return items.makeStackItem(pt);
943 } finally {
944 this.pt = prevPt;
945 }
946 }
947
948 public boolean isConstantDynamic(Symbol sym) {
949 return sym.kind == VAR &&
950 sym instanceof DynamicVarSymbol dynamicVarSymbol &&
951 dynamicVarSymbol.isDynamic();
952 }
953
954 /** Derived visitor method: generate code for a list of method arguments.
955 * @param trees The argument expressions to be visited.
956 * @param pts The expression's expected types (i.e. the formal parameter
957 * types of the invoked method).
958 */
959 public void genArgs(List<JCExpression> trees, List<Type> pts) {
960 for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail) {
961 genExpr(l.head, pts.head).load();
962 pts = pts.tail;
963 }
964 // require lists be of same length
965 Assert.check(pts.isEmpty());
966 }
967
968 /* ************************************************************************
969 * Visitor methods for statements and definitions
970 *************************************************************************/
971
972 /** Thrown when the byte code size exceeds limit.
973 */
974 public static class CodeSizeOverflow extends RuntimeException {
975 private static final long serialVersionUID = 0;
976 public CodeSizeOverflow() {}
977 }
978
979 public void visitMethodDef(JCMethodDecl tree) {
980 // Create a new local environment that points pack at method
981 // definition.
982 Env<GenContext> localEnv = env.dup(tree);
983 localEnv.enclMethod = tree;
984 // The expected type of every return statement in this method
985 // is the method's return type.
986 this.pt = tree.sym.erasure(types).getReturnType();
987
988 checkDimension(tree.pos(), tree.sym.erasure(types));
989 genMethod(tree, localEnv, false);
990 }
991 //where
992 /** Generate code for a method.
993 * @param tree The tree representing the method definition.
994 * @param env The environment current for the method body.
995 * @param fatcode A flag that indicates whether all jumps are
996 * within 32K. We first invoke this method under
997 * the assumption that fatcode == false, i.e. all
998 * jumps are within 32K. If this fails, fatcode
999 * is set to true and we try again.
1000 */
1001 void genMethod(JCMethodDecl tree, Env<GenContext> env, boolean fatcode) {
1002 MethodSymbol meth = tree.sym;
1003 int extras = 0;
1004 // Count up extra parameters
1005 if (meth.isConstructor()) {
1006 extras++;
1007 if (meth.enclClass().isInner() &&
1008 !meth.enclClass().isStatic()) {
1009 extras++;
1010 }
1011 } else if ((tree.mods.flags & STATIC) == 0) {
1012 extras++;
1013 }
1014 // System.err.println("Generating " + meth + " in " + meth.owner); //DEBUG
1015 if (Code.width(types.erasure(env.enclMethod.sym.type).getParameterTypes()) + extras >
1016 ClassFile.MAX_PARAMETERS) {
1017 log.error(tree.pos(), Errors.LimitParameters);
1018 nerrs++;
1019 }
1020
1021 else if (tree.body != null) {
1022 // Create a new code structure and initialize it.
1023 int startpcCrt = initCode(tree, env, fatcode);
1024 Set<VarSymbol> prevUnsetFields = code.currentUnsetFields;
1025 if (meth.isConstructor()) {
1026 code.currentUnsetFields = unsetFieldsInfo.getUnsetFields(env.enclClass.sym, tree.body);
1027 code.initialUnsetFields = unsetFieldsInfo.getUnsetFields(env.enclClass.sym, tree.body);
1028 }
1029
1030 try {
1031 genStat(tree.body, env);
1032 } catch (CodeSizeOverflow e) {
1033 // Failed due to code limit, try again with jsr/ret
1034 startpcCrt = initCode(tree, env, fatcode);
1035 genStat(tree.body, env);
1036 } finally {
1037 code.currentUnsetFields = prevUnsetFields;
1038 }
1039
1040 if (code.state.stacksize != 0) {
1041 log.error(tree.body.pos(), Errors.StackSimError(tree.sym));
1042 throw new AssertionError();
1043 }
1044
1045 // If last statement could complete normally, insert a
1046 // return at the end.
1047 if (code.isAlive()) {
1048 code.statBegin(TreeInfo.endPos(tree.body));
1049 if (env.enclMethod == null ||
1050 env.enclMethod.sym.type.getReturnType().hasTag(VOID)) {
1051 code.emitop0(return_);
1052 } else {
1053 // sometime dead code seems alive (4415991);
1054 // generate a small loop instead
1055 int startpc = code.entryPoint();
1056 CondItem c = items.makeCondItem(goto_);
1057 code.resolve(c.jumpTrue(), startpc);
1058 }
1059 }
1060 if (genCrt)
1061 code.crt.put(tree.body,
1062 CRT_BLOCK,
1063 startpcCrt,
1064 code.curCP());
1065
1066 code.endScopes(0);
1067
1068 // If we exceeded limits, panic
1069 if (code.checkLimits(tree.pos(), log)) {
1070 nerrs++;
1071 return;
1072 }
1073
1074 // If we generated short code but got a long jump, do it again
1075 // with fatCode = true.
1076 if (!fatcode && code.fatcode) genMethod(tree, env, true);
1077
1078 // Clean up
1079 if(stackMap == StackMapFormat.JSR202) {
1080 code.lastFrame = null;
1081 code.frameBeforeLast = null;
1082 }
1083
1084 // Compress exception table
1085 code.compressCatchTable();
1086
1087 // Fill in type annotation positions for exception parameters
1088 code.fillExceptionParameterPositions();
1089 }
1090 }
1091
1092 private int initCode(JCMethodDecl tree, Env<GenContext> env, boolean fatcode) {
1093 MethodSymbol meth = tree.sym;
1094
1095 // Create a new code structure.
1096 meth.code = code = new Code(meth,
1097 fatcode,
1098 lineDebugInfo ? toplevel.lineMap : null,
1099 varDebugInfo,
1100 stackMap,
1101 debugCode,
1102 genCrt ? new CRTable(tree) : null,
1103 syms,
1104 types,
1105 poolWriter,
1106 allowValueClasses);
1107 items = new Items(poolWriter, code, syms, types);
1108 if (code.debugCode) {
1109 System.err.println(meth + " for body " + tree);
1110 }
1111
1112 // If method is not static, create a new local variable address
1113 // for `this'.
1114 if ((tree.mods.flags & STATIC) == 0) {
1115 Type selfType = meth.owner.type;
1116 if (meth.isConstructor() && selfType != syms.objectType)
1117 selfType = UninitializedType.uninitializedThis(selfType);
1118 code.setDefined(
1119 code.newLocal(
1120 new VarSymbol(FINAL, names._this, selfType, meth.owner)));
1121 }
1122
1123 // Mark all parameters as defined from the beginning of
1124 // the method.
1125 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
1126 checkDimension(l.head.pos(), l.head.sym.type);
1127 code.setDefined(code.newLocal(l.head.sym));
1128 }
1129
1130 // Get ready to generate code for method body.
1131 int startpcCrt = genCrt ? code.curCP() : 0;
1132 code.entryPoint();
1133
1134 // Suppress initial stackmap
1135 code.pendingStackMap = false;
1136
1137 return startpcCrt;
1138 }
1139
1140 public void visitVarDef(JCVariableDecl tree) {
1141 VarSymbol v = tree.sym;
1142 if (tree.init != null) {
1143 checkStringConstant(tree.init.pos(), v.getConstValue());
1144 if (v.getConstValue() == null || varDebugInfo) {
1145 Assert.check(code.isStatementStart());
1146 code.newLocal(v);
1147 genExpr(tree.init, v.erasure(types)).load();
1148 items.makeLocalItem(v).store();
1149 Assert.check(code.isStatementStart());
1150 }
1151 } else {
1152 code.newLocal(v);
1153 }
1154 checkDimension(tree.pos(), v.type);
1155 }
1156
1157 public void visitSkip(JCSkip tree) {
1158 }
1159
1160 public void visitBlock(JCBlock tree) {
1161 /* this method is heavily invoked, as expected, for deeply nested blocks, if blocks doesn't happen to have
1162 * patterns there will be an unnecessary tax on memory consumption every time this method is executed, for this
1163 * reason we have created helper methods and here at a higher level we just discriminate depending on the
1164 * presence, or not, of patterns in a given block
1165 */
1166 if (tree.patternMatchingCatch != null) {
1167 visitBlockWithPatterns(tree);
1168 } else {
1169 internalVisitBlock(tree);
1170 }
1171 }
1172
1173 private void visitBlockWithPatterns(JCBlock tree) {
1174 PatternMatchingCatchConfiguration prevConfiguration = patternMatchingCatchConfiguration;
1175 try {
1176 patternMatchingCatchConfiguration =
1177 new PatternMatchingCatchConfiguration(tree.patternMatchingCatch.calls2Handle(),
1178 new ListBuffer<int[]>(),
1179 tree.patternMatchingCatch.handler(),
1180 code.state.dup());
1181 internalVisitBlock(tree);
1182 } finally {
1183 generatePatternMatchingCatch(env);
1184 patternMatchingCatchConfiguration = prevConfiguration;
1185 }
1186 }
1187
1188 private void generatePatternMatchingCatch(Env<GenContext> env) {
1189 if (patternMatchingCatchConfiguration.handler != null &&
1190 !patternMatchingCatchConfiguration.ranges.isEmpty()) {
1191 Chain skipCatch = code.branch(goto_);
1192 JCCatch handler = patternMatchingCatchConfiguration.handler();
1193 code.entryPoint(patternMatchingCatchConfiguration.startState(),
1194 handler.param.sym.type);
1195 genPatternMatchingCatch(handler,
1196 env,
1197 patternMatchingCatchConfiguration.ranges.toList());
1198 code.resolve(skipCatch);
1199 }
1200 }
1201
1202 private void internalVisitBlock(JCBlock tree) {
1203 int limit = code.nextreg;
1204 Env<GenContext> localEnv = env.dup(tree, new GenContext());
1205 genStats(tree.stats, localEnv);
1206 // End the scope of all block-local variables in variable info.
1207 if (!env.tree.hasTag(METHODDEF)) {
1208 code.statBegin(tree.bracePos);
1209 code.endScopes(limit);
1210 code.pendingStatPos = Position.NOPOS;
1211 }
1212 }
1213
1214 public void visitDoLoop(JCDoWhileLoop tree) {
1215 genLoop(tree, tree.body, tree.cond, List.nil(), false);
1216 }
1217
1218 public void visitWhileLoop(JCWhileLoop tree) {
1219 genLoop(tree, tree.body, tree.cond, List.nil(), true);
1220 }
1221
1222 public void visitForLoop(JCForLoop tree) {
1223 int limit = code.nextreg;
1224 genStats(tree.init, env);
1225 genLoop(tree, tree.body, tree.cond, tree.step, true);
1226 code.endScopes(limit);
1227 }
1228 //where
1229 /** Generate code for a loop.
1230 * @param loop The tree representing the loop.
1231 * @param body The loop's body.
1232 * @param cond The loop's controlling condition.
1233 * @param step "Step" statements to be inserted at end of
1234 * each iteration.
1235 * @param testFirst True if the loop test belongs before the body.
1236 */
1237 private void genLoop(JCStatement loop,
1238 JCStatement body,
1239 JCExpression cond,
1240 List<JCExpressionStatement> step,
1241 boolean testFirst) {
1242 Set<VarSymbol> prevCodeUnsetFields = code.currentUnsetFields;
1243 try {
1244 genLoopHelper(loop, body, cond, step, testFirst);
1245 } finally {
1246 code.currentUnsetFields = prevCodeUnsetFields;
1247 }
1248 }
1249
1250 private void genLoopHelper(JCStatement loop,
1251 JCStatement body,
1252 JCExpression cond,
1253 List<JCExpressionStatement> step,
1254 boolean testFirst) {
1255 Env<GenContext> loopEnv = env.dup(loop, new GenContext());
1256 int startpc = code.entryPoint();
1257 if (testFirst) { //while or for loop
1258 CondItem c;
1259 if (cond != null) {
1260 code.statBegin(cond.pos);
1261 Assert.check(code.isStatementStart());
1262 c = genCond(TreeInfo.skipParens(cond), CRT_FLOW_CONTROLLER);
1263 } else {
1264 c = items.makeCondItem(goto_);
1265 }
1266 Chain loopDone = c.jumpFalse();
1267 code.resolve(c.trueJumps);
1268 Assert.check(code.isStatementStart());
1269 genStat(body, loopEnv, CRT_STATEMENT | CRT_FLOW_TARGET);
1270 code.resolve(loopEnv.info.cont);
1271 genStats(step, loopEnv);
1272 code.resolve(code.branch(goto_), startpc);
1273 code.resolve(loopDone);
1274 } else {
1275 genStat(body, loopEnv, CRT_STATEMENT | CRT_FLOW_TARGET);
1276 code.resolve(loopEnv.info.cont);
1277 genStats(step, loopEnv);
1278 if (code.isAlive()) {
1279 CondItem c;
1280 if (cond != null) {
1281 code.statBegin(cond.pos);
1282 Assert.check(code.isStatementStart());
1283 c = genCond(TreeInfo.skipParens(cond), CRT_FLOW_CONTROLLER);
1284 } else {
1285 c = items.makeCondItem(goto_);
1286 }
1287 code.resolve(c.jumpTrue(), startpc);
1288 Assert.check(code.isStatementStart());
1289 code.resolve(c.falseJumps);
1290 }
1291 }
1292 code.resolve(loopEnv.info.exit);
1293 }
1294
1295 public void visitForeachLoop(JCEnhancedForLoop tree) {
1296 throw new AssertionError(); // should have been removed by Lower.
1297 }
1298
1299 public void visitLabelled(JCLabeledStatement tree) {
1300 Env<GenContext> localEnv = env.dup(tree, new GenContext());
1301 genStat(tree.body, localEnv, CRT_STATEMENT);
1302 code.resolve(localEnv.info.exit);
1303 }
1304
1305 public void visitSwitch(JCSwitch tree) {
1306 handleSwitch(tree, tree.selector, tree.cases, tree.patternSwitch);
1307 }
1308
1309 @Override
1310 public void visitSwitchExpression(JCSwitchExpression tree) {
1311 code.resolvePending();
1312 boolean prevInCondSwitchExpression = inCondSwitchExpression;
1313 Set<VarSymbol> prevCodeUnsetFields = code.currentUnsetFields;
1314 try {
1315 inCondSwitchExpression = false;
1316 doHandleSwitchExpression(tree);
1317 } finally {
1318 inCondSwitchExpression = prevInCondSwitchExpression;
1319 code.currentUnsetFields = prevCodeUnsetFields;
1320 }
1321 result = items.makeStackItem(pt);
1322 }
1323
1324 private void doHandleSwitchExpression(JCSwitchExpression tree) {
1325 List<LocalItem> prevStackBeforeSwitchExpression = stackBeforeSwitchExpression;
1326 LocalItem prevSwitchResult = switchResult;
1327 int limit = code.nextreg;
1328 try {
1329 stackBeforeSwitchExpression = List.nil();
1330 switchResult = null;
1331 if (hasTry(tree)) {
1332 //if the switch expression contains try-catch, the catch handlers need to have
1333 //an empty stack. So stash whole stack to local variables, and restore it before
1334 //breaks:
1335 while (code.state.stacksize > 0) {
1336 Type type = code.state.peek();
1337 Name varName = names.fromString(target.syntheticNameChar() +
1338 "stack" +
1339 target.syntheticNameChar() +
1340 tree.pos +
1341 target.syntheticNameChar() +
1342 code.state.stacksize);
1343 VarSymbol var = new VarSymbol(Flags.SYNTHETIC, varName, type,
1344 this.env.enclMethod.sym);
1345 LocalItem item = items.new LocalItem(type, code.newLocal(var));
1346 stackBeforeSwitchExpression = stackBeforeSwitchExpression.prepend(item);
1347 item.store();
1348 }
1349 switchResult = makeTemp(tree.type);
1350 }
1351 int prevLetExprStart = code.setLetExprStackPos(code.state.stacksize);
1352 try {
1353 handleSwitch(tree, tree.selector, tree.cases, tree.patternSwitch);
1354 } finally {
1355 code.setLetExprStackPos(prevLetExprStart);
1356 }
1357 } finally {
1358 stackBeforeSwitchExpression = prevStackBeforeSwitchExpression;
1359 switchResult = prevSwitchResult;
1360 code.endScopes(limit);
1361 }
1362 }
1363 //where:
1364 private boolean hasTry(JCSwitchExpression tree) {
1365 class HasTryScanner extends TreeScanner {
1366 private boolean hasTry;
1367
1368 @Override
1369 public void visitTry(JCTry tree) {
1370 hasTry = true;
1371 }
1372
1373 @Override
1374 public void visitSynchronized(JCSynchronized tree) {
1375 hasTry = true;
1376 }
1377
1378 @Override
1379 public void visitClassDef(JCClassDecl tree) {
1380 }
1381
1382 @Override
1383 public void visitLambda(JCLambda tree) {
1384 }
1385 };
1386
1387 HasTryScanner hasTryScanner = new HasTryScanner();
1388
1389 hasTryScanner.scan(tree);
1390 return hasTryScanner.hasTry;
1391 }
1392
1393 private void handleSwitch(JCTree swtch, JCExpression selector, List<JCCase> cases,
1394 boolean patternSwitch) {
1395 Set<VarSymbol> prevCodeUnsetFields = code.currentUnsetFields;
1396 try {
1397 handleSwitchHelper(swtch, selector, cases, patternSwitch);
1398 } finally {
1399 code.currentUnsetFields = prevCodeUnsetFields;
1400 }
1401 }
1402
1403 void handleSwitchHelper(JCTree swtch, JCExpression selector, List<JCCase> cases,
1404 boolean patternSwitch) {
1405 int limit = code.nextreg;
1406 Assert.check(!selector.type.hasTag(CLASS));
1407 int switchStart = patternSwitch ? code.entryPoint() : -1;
1408 int startpcCrt = genCrt ? code.curCP() : 0;
1409 Assert.check(code.isStatementStart());
1410 Item sel = genExpr(selector, syms.intType);
1411 if (cases.isEmpty()) {
1412 // We are seeing: switch <sel> {}
1413 sel.load().drop();
1414 if (genCrt)
1415 code.crt.put(TreeInfo.skipParens(selector),
1416 CRT_FLOW_CONTROLLER, startpcCrt, code.curCP());
1417 } else {
1418 // We are seeing a nonempty switch.
1419 sel.load();
1420 if (genCrt)
1421 code.crt.put(TreeInfo.skipParens(selector),
1422 CRT_FLOW_CONTROLLER, startpcCrt, code.curCP());
1423 Env<GenContext> switchEnv = env.dup(swtch, new GenContext());
1424 switchEnv.info.isSwitch = true;
1425
1426 // Compute number of labels and minimum and maximum label values.
1427 // For each case, store its label in an array.
1428 int lo = Integer.MAX_VALUE; // minimum label.
1429 int hi = Integer.MIN_VALUE; // maximum label.
1430 int nlabels = 0; // number of labels.
1431
1432 int[] labels = new int[cases.length()]; // the label array.
1433 int defaultIndex = -1; // the index of the default clause.
1434
1435 List<JCCase> l = cases;
1436 for (int i = 0; i < labels.length; i++) {
1437 if (l.head.labels.head instanceof JCConstantCaseLabel constLabel) {
1438 Assert.check(l.head.labels.size() == 1);
1439 int val = ((Number) constLabel.expr.type.constValue()).intValue();
1440 labels[i] = val;
1441 if (val < lo) lo = val;
1442 if (hi < val) hi = val;
1443 nlabels++;
1444 } else {
1445 Assert.check(defaultIndex == -1);
1446 defaultIndex = i;
1447 }
1448 l = l.tail;
1449 }
1450
1451 // Determine whether to issue a tableswitch or a lookupswitch
1452 // instruction.
1453 long table_space_cost = 4 + ((long) hi - lo + 1); // words
1454 long table_time_cost = 3; // comparisons
1455 long lookup_space_cost = 3 + 2 * (long) nlabels;
1456 long lookup_time_cost = nlabels;
1457 int opcode =
1458 nlabels > 0 &&
1459 table_space_cost + 3 * table_time_cost <=
1460 lookup_space_cost + 3 * lookup_time_cost
1461 ?
1462 tableswitch : lookupswitch;
1463
1464 int startpc = code.curCP(); // the position of the selector operation
1465 code.emitop0(opcode);
1466 code.align(4);
1467 int tableBase = code.curCP(); // the start of the jump table
1468 int[] offsets = null; // a table of offsets for a lookupswitch
1469 code.emit4(-1); // leave space for default offset
1470 if (opcode == tableswitch) {
1471 code.emit4(lo); // minimum label
1472 code.emit4(hi); // maximum label
1473 for (long i = lo; i <= hi; i++) { // leave space for jump table
1474 code.emit4(-1);
1475 }
1476 } else {
1477 code.emit4(nlabels); // number of labels
1478 for (int i = 0; i < nlabels; i++) {
1479 code.emit4(-1); code.emit4(-1); // leave space for lookup table
1480 }
1481 offsets = new int[labels.length];
1482 }
1483 Code.State stateSwitch = code.state.dup();
1484 code.markDead();
1485
1486 // For each case do:
1487 l = cases;
1488 for (int i = 0; i < labels.length; i++) {
1489 JCCase c = l.head;
1490 l = l.tail;
1491
1492 int pc = code.entryPoint(stateSwitch);
1493 // Insert offset directly into code or else into the
1494 // offsets table.
1495 if (i != defaultIndex) {
1496 if (opcode == tableswitch) {
1497 code.put4(
1498 tableBase + 4 * (labels[i] - lo + 3),
1499 pc - startpc);
1500 } else {
1501 offsets[i] = pc - startpc;
1502 }
1503 } else {
1504 code.put4(tableBase, pc - startpc);
1505 }
1506
1507 // Generate code for the statements in this case.
1508 genStats(c.stats, switchEnv, CRT_FLOW_TARGET);
1509 }
1510
1511 if (switchEnv.info.cont != null) {
1512 Assert.check(patternSwitch);
1513 code.resolve(switchEnv.info.cont, switchStart);
1514 }
1515
1516 // Resolve all breaks.
1517 code.resolve(switchEnv.info.exit);
1518
1519 // If we have not set the default offset, we do so now.
1520 if (code.get4(tableBase) == -1) {
1521 code.put4(tableBase, code.entryPoint(stateSwitch) - startpc);
1522 }
1523
1524 if (opcode == tableswitch) {
1525 // Let any unfilled slots point to the default case.
1526 int defaultOffset = code.get4(tableBase);
1527 for (long i = lo; i <= hi; i++) {
1528 int t = (int)(tableBase + 4 * (i - lo + 3));
1529 if (code.get4(t) == -1)
1530 code.put4(t, defaultOffset);
1531 }
1532 } else {
1533 // Sort non-default offsets and copy into lookup table.
1534 if (defaultIndex >= 0)
1535 for (int i = defaultIndex; i < labels.length - 1; i++) {
1536 labels[i] = labels[i+1];
1537 offsets[i] = offsets[i+1];
1538 }
1539 if (nlabels > 0)
1540 qsort2(labels, offsets, 0, nlabels - 1);
1541 for (int i = 0; i < nlabels; i++) {
1542 int caseidx = tableBase + 8 * (i + 1);
1543 code.put4(caseidx, labels[i]);
1544 code.put4(caseidx + 4, offsets[i]);
1545 }
1546 }
1547
1548 if (swtch instanceof JCSwitchExpression) {
1549 // Emit line position for the end of a switch expression
1550 code.statBegin(TreeInfo.endPos(swtch));
1551 }
1552 }
1553 code.endScopes(limit);
1554 }
1555 //where
1556 /** Sort (int) arrays of keys and values
1557 */
1558 static void qsort2(int[] keys, int[] values, int lo, int hi) {
1559 int i = lo;
1560 int j = hi;
1561 int pivot = keys[(i+j)/2];
1562 do {
1563 while (keys[i] < pivot) i++;
1564 while (pivot < keys[j]) j--;
1565 if (i <= j) {
1566 int temp1 = keys[i];
1567 keys[i] = keys[j];
1568 keys[j] = temp1;
1569 int temp2 = values[i];
1570 values[i] = values[j];
1571 values[j] = temp2;
1572 i++;
1573 j--;
1574 }
1575 } while (i <= j);
1576 if (lo < j) qsort2(keys, values, lo, j);
1577 if (i < hi) qsort2(keys, values, i, hi);
1578 }
1579
1580 public void visitSynchronized(JCSynchronized tree) {
1581 int limit = code.nextreg;
1582 // Generate code to evaluate lock and save in temporary variable.
1583 final LocalItem lockVar = makeTemp(syms.objectType);
1584 Assert.check(code.isStatementStart());
1585 genExpr(tree.lock, tree.lock.type).load().duplicate();
1586 lockVar.store();
1587
1588 // Generate code to enter monitor.
1589 code.emitop0(monitorenter);
1590 code.state.lock(lockVar.reg);
1591
1592 // Generate code for a try statement with given body, no catch clauses
1593 // in a new environment with the "exit-monitor" operation as finalizer.
1594 final Env<GenContext> syncEnv = env.dup(tree, new GenContext());
1595 syncEnv.info.finalize = new GenFinalizer() {
1596 void gen() {
1597 genLast();
1598 Assert.check(syncEnv.info.gaps.length() % 2 == 0);
1599 syncEnv.info.gaps.append(code.curCP());
1600 }
1601 void genLast() {
1602 if (code.isAlive()) {
1603 lockVar.load();
1604 code.emitop0(monitorexit);
1605 code.state.unlock(lockVar.reg);
1606 }
1607 }
1608 };
1609 syncEnv.info.gaps = new ListBuffer<>();
1610 genTry(tree.body, List.nil(), syncEnv);
1611 code.endScopes(limit);
1612 }
1613
1614 public void visitTry(final JCTry tree) {
1615 // Generate code for a try statement with given body and catch clauses,
1616 // in a new environment which calls the finally block if there is one.
1617 final Env<GenContext> tryEnv = env.dup(tree, new GenContext());
1618 final Env<GenContext> oldEnv = env;
1619 tryEnv.info.finalize = new GenFinalizer() {
1620 void gen() {
1621 Assert.check(tryEnv.info.gaps.length() % 2 == 0);
1622 tryEnv.info.gaps.append(code.curCP());
1623 genLast();
1624 }
1625 void genLast() {
1626 if (tree.finalizer != null)
1627 genStat(tree.finalizer, oldEnv, CRT_BLOCK);
1628 }
1629 boolean hasFinalizer() {
1630 return tree.finalizer != null;
1631 }
1632
1633 @Override
1634 void afterBody() {
1635 if (tree.finalizer != null && (tree.finalizer.flags & BODY_ONLY_FINALIZE) != 0) {
1636 //for body-only finally, remove the GenFinalizer after try body
1637 //so that the finally is not generated to catch bodies:
1638 tryEnv.info.finalize = null;
1639 }
1640 }
1641
1642 };
1643 tryEnv.info.gaps = new ListBuffer<>();
1644 genTry(tree.body, tree.catchers, tryEnv);
1645 }
1646 //where
1647 /** Generate code for a try or synchronized statement
1648 * @param body The body of the try or synchronized statement.
1649 * @param catchers The list of catch clauses.
1650 * @param env The current environment of the body.
1651 */
1652 void genTry(JCTree body, List<JCCatch> catchers, Env<GenContext> env) {
1653 Set<VarSymbol> prevCodeUnsetFields = code.currentUnsetFields;
1654 try {
1655 genTryHelper(body, catchers, env);
1656 } finally {
1657 code.currentUnsetFields = prevCodeUnsetFields;
1658 }
1659 }
1660
1661 void genTryHelper(JCTree body, List<JCCatch> catchers, Env<GenContext> env) {
1662 int limit = code.nextreg;
1663 int startpc = code.curCP();
1664 Code.State stateTry = code.state.dup();
1665 genStat(body, env, CRT_BLOCK);
1666 int endpc = code.curCP();
1667 List<Integer> gaps = env.info.gaps.toList();
1668 code.statBegin(TreeInfo.endPos(body));
1669 genFinalizer(env);
1670 code.statBegin(TreeInfo.endPos(env.tree));
1671 Chain exitChain;
1672 boolean actualTry = env.tree.hasTag(TRY);
1673 if (startpc == endpc && actualTry) {
1674 exitChain = code.branch(dontgoto);
1675 } else {
1676 exitChain = code.branch(goto_);
1677 }
1678 endFinalizerGap(env);
1679 env.info.finalize.afterBody();
1680 boolean hasFinalizer =
1681 env.info.finalize != null &&
1682 env.info.finalize.hasFinalizer();
1683 if (startpc != endpc) for (List<JCCatch> l = catchers; l.nonEmpty(); l = l.tail) {
1684 // start off with exception on stack
1685 code.entryPoint(stateTry, l.head.param.sym.type);
1686 genCatch(l.head, env, startpc, endpc, gaps);
1687 genFinalizer(env);
1688 if (hasFinalizer || l.tail.nonEmpty()) {
1689 code.statBegin(TreeInfo.endPos(env.tree));
1690 exitChain = Code.mergeChains(exitChain,
1691 code.branch(goto_));
1692 }
1693 endFinalizerGap(env);
1694 }
1695 if (hasFinalizer && (startpc != endpc || !actualTry)) {
1696 // Create a new register segment to avoid allocating
1697 // the same variables in finalizers and other statements.
1698 code.newRegSegment();
1699
1700 // Add a catch-all clause.
1701
1702 // start off with exception on stack
1703 int catchallpc = code.entryPoint(stateTry, syms.throwableType);
1704
1705 // Register all exception ranges for catch all clause.
1706 // The range of the catch all clause is from the beginning
1707 // of the try or synchronized block until the present
1708 // code pointer excluding all gaps in the current
1709 // environment's GenContext.
1710 int startseg = startpc;
1711 while (env.info.gaps.nonEmpty()) {
1712 int endseg = env.info.gaps.next().intValue();
1713 registerCatch(body.pos(), startseg, endseg,
1714 catchallpc, 0);
1715 startseg = env.info.gaps.next().intValue();
1716 }
1717 code.statBegin(TreeInfo.finalizerPos(env.tree, PosKind.FIRST_STAT_POS));
1718 code.markStatBegin();
1719
1720 Item excVar = makeTemp(syms.throwableType);
1721 excVar.store();
1722 genFinalizer(env);
1723 code.resolvePending();
1724 code.statBegin(TreeInfo.finalizerPos(env.tree, PosKind.END_POS));
1725 code.markStatBegin();
1726
1727 excVar.load();
1728 registerCatch(body.pos(), startseg,
1729 env.info.gaps.next().intValue(),
1730 catchallpc, 0);
1731 code.emitop0(athrow);
1732 code.markDead();
1733
1734 // If there are jsr's to this finalizer, ...
1735 if (env.info.cont != null) {
1736 // Resolve all jsr's.
1737 code.resolve(env.info.cont);
1738
1739 // Mark statement line number
1740 code.statBegin(TreeInfo.finalizerPos(env.tree, PosKind.FIRST_STAT_POS));
1741 code.markStatBegin();
1742
1743 // Save return address.
1744 LocalItem retVar = makeTemp(syms.throwableType);
1745 retVar.store();
1746
1747 // Generate finalizer code.
1748 env.info.finalize.genLast();
1749
1750 // Return.
1751 code.emitop1w(ret, retVar.reg);
1752 code.markDead();
1753 }
1754 }
1755 // Resolve all breaks.
1756 code.resolve(exitChain);
1757
1758 code.endScopes(limit);
1759 }
1760
1761 /** Generate code for a catch clause.
1762 * @param tree The catch clause.
1763 * @param env The environment current in the enclosing try.
1764 * @param startpc Start pc of try-block.
1765 * @param endpc End pc of try-block.
1766 */
1767 void genCatch(JCCatch tree,
1768 Env<GenContext> env,
1769 int startpc, int endpc,
1770 List<Integer> gaps) {
1771 if (startpc != endpc) {
1772 List<Pair<List<Attribute.TypeCompound>, JCExpression>> catchTypeExprs
1773 = catchTypesWithAnnotations(tree);
1774 while (gaps.nonEmpty()) {
1775 for (Pair<List<Attribute.TypeCompound>, JCExpression> subCatch1 : catchTypeExprs) {
1776 JCExpression subCatch = subCatch1.snd;
1777 int catchType = makeRef(tree.pos(), subCatch.type);
1778 int end = gaps.head.intValue();
1779 registerCatch(tree.pos(),
1780 startpc, end, code.curCP(),
1781 catchType);
1782 for (Attribute.TypeCompound tc : subCatch1.fst) {
1783 tc.position.setCatchInfo(catchType, startpc);
1784 }
1785 }
1786 gaps = gaps.tail;
1787 startpc = gaps.head.intValue();
1788 gaps = gaps.tail;
1789 }
1790 if (startpc < endpc) {
1791 for (Pair<List<Attribute.TypeCompound>, JCExpression> subCatch1 : catchTypeExprs) {
1792 JCExpression subCatch = subCatch1.snd;
1793 int catchType = makeRef(tree.pos(), subCatch.type);
1794 registerCatch(tree.pos(),
1795 startpc, endpc, code.curCP(),
1796 catchType);
1797 for (Attribute.TypeCompound tc : subCatch1.fst) {
1798 tc.position.setCatchInfo(catchType, startpc);
1799 }
1800 }
1801 }
1802 genCatchBlock(tree, env);
1803 }
1804 }
1805 void genPatternMatchingCatch(JCCatch tree,
1806 Env<GenContext> env,
1807 List<int[]> ranges) {
1808 for (int[] range : ranges) {
1809 JCExpression subCatch = tree.param.vartype;
1810 int catchType = makeRef(tree.pos(), subCatch.type);
1811 registerCatch(tree.pos(),
1812 range[0], range[1], code.curCP(),
1813 catchType);
1814 }
1815 genCatchBlock(tree, env);
1816 }
1817 void genCatchBlock(JCCatch tree, Env<GenContext> env) {
1818 VarSymbol exparam = tree.param.sym;
1819 code.statBegin(tree.pos);
1820 code.markStatBegin();
1821 int limit = code.nextreg;
1822 code.newLocal(exparam);
1823 items.makeLocalItem(exparam).store();
1824 code.statBegin(TreeInfo.firstStatPos(tree.body));
1825 genStat(tree.body, env, CRT_BLOCK);
1826 code.endScopes(limit);
1827 code.statBegin(TreeInfo.endPos(tree.body));
1828 }
1829 // where
1830 List<Pair<List<Attribute.TypeCompound>, JCExpression>> catchTypesWithAnnotations(JCCatch tree) {
1831 return TreeInfo.isMultiCatch(tree) ?
1832 catchTypesWithAnnotationsFromMulticatch((JCTypeUnion)tree.param.vartype, tree.param.sym.getRawTypeAttributes()) :
1833 List.of(new Pair<>(tree.param.sym.getRawTypeAttributes(), tree.param.vartype));
1834 }
1835 // where
1836 List<Pair<List<Attribute.TypeCompound>, JCExpression>> catchTypesWithAnnotationsFromMulticatch(JCTypeUnion tree, List<TypeCompound> first) {
1837 List<JCExpression> alts = tree.alternatives;
1838 List<Pair<List<TypeCompound>, JCExpression>> res = List.of(new Pair<>(first, alts.head));
1839 alts = alts.tail;
1840
1841 while(alts != null && alts.head != null) {
1842 JCExpression alt = alts.head;
1843 if (alt instanceof JCAnnotatedType annotatedType) {
1844 res = res.prepend(new Pair<>(annotate.fromAnnotations(annotatedType.annotations), alt));
1845 } else {
1846 res = res.prepend(new Pair<>(List.nil(), alt));
1847 }
1848 alts = alts.tail;
1849 }
1850 return res.reverse();
1851 }
1852
1853 /** Register a catch clause in the "Exceptions" code-attribute.
1854 */
1855 void registerCatch(DiagnosticPosition pos,
1856 int startpc, int endpc,
1857 int handler_pc, int catch_type) {
1858 char startpc1 = (char)startpc;
1859 char endpc1 = (char)endpc;
1860 char handler_pc1 = (char)handler_pc;
1861 if (startpc1 == startpc &&
1862 endpc1 == endpc &&
1863 handler_pc1 == handler_pc) {
1864 code.addCatch(startpc1, endpc1, handler_pc1,
1865 (char)catch_type);
1866 } else {
1867 log.error(pos, Errors.LimitCodeTooLargeForTryStmt);
1868 nerrs++;
1869 }
1870 }
1871
1872 public void visitIf(JCIf tree) {
1873 Set<VarSymbol> prevCodeUnsetFields = code.currentUnsetFields;
1874 try {
1875 visitIfHelper(tree);
1876 } finally {
1877 code.currentUnsetFields = prevCodeUnsetFields;
1878 }
1879 }
1880
1881 public void visitIfHelper(JCIf tree) {
1882 int limit = code.nextreg;
1883 Chain thenExit = null;
1884 Assert.check(code.isStatementStart());
1885 CondItem c = genCond(TreeInfo.skipParens(tree.cond),
1886 CRT_FLOW_CONTROLLER);
1887 Chain elseChain = c.jumpFalse();
1888 Assert.check(code.isStatementStart());
1889 if (!c.isFalse()) {
1890 code.resolve(c.trueJumps);
1891 genStat(tree.thenpart, env, CRT_STATEMENT | CRT_FLOW_TARGET);
1892 thenExit = code.branch(goto_);
1893 }
1894 if (elseChain != null) {
1895 code.resolve(elseChain);
1896 if (tree.elsepart != null) {
1897 genStat(tree.elsepart, env,CRT_STATEMENT | CRT_FLOW_TARGET);
1898 }
1899 }
1900 code.resolve(thenExit);
1901 code.endScopes(limit);
1902 Assert.check(code.isStatementStart());
1903 }
1904
1905 public void visitExec(JCExpressionStatement tree) {
1906 // Optimize x++ to ++x and x-- to --x.
1907 JCExpression e = tree.expr;
1908 switch (e.getTag()) {
1909 case POSTINC:
1910 ((JCUnary) e).setTag(PREINC);
1911 break;
1912 case POSTDEC:
1913 ((JCUnary) e).setTag(PREDEC);
1914 break;
1915 }
1916 Assert.check(code.isStatementStart());
1917 genExpr(tree.expr, tree.expr.type).drop();
1918 Assert.check(code.isStatementStart());
1919 }
1920
1921 public void visitBreak(JCBreak tree) {
1922 Assert.check(code.isStatementStart());
1923 final Env<GenContext> targetEnv = unwindBreak(tree.target);
1924 targetEnv.info.addExit(code.branch(goto_));
1925 endFinalizerGaps(env, targetEnv);
1926 }
1927
1928 public void visitYield(JCYield tree) {
1929 Assert.check(code.isStatementStart());
1930 final Env<GenContext> targetEnv;
1931 if (inCondSwitchExpression) {
1932 CondItem value = genCond(tree.value, CRT_FLOW_TARGET);
1933 Chain falseJumps = value.jumpFalse();
1934
1935 code.resolve(value.trueJumps);
1936 Env<GenContext> localEnv = unwindBreak(tree.target);
1937 reloadStackBeforeSwitchExpr();
1938 Chain trueJumps = code.branch(goto_);
1939
1940 endFinalizerGaps(env, localEnv);
1941
1942 code.resolve(falseJumps);
1943 targetEnv = unwindBreak(tree.target);
1944 reloadStackBeforeSwitchExpr();
1945 falseJumps = code.branch(goto_);
1946
1947 if (switchExpressionTrueChain == null) {
1948 switchExpressionTrueChain = trueJumps;
1949 } else {
1950 switchExpressionTrueChain =
1951 Code.mergeChains(switchExpressionTrueChain, trueJumps);
1952 }
1953 if (switchExpressionFalseChain == null) {
1954 switchExpressionFalseChain = falseJumps;
1955 } else {
1956 switchExpressionFalseChain =
1957 Code.mergeChains(switchExpressionFalseChain, falseJumps);
1958 }
1959 } else {
1960 genExpr(tree.value, pt).load();
1961 if (switchResult != null)
1962 switchResult.store();
1963
1964 targetEnv = unwindBreak(tree.target);
1965
1966 if (code.isAlive()) {
1967 reloadStackBeforeSwitchExpr();
1968 if (switchResult != null)
1969 switchResult.load();
1970
1971 targetEnv.info.addExit(code.branch(goto_));
1972 code.markDead();
1973 }
1974 }
1975 endFinalizerGaps(env, targetEnv);
1976 }
1977 //where:
1978 /** As side-effect, might mark code as dead disabling any further emission.
1979 */
1980 private Env<GenContext> unwindBreak(JCTree target) {
1981 int tmpPos = code.pendingStatPos;
1982 Env<GenContext> targetEnv = unwind(target, env);
1983 code.pendingStatPos = tmpPos;
1984 return targetEnv;
1985 }
1986
1987 private void reloadStackBeforeSwitchExpr() {
1988 for (LocalItem li : stackBeforeSwitchExpression)
1989 li.load();
1990 }
1991
1992 public void visitContinue(JCContinue tree) {
1993 int tmpPos = code.pendingStatPos;
1994 Env<GenContext> targetEnv = unwind(tree.target, env);
1995 code.pendingStatPos = tmpPos;
1996 Assert.check(code.isStatementStart());
1997 targetEnv.info.addCont(code.branch(goto_));
1998 endFinalizerGaps(env, targetEnv);
1999 }
2000
2001 public void visitReturn(JCReturn tree) {
2002 int limit = code.nextreg;
2003 final Env<GenContext> targetEnv;
2004
2005 /* Save and then restore the location of the return in case a finally
2006 * is expanded (with unwind()) in the middle of our bytecodes.
2007 */
2008 int tmpPos = code.pendingStatPos;
2009 if (tree.expr != null) {
2010 Assert.check(code.isStatementStart());
2011 Item r = genExpr(tree.expr, pt).load();
2012 if (hasFinally(env.enclMethod, env)) {
2013 r = makeTemp(pt);
2014 r.store();
2015 }
2016 targetEnv = unwind(env.enclMethod, env);
2017 code.pendingStatPos = tmpPos;
2018 r.load();
2019 code.emitop0(ireturn + Code.truncate(Code.typecode(pt)));
2020 } else {
2021 targetEnv = unwind(env.enclMethod, env);
2022 code.pendingStatPos = tmpPos;
2023 code.emitop0(return_);
2024 }
2025 endFinalizerGaps(env, targetEnv);
2026 code.endScopes(limit);
2027 }
2028
2029 public void visitThrow(JCThrow tree) {
2030 Assert.check(code.isStatementStart());
2031 genExpr(tree.expr, tree.expr.type).load();
2032 code.emitop0(athrow);
2033 Assert.check(code.isStatementStart());
2034 }
2035
2036 /* ************************************************************************
2037 * Visitor methods for expressions
2038 *************************************************************************/
2039
2040 public void visitApply(JCMethodInvocation tree) {
2041 setTypeAnnotationPositions(tree.pos);
2042 // Generate code for method.
2043 Item m = genExpr(tree.meth, methodType);
2044 // Generate code for all arguments, where the expected types are
2045 // the parameters of the method's external type (that is, any implicit
2046 // outer instance of a super(...) call appears as first parameter).
2047 MethodSymbol msym = (MethodSymbol)TreeInfo.symbol(tree.meth);
2048 genArgs(tree.args,
2049 msym.externalType(types).getParameterTypes());
2050 if (!msym.isDynamic()) {
2051 code.statBegin(tree.pos);
2052 }
2053 if (patternMatchingCatchConfiguration.invocations().contains(tree)) {
2054 int start = code.curCP();
2055 result = m.invoke();
2056 patternMatchingCatchConfiguration.ranges().add(new int[] {start, code.curCP()});
2057 } else {
2058 if (msym.isConstructor() && TreeInfo.isConstructorCall(tree)) {
2059 //if this is a this(...) or super(...) call, there is a pending
2060 //"uninitialized this" before this call. One catch handler cannot
2061 //handle exceptions that may come from places with "uninitialized this"
2062 //and (initialized) this, hence generate one set of handlers here
2063 //for the "uninitialized this" case, and another set of handlers
2064 //will be generated at the end of the method for the initialized this,
2065 //if needed:
2066 generatePatternMatchingCatch(env);
2067 result = m.invoke();
2068 patternMatchingCatchConfiguration =
2069 patternMatchingCatchConfiguration.restart(code.state.dup());
2070 } else {
2071 result = m.invoke();
2072 }
2073 }
2074 }
2075
2076 public void visitConditional(JCConditional tree) {
2077 Chain thenExit = null;
2078 code.statBegin(tree.cond.pos);
2079 CondItem c = genCond(tree.cond, CRT_FLOW_CONTROLLER);
2080 Chain elseChain = c.jumpFalse();
2081 if (!c.isFalse()) {
2082 code.resolve(c.trueJumps);
2083 int startpc = genCrt ? code.curCP() : 0;
2084 code.statBegin(tree.truepart.pos);
2085 genExpr(tree.truepart, pt).load();
2086 if (genCrt) code.crt.put(tree.truepart, CRT_FLOW_TARGET,
2087 startpc, code.curCP());
2088 thenExit = code.branch(goto_);
2089 }
2090 if (elseChain != null) {
2091 code.resolve(elseChain);
2092 int startpc = genCrt ? code.curCP() : 0;
2093 code.statBegin(tree.falsepart.pos);
2094 genExpr(tree.falsepart, pt).load();
2095 if (genCrt) code.crt.put(tree.falsepart, CRT_FLOW_TARGET,
2096 startpc, code.curCP());
2097 }
2098 code.resolve(thenExit);
2099 result = items.makeStackItem(pt);
2100 }
2101
2102 private void setTypeAnnotationPositions(int treePos) {
2103 MethodSymbol meth = code.meth;
2104 boolean initOrClinit = code.meth.getKind() == javax.lang.model.element.ElementKind.CONSTRUCTOR
2105 || code.meth.getKind() == javax.lang.model.element.ElementKind.STATIC_INIT;
2106
2107 for (Attribute.TypeCompound ta : meth.getRawTypeAttributes()) {
2108 if (ta.hasUnknownPosition())
2109 ta.tryFixPosition();
2110
2111 if (ta.position.matchesPos(treePos))
2112 ta.position.updatePosOffset(code.cp);
2113 }
2114
2115 if (!initOrClinit)
2116 return;
2117
2118 for (Attribute.TypeCompound ta : meth.owner.getRawTypeAttributes()) {
2119 if (ta.hasUnknownPosition())
2120 ta.tryFixPosition();
2121
2122 if (ta.position.matchesPos(treePos))
2123 ta.position.updatePosOffset(code.cp);
2124 }
2125
2126 ClassSymbol clazz = meth.enclClass();
2127 for (Symbol s : new com.sun.tools.javac.model.FilteredMemberList(clazz.members())) {
2128 if (!s.getKind().isField())
2129 continue;
2130
2131 for (Attribute.TypeCompound ta : s.getRawTypeAttributes()) {
2132 if (ta.hasUnknownPosition())
2133 ta.tryFixPosition();
2134
2135 if (ta.position.matchesPos(treePos))
2136 ta.position.updatePosOffset(code.cp);
2137 }
2138 }
2139 }
2140
2141 public void visitNewClass(JCNewClass tree) {
2142 // Enclosing instances or anonymous classes should have been eliminated
2143 // by now.
2144 Assert.check(tree.encl == null && tree.def == null);
2145 setTypeAnnotationPositions(tree.pos);
2146
2147 code.emitop2(new_, checkDimension(tree.pos(), tree.type), PoolWriter::putClass);
2148 code.emitop0(dup);
2149
2150 // Generate code for all arguments, where the expected types are
2151 // the parameters of the constructor's external type (that is,
2152 // any implicit outer instance appears as first parameter).
2153 genArgs(tree.args, tree.constructor.externalType(types).getParameterTypes());
2154
2155 items.makeMemberItem(tree.constructor, true).invoke();
2156 result = items.makeStackItem(tree.type);
2157 }
2158
2159 public void visitNewArray(JCNewArray tree) {
2160 setTypeAnnotationPositions(tree.pos);
2161
2162 if (tree.elems != null) {
2163 Type elemtype = types.elemtype(tree.type);
2164 loadIntConst(tree.elems.length());
2165 Item arr = makeNewArray(tree.pos(), tree.type, 1);
2166 int i = 0;
2167 for (List<JCExpression> l = tree.elems; l.nonEmpty(); l = l.tail) {
2168 arr.duplicate();
2169 loadIntConst(i);
2170 i++;
2171 genExpr(l.head, elemtype).load();
2172 items.makeIndexedItem(elemtype).store();
2173 }
2174 result = arr;
2175 } else {
2176 for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) {
2177 genExpr(l.head, syms.intType).load();
2178 }
2179 result = makeNewArray(tree.pos(), tree.type, tree.dims.length());
2180 }
2181 }
2182 //where
2183 /** Generate code to create an array with given element type and number
2184 * of dimensions.
2185 */
2186 Item makeNewArray(DiagnosticPosition pos, Type type, int ndims) {
2187 Type elemtype = types.elemtype(type);
2188 if (types.dimensions(type) > ClassFile.MAX_DIMENSIONS) {
2189 log.error(pos, Errors.LimitDimensions);
2190 nerrs++;
2191 }
2192 int elemcode = Code.arraycode(elemtype);
2193 if (elemcode == 0 || (elemcode == 1 && ndims == 1)) {
2194 code.emitAnewarray(makeRef(pos, elemtype), type);
2195 } else if (elemcode == 1) {
2196 code.emitMultianewarray(ndims, makeRef(pos, type), type);
2197 } else {
2198 code.emitNewarray(elemcode, type);
2199 }
2200 return items.makeStackItem(type);
2201 }
2202
2203 public void visitParens(JCParens tree) {
2204 result = genExpr(tree.expr, tree.expr.type);
2205 }
2206
2207 public void visitAssign(JCAssign tree) {
2208 Item l = genExpr(tree.lhs, tree.lhs.type);
2209 genExpr(tree.rhs, tree.lhs.type).load();
2210 Set<VarSymbol> tmpUnsetSymbols = unsetFieldsInfo.getUnsetFields(env.enclClass.sym, tree);
2211 code.currentUnsetFields = tmpUnsetSymbols != null ? tmpUnsetSymbols : code.currentUnsetFields;
2212 if (tree.rhs.type.hasTag(BOT)) {
2213 /* This is just a case of widening reference conversion that per 5.1.5 simply calls
2214 for "regarding a reference as having some other type in a manner that can be proved
2215 correct at compile time."
2216 */
2217 code.state.forceStackTop(tree.lhs.type);
2218 }
2219 result = items.makeAssignItem(l);
2220 }
2221
2222 public void visitAssignop(JCAssignOp tree) {
2223 OperatorSymbol operator = tree.operator;
2224 Item l;
2225 if (operator.opcode == string_add) {
2226 l = concat.makeConcat(tree);
2227 } else {
2228 // Generate code for first expression
2229 l = genExpr(tree.lhs, tree.lhs.type);
2230
2231 // If we have an increment of -32768 to +32767 of a local
2232 // int variable we can use an incr instruction instead of
2233 // proceeding further.
2234 if ((tree.hasTag(PLUS_ASG) || tree.hasTag(MINUS_ASG)) &&
2235 l instanceof LocalItem localItem &&
2236 tree.lhs.type.getTag().isSubRangeOf(INT) &&
2237 tree.rhs.type.getTag().isSubRangeOf(INT) &&
2238 tree.rhs.type.constValue() != null) {
2239 int ival = ((Number) tree.rhs.type.constValue()).intValue();
2240 if (tree.hasTag(MINUS_ASG)) ival = -ival;
2241 localItem.incr(ival);
2242 result = l;
2243 return;
2244 }
2245 // Otherwise, duplicate expression, load one copy
2246 // and complete binary operation.
2247 l.duplicate();
2248 l.coerce(operator.type.getParameterTypes().head).load();
2249 completeBinop(tree.lhs, tree.rhs, operator).coerce(tree.lhs.type);
2250 }
2251 result = items.makeAssignItem(l);
2252 }
2253
2254 public void visitUnary(JCUnary tree) {
2255 OperatorSymbol operator = tree.operator;
2256 if (tree.hasTag(NOT)) {
2257 CondItem od = genCond(tree.arg, false);
2258 result = od.negate();
2259 } else {
2260 Item od = genExpr(tree.arg, operator.type.getParameterTypes().head);
2261 switch (tree.getTag()) {
2262 case POS:
2263 result = od.load();
2264 break;
2265 case NEG:
2266 result = od.load();
2267 code.emitop0(operator.opcode);
2268 break;
2269 case COMPL:
2270 result = od.load();
2271 emitMinusOne(od.typecode);
2272 code.emitop0(operator.opcode);
2273 break;
2274 case PREINC: case PREDEC:
2275 od.duplicate();
2276 if (od instanceof LocalItem localItem &&
2277 (operator.opcode == iadd || operator.opcode == isub)) {
2278 localItem.incr(tree.hasTag(PREINC) ? 1 : -1);
2279 result = od;
2280 } else {
2281 od.load();
2282 code.emitop0(one(od.typecode));
2283 code.emitop0(operator.opcode);
2284 // Perform narrowing primitive conversion if byte,
2285 // char, or short. Fix for 4304655.
2286 if (od.typecode != INTcode &&
2287 Code.truncate(od.typecode) == INTcode)
2288 code.emitop0(int2byte + od.typecode - BYTEcode);
2289 result = items.makeAssignItem(od);
2290 }
2291 break;
2292 case POSTINC: case POSTDEC:
2293 od.duplicate();
2294 if (od instanceof LocalItem localItem &&
2295 (operator.opcode == iadd || operator.opcode == isub)) {
2296 Item res = od.load();
2297 localItem.incr(tree.hasTag(POSTINC) ? 1 : -1);
2298 result = res;
2299 } else {
2300 Item res = od.load();
2301 od.stash(od.typecode);
2302 code.emitop0(one(od.typecode));
2303 code.emitop0(operator.opcode);
2304 // Perform narrowing primitive conversion if byte,
2305 // char, or short. Fix for 4304655.
2306 if (od.typecode != INTcode &&
2307 Code.truncate(od.typecode) == INTcode)
2308 code.emitop0(int2byte + od.typecode - BYTEcode);
2309 od.store();
2310 result = res;
2311 }
2312 break;
2313 case NULLCHK:
2314 result = od.load();
2315 code.emitop0(dup);
2316 genNullCheck(tree);
2317 break;
2318 default:
2319 Assert.error();
2320 }
2321 }
2322 }
2323
2324 /** Generate a null check from the object value at stack top. */
2325 private void genNullCheck(JCTree tree) {
2326 code.statBegin(tree.pos);
2327 callMethod(tree.pos(), syms.objectsType, names.requireNonNull,
2328 List.of(syms.objectType), true);
2329 code.emitop0(pop);
2330 }
2331
2332 public void visitBinary(JCBinary tree) {
2333 OperatorSymbol operator = tree.operator;
2334 if (operator.opcode == string_add) {
2335 result = concat.makeConcat(tree);
2336 } else if (tree.hasTag(AND)) {
2337 CondItem lcond = genCond(tree.lhs, CRT_FLOW_CONTROLLER);
2338 if (!lcond.isFalse()) {
2339 Chain falseJumps = lcond.jumpFalse();
2340 code.resolve(lcond.trueJumps);
2341 CondItem rcond = genCond(tree.rhs, CRT_FLOW_TARGET);
2342 result = items.
2343 makeCondItem(rcond.opcode,
2344 rcond.trueJumps,
2345 Code.mergeChains(falseJumps,
2346 rcond.falseJumps));
2347 } else {
2348 result = lcond;
2349 }
2350 } else if (tree.hasTag(OR)) {
2351 CondItem lcond = genCond(tree.lhs, CRT_FLOW_CONTROLLER);
2352 if (!lcond.isTrue()) {
2353 Chain trueJumps = lcond.jumpTrue();
2354 code.resolve(lcond.falseJumps);
2355 CondItem rcond = genCond(tree.rhs, CRT_FLOW_TARGET);
2356 result = items.
2357 makeCondItem(rcond.opcode,
2358 Code.mergeChains(trueJumps, rcond.trueJumps),
2359 rcond.falseJumps);
2360 } else {
2361 result = lcond;
2362 }
2363 } else {
2364 Item od = genExpr(tree.lhs, operator.type.getParameterTypes().head);
2365 od.load();
2366 result = completeBinop(tree.lhs, tree.rhs, operator);
2367 }
2368 }
2369
2370
2371 /** Complete generating code for operation, with left operand
2372 * already on stack.
2373 * @param lhs The tree representing the left operand.
2374 * @param rhs The tree representing the right operand.
2375 * @param operator The operator symbol.
2376 */
2377 Item completeBinop(JCTree lhs, JCTree rhs, OperatorSymbol operator) {
2378 MethodType optype = (MethodType)operator.type;
2379 int opcode = operator.opcode;
2380 if (opcode >= if_icmpeq && opcode <= if_icmple &&
2381 rhs.type.constValue() instanceof Number number &&
2382 number.intValue() == 0) {
2383 opcode = opcode + (ifeq - if_icmpeq);
2384 } else if (opcode >= if_acmpeq && opcode <= if_acmpne &&
2385 TreeInfo.isNull(rhs)) {
2386 opcode = opcode + (if_acmp_null - if_acmpeq);
2387 } else {
2388 // The expected type of the right operand is
2389 // the second parameter type of the operator, except for
2390 // shifts with long shiftcount, where we convert the opcode
2391 // to a short shift and the expected type to int.
2392 Type rtype = operator.erasure(types).getParameterTypes().tail.head;
2393 if (opcode >= ishll && opcode <= lushrl) {
2394 opcode = opcode + (ishl - ishll);
2395 rtype = syms.intType;
2396 }
2397 // Generate code for right operand and load.
2398 genExpr(rhs, rtype).load();
2399 // If there are two consecutive opcode instructions,
2400 // emit the first now.
2401 if (opcode >= (1 << preShift)) {
2402 code.emitop0(opcode >> preShift);
2403 opcode = opcode & 0xFF;
2404 }
2405 }
2406 if (opcode >= ifeq && opcode <= if_acmpne ||
2407 opcode == if_acmp_null || opcode == if_acmp_nonnull) {
2408 return items.makeCondItem(opcode);
2409 } else {
2410 code.emitop0(opcode);
2411 return items.makeStackItem(optype.restype);
2412 }
2413 }
2414
2415 public void visitTypeCast(JCTypeCast tree) {
2416 result = genExpr(tree.expr, tree.clazz.type).load();
2417 setTypeAnnotationPositions(tree.pos);
2418 // Additional code is only needed if we cast to a reference type
2419 // which is not statically a supertype of the expression's type.
2420 // For basic types, the coerce(...) in genExpr(...) will do
2421 // the conversion.
2422 if (!tree.clazz.type.isPrimitive() &&
2423 !types.isSameType(tree.expr.type, tree.clazz.type) &&
2424 types.asSuper(tree.expr.type, tree.clazz.type.tsym) == null) {
2425 code.emitop2(checkcast, checkDimension(tree.pos(), tree.clazz.type), PoolWriter::putClass);
2426 }
2427 }
2428
2429 public void visitWildcard(JCWildcard tree) {
2430 throw new AssertionError(this.getClass().getName());
2431 }
2432
2433 public void visitTypeTest(JCInstanceOf tree) {
2434 genExpr(tree.expr, tree.expr.type).load();
2435 setTypeAnnotationPositions(tree.pos);
2436 code.emitop2(instanceof_, makeRef(tree.pos(), tree.pattern.type));
2437 result = items.makeStackItem(syms.booleanType);
2438 }
2439
2440 public void visitIndexed(JCArrayAccess tree) {
2441 genExpr(tree.indexed, tree.indexed.type).load();
2442 genExpr(tree.index, syms.intType).load();
2443 result = items.makeIndexedItem(tree.type);
2444 }
2445
2446 public void visitIdent(JCIdent tree) {
2447 Symbol sym = tree.sym;
2448 if (tree.name == names._this || tree.name == names._super) {
2449 Item res = tree.name == names._this
2450 ? items.makeThisItem()
2451 : items.makeSuperItem();
2452 if (sym.kind == MTH) {
2453 // Generate code to address the constructor.
2454 res.load();
2455 res = items.makeMemberItem(sym, true);
2456 }
2457 result = res;
2458 } else if (isInvokeDynamic(sym) || isConstantDynamic(sym)) {
2459 if (isConstantDynamic(sym)) {
2460 setTypeAnnotationPositions(tree.pos);
2461 }
2462 result = items.makeDynamicItem(sym);
2463 } else if (sym.kind == VAR && (sym.owner.kind == MTH || sym.owner.kind == VAR)) {
2464 result = items.makeLocalItem((VarSymbol)sym);
2465 } else if ((sym.flags() & STATIC) != 0) {
2466 if (!isAccessSuper(env.enclMethod))
2467 sym = binaryQualifier(sym, env.enclClass.type);
2468 result = items.makeStaticItem(sym);
2469 } else {
2470 items.makeThisItem().load();
2471 sym = binaryQualifier(sym, env.enclClass.type);
2472 result = items.makeMemberItem(sym, nonVirtualForPrivateAccess(sym));
2473 }
2474 }
2475
2476 //where
2477 private boolean nonVirtualForPrivateAccess(Symbol sym) {
2478 boolean useVirtual = target.hasVirtualPrivateInvoke() &&
2479 !disableVirtualizedPrivateInvoke;
2480 return !useVirtual && ((sym.flags() & PRIVATE) != 0);
2481 }
2482
2483 public void visitSelect(JCFieldAccess tree) {
2484 Symbol sym = tree.sym;
2485
2486 if (tree.name == names._class) {
2487 code.emitLdc((LoadableConstant)checkDimension(tree.pos(), tree.selected.type));
2488 result = items.makeStackItem(pt);
2489 return;
2490 }
2491
2492 Symbol ssym = TreeInfo.symbol(tree.selected);
2493
2494 // Are we selecting via super?
2495 boolean selectSuper =
2496 ssym != null && (ssym.kind == TYP || ssym.name == names._super);
2497
2498 // Are we accessing a member of the superclass in an access method
2499 // resulting from a qualified super?
2500 boolean accessSuper = isAccessSuper(env.enclMethod);
2501
2502 Item base = (selectSuper)
2503 ? items.makeSuperItem()
2504 : genExpr(tree.selected, tree.selected.type);
2505
2506 if (sym.kind == VAR && ((VarSymbol) sym).getConstValue() != null) {
2507 // We are seeing a variable that is constant but its selecting
2508 // expression is not.
2509 if ((sym.flags() & STATIC) != 0) {
2510 if (!selectSuper && (ssym == null || ssym.kind != TYP))
2511 base = base.load();
2512 base.drop();
2513 } else {
2514 base.load();
2515 genNullCheck(tree.selected);
2516 }
2517 result = items.
2518 makeImmediateItem(sym.type, ((VarSymbol) sym).getConstValue());
2519 } else {
2520 if (isInvokeDynamic(sym)) {
2521 result = items.makeDynamicItem(sym);
2522 return;
2523 } else {
2524 sym = binaryQualifier(sym, tree.selected.type);
2525 }
2526 if ((sym.flags() & STATIC) != 0) {
2527 if (!selectSuper && (ssym == null || ssym.kind != TYP))
2528 base = base.load();
2529 base.drop();
2530 result = items.makeStaticItem(sym);
2531 } else {
2532 base.load();
2533 if (sym == syms.lengthVar) {
2534 code.emitop0(arraylength);
2535 result = items.makeStackItem(syms.intType);
2536 } else {
2537 result = items.
2538 makeMemberItem(sym,
2539 nonVirtualForPrivateAccess(sym) ||
2540 selectSuper || accessSuper);
2541 }
2542 }
2543 }
2544 }
2545
2546 public boolean isInvokeDynamic(Symbol sym) {
2547 return sym.kind == MTH && ((MethodSymbol)sym).isDynamic();
2548 }
2549
2550 public void visitLiteral(JCLiteral tree) {
2551 if (tree.type.hasTag(BOT)) {
2552 code.emitop0(aconst_null);
2553 result = items.makeStackItem(tree.type);
2554 }
2555 else
2556 result = items.makeImmediateItem(tree.type, tree.value);
2557 }
2558
2559 public void visitLetExpr(LetExpr tree) {
2560 code.resolvePending();
2561
2562 int limit = code.nextreg;
2563 int prevLetExprStart = code.setLetExprStackPos(code.state.stacksize);
2564 try {
2565 genStats(tree.defs, env);
2566 } finally {
2567 code.setLetExprStackPos(prevLetExprStart);
2568 }
2569 result = genExpr(tree.expr, tree.expr.type).load();
2570 code.endScopes(limit);
2571 }
2572
2573 private void generateReferencesToPrunedTree(ClassSymbol classSymbol) {
2574 List<JCTree> prunedInfo = lower.prunedTree.get(classSymbol);
2575 if (prunedInfo != null) {
2576 for (JCTree prunedTree: prunedInfo) {
2577 prunedTree.accept(classReferenceVisitor);
2578 }
2579 }
2580 }
2581
2582 /* ************************************************************************
2583 * main method
2584 *************************************************************************/
2585
2586 /** Generate code for a class definition.
2587 * @param env The attribution environment that belongs to the
2588 * outermost class containing this class definition.
2589 * We need this for resolving some additional symbols.
2590 * @param cdef The tree representing the class definition.
2591 * @return True if code is generated with no errors.
2592 */
2593 public boolean genClass(Env<AttrContext> env, JCClassDecl cdef) {
2594 try {
2595 attrEnv = env;
2596 ClassSymbol c = cdef.sym;
2597 this.toplevel = env.toplevel;
2598 /* method normalizeDefs() can add references to external classes into the constant pool
2599 */
2600 cdef.defs = normalizeDefs(cdef.defs, c);
2601 generateReferencesToPrunedTree(c);
2602 Env<GenContext> localEnv = new Env<>(cdef, new GenContext());
2603 localEnv.toplevel = env.toplevel;
2604 localEnv.enclClass = cdef;
2605
2606 for (List<JCTree> l = cdef.defs; l.nonEmpty(); l = l.tail) {
2607 genDef(l.head, localEnv);
2608 }
2609 if (poolWriter.size() > PoolWriter.MAX_ENTRIES) {
2610 log.error(cdef.pos(), Errors.LimitPool);
2611 nerrs++;
2612 }
2613 if (nerrs != 0) {
2614 // if errors, discard code
2615 for (List<JCTree> l = cdef.defs; l.nonEmpty(); l = l.tail) {
2616 if (l.head.hasTag(METHODDEF))
2617 ((JCMethodDecl) l.head).sym.code = null;
2618 }
2619 }
2620 cdef.defs = List.nil(); // discard trees
2621 return nerrs == 0;
2622 } finally {
2623 // note: this method does NOT support recursion.
2624 attrEnv = null;
2625 this.env = null;
2626 toplevel = null;
2627 nerrs = 0;
2628 qualifiedSymbolCache.clear();
2629 }
2630 }
2631
2632 /* ************************************************************************
2633 * Auxiliary classes
2634 *************************************************************************/
2635
2636 /** An abstract class for finalizer generation.
2637 */
2638 abstract class GenFinalizer {
2639 /** Generate code to clean up when unwinding. */
2640 abstract void gen();
2641
2642 /** Generate code to clean up at last. */
2643 abstract void genLast();
2644
2645 /** Does this finalizer have some nontrivial cleanup to perform? */
2646 boolean hasFinalizer() { return true; }
2647
2648 /** Should be invoked after the try's body has been visited. */
2649 void afterBody() {}
2650 }
2651
2652 /** code generation contexts,
2653 * to be used as type parameter for environments.
2654 */
2655 final class GenContext {
2656
2657 /**
2658 * The top defined local variables for exit or continue branches to merge into.
2659 * It may contain uninitialized variables to be initialized by branched code,
2660 * so we cannot use Code.State.defined bits.
2661 */
2662 final int limit;
2663
2664 /** A chain for all unresolved jumps that exit the current environment.
2665 */
2666 Chain exit = null;
2667
2668 /** A chain for all unresolved jumps that continue in the
2669 * current environment.
2670 */
2671 Chain cont = null;
2672
2673 /** A closure that generates the finalizer of the current environment.
2674 * Only set for Synchronized and Try contexts.
2675 */
2676 GenFinalizer finalize = null;
2677
2678 /** Is this a switch statement? If so, allocate registers
2679 * even when the variable declaration is unreachable.
2680 */
2681 boolean isSwitch = false;
2682
2683 /** A list buffer containing all gaps in the finalizer range,
2684 * where a catch all exception should not apply.
2685 */
2686 ListBuffer<Integer> gaps = null;
2687
2688 GenContext() {
2689 var code = Gen.this.code;
2690 this.limit = code == null ? 0 : code.nextreg;
2691 }
2692
2693 /** Add given chain to exit chain.
2694 */
2695 void addExit(Chain c) {
2696 if (c != null) {
2697 c.state.defined.excludeFrom(limit);
2698 }
2699 exit = Code.mergeChains(c, exit);
2700 }
2701
2702 /** Add given chain to cont chain.
2703 */
2704 void addCont(Chain c) {
2705 if (c != null) {
2706 c.state.defined.excludeFrom(limit);
2707 }
2708 cont = Code.mergeChains(c, cont);
2709 }
2710 }
2711
2712 record PatternMatchingCatchConfiguration(Set<JCMethodInvocation> invocations,
2713 ListBuffer<int[]> ranges,
2714 JCCatch handler,
2715 State startState) {
2716 public PatternMatchingCatchConfiguration restart(State newState) {
2717 return new PatternMatchingCatchConfiguration(invocations(),
2718 new ListBuffer<int[]>(),
2719 handler(),
2720 newState);
2721 }
2722 }
2723 }