< prev index next >

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

Print this page


   1 /*
   2  * Copyright (c) 1999, 2019, 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 com.sun.tools.javac.jvm.PoolConstant.LoadableConstant;


  29 import com.sun.tools.javac.tree.TreeInfo.PosKind;
  30 import com.sun.tools.javac.util.*;
  31 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
  32 import com.sun.tools.javac.util.List;
  33 import com.sun.tools.javac.code.*;
  34 import com.sun.tools.javac.code.Attribute.TypeCompound;

  35 import com.sun.tools.javac.code.Symbol.VarSymbol;
  36 import com.sun.tools.javac.comp.*;

  37 import com.sun.tools.javac.tree.*;
  38 
  39 import com.sun.tools.javac.code.Symbol.*;
  40 import com.sun.tools.javac.code.Type.*;
  41 import com.sun.tools.javac.jvm.Code.*;
  42 import com.sun.tools.javac.jvm.Items.*;
  43 import com.sun.tools.javac.resources.CompilerProperties.Errors;
  44 import com.sun.tools.javac.tree.EndPosTable;
  45 import com.sun.tools.javac.tree.JCTree.*;
  46 
  47 import static com.sun.tools.javac.code.Flags.*;
  48 import static com.sun.tools.javac.code.Kinds.Kind.*;
  49 import static com.sun.tools.javac.code.TypeTag.*;
  50 import static com.sun.tools.javac.jvm.ByteCodes.*;
  51 import static com.sun.tools.javac.jvm.CRTFlags.*;
  52 import static com.sun.tools.javac.main.Option.*;
  53 import static com.sun.tools.javac.tree.JCTree.Tag.*;
  54 
  55 /** This pass maps flat Java (i.e. without inner classes) to bytecodes.
  56  *
  57  *  <p><b>This is NOT part of any supported API.
  58  *  If you write code that depends on this, you do so at your own risk.
  59  *  This code and its internal interfaces are subject to change or
  60  *  deletion without notice.</b>
  61  */
  62 public class Gen extends JCTree.Visitor {
  63     protected static final Context.Key<Gen> genKey = new Context.Key<>();
  64 
  65     private final Log log;
  66     private final Symtab syms;
  67     private final Check chk;
  68     private final Resolve rs;
  69     private final TreeMaker make;
  70     private final Names names;
  71     private final Target target;
  72     private final Name accessDollar;
  73     private final Types types;
  74     private final Lower lower;
  75     private final Annotate annotate;
  76     private final StringConcat concat;

  77 
  78     /** Format of stackmap tables to be generated. */
  79     private final Code.StackMapFormat stackMap;
  80 
  81     /** A type that serves as the expected type for all method expressions.
  82      */
  83     private final Type methodType;
  84 
  85     public static Gen instance(Context context) {
  86         Gen instance = context.get(genKey);
  87         if (instance == null)
  88             instance = new Gen(context);
  89         return instance;
  90     }
  91 
  92     /** Constant pool writer, set by genClass.
  93      */
  94     final PoolWriter poolWriter;
  95 
  96     protected Gen(Context context) {
  97         context.put(genKey, this);
  98 
  99         names = Names.instance(context);
 100         log = Log.instance(context);
 101         syms = Symtab.instance(context);
 102         chk = Check.instance(context);
 103         rs = Resolve.instance(context);
 104         make = TreeMaker.instance(context);
 105         target = Target.instance(context);
 106         types = Types.instance(context);
 107         concat = StringConcat.instance(context);

 108 
 109         methodType = new MethodType(null, null, null, syms.methodClass);
 110         accessDollar = names.
 111             fromString("access" + target.syntheticNameChar());
 112         lower = Lower.instance(context);
 113 
 114         Options options = Options.instance(context);
 115         lineDebugInfo =
 116             options.isUnset(G_CUSTOM) ||
 117             options.isSet(G_CUSTOM, "lines");
 118         varDebugInfo =
 119             options.isUnset(G_CUSTOM)
 120             ? options.isSet(G)
 121             : options.isSet(G_CUSTOM, "vars");
 122         genCrt = options.isSet(XJCOV);
 123         debugCode = options.isSet("debug.code");






 124         disableVirtualizedPrivateInvoke = options.isSet("disableVirtualizedPrivateInvoke");
 125         poolWriter = new PoolWriter(types, names);
 126 
 127         // ignore cldc because we cannot have both stackmap formats
 128         this.stackMap = StackMapFormat.JSR202;
 129         annotate = Annotate.instance(context);
 130     }
 131 
 132     /** Switches
 133      */
 134     private final boolean lineDebugInfo;
 135     private final boolean varDebugInfo;
 136     private final boolean genCrt;
 137     private final boolean debugCode;

 138     private boolean disableVirtualizedPrivateInvoke;
 139 
 140     /** Code buffer, set by genMethod.
 141      */
 142     private Code code;
 143 
 144     /** Items structure, set by genMethod.
 145      */
 146     private Items items;
 147 
 148     /** Environment for symbol lookup, set by genClass
 149      */
 150     private Env<AttrContext> attrEnv;
 151 
 152     /** The top level tree.
 153      */
 154     private JCCompilationUnit toplevel;
 155 
 156     /** The number of code-gen errors in this class.
 157      */


 236 
 237         if (sym.owner == site.tsym ||
 238             (sym.flags() & (STATIC | SYNTHETIC)) == (STATIC | SYNTHETIC)) {
 239             return sym;
 240         }
 241 
 242         // leave alone methods inherited from Object
 243         // JLS 13.1.
 244         if (sym.owner == syms.objectType.tsym)
 245             return sym;
 246 
 247         return sym.clone(site.tsym);
 248     }
 249 
 250     /** Insert a reference to given type in the constant pool,
 251      *  checking for an array with too many dimensions;
 252      *  return the reference's index.
 253      *  @param type   The type for which a reference is inserted.
 254      */
 255     int makeRef(DiagnosticPosition pos, Type type) {
 256         return poolWriter.putClass(checkDimension(pos, type));





 257     }
 258 
 259     /** Check if the given type is an array with too many dimensions.
 260      */
 261     private Type checkDimension(DiagnosticPosition pos, Type t) {
 262         checkDimensionInternal(pos, t);
 263         return t;
 264     }
 265 
 266     private void checkDimensionInternal(DiagnosticPosition pos, Type t) {
 267         switch (t.getTag()) {
 268         case METHOD:
 269             checkDimension(pos, t.getReturnType());
 270             for (List<Type> args = t.getParameterTypes(); args.nonEmpty(); args = args.tail)
 271                 checkDimension(pos, args.head);
 272             break;
 273         case ARRAY:
 274             if (types.dimensions(t) > ClassFile.MAX_DIMENSIONS) {
 275                 log.error(pos, Errors.LimitDimensions);
 276                 nerrs++;
 277             }
 278             break;
 279         default:
 280             break;
 281         }
 282     }
 283 
 284     /** Create a tempory variable.
 285      *  @param type   The variable's type.
 286      */


 422                 if ((block.flags & STATIC) != 0)
 423                     clinitCode.append(block);
 424                 else if ((block.flags & SYNTHETIC) == 0)
 425                     initCode.append(block);
 426                 break;
 427             case METHODDEF:
 428                 methodDefs.append(def);
 429                 break;
 430             case VARDEF:
 431                 JCVariableDecl vdef = (JCVariableDecl) def;
 432                 VarSymbol sym = vdef.sym;
 433                 checkDimension(vdef.pos(), sym.type);
 434                 if (vdef.init != null) {
 435                     if ((sym.flags() & STATIC) == 0) {
 436                         // Always initialize instance variables.
 437                         JCStatement init = make.at(vdef.pos()).
 438                             Assignment(sym, vdef.init);
 439                         initCode.append(init);
 440                         endPosTable.replaceTree(vdef, init);
 441                         initTAs.addAll(getAndRemoveNonFieldTAs(sym));
 442                     } else if (sym.getConstValue() == null) {

 443                         // Initialize class (static) variables only if
 444                         // they are not compile-time constants.
 445                         JCStatement init = make.at(vdef.pos).
 446                             Assignment(sym, vdef.init);
 447                         clinitCode.append(init);
 448                         endPosTable.replaceTree(vdef, init);
 449                         clinitTAs.addAll(getAndRemoveNonFieldTAs(sym));
 450                     } else {
 451                         checkStringConstant(vdef.init.pos(), sym.getConstValue());
 452                         /* if the init contains a reference to an external class, add it to the
 453                          * constant's pool
 454                          */
 455                         vdef.init.accept(classReferenceVisitor);
 456                     }
 457                 }
 458                 break;
 459             default:
 460                 Assert.error();
 461             }
 462         }


 500         ListBuffer<Attribute.TypeCompound> nonfieldTAs = new ListBuffer<>();
 501         for (TypeCompound ta : tas) {
 502             Assert.check(ta.getPosition().type != TargetType.UNKNOWN);
 503             if (ta.getPosition().type == TargetType.FIELD) {
 504                 fieldTAs.add(ta);
 505             } else {
 506                 nonfieldTAs.add(ta);
 507             }
 508         }
 509         sym.setTypeAttributes(fieldTAs.toList());
 510         return nonfieldTAs.toList();
 511     }
 512 
 513     /** Check a constant value and report if it is a string that is
 514      *  too large.
 515      */
 516     private void checkStringConstant(DiagnosticPosition pos, Object constValue) {
 517         if (nerrs != 0 || // only complain about a long string once
 518             constValue == null ||
 519             !(constValue instanceof String) ||
 520             ((String)constValue).length() < PoolWriter.MAX_STRING_LENGTH)
 521             return;
 522         log.error(pos, Errors.LimitString);
 523         nerrs++;
 524     }
 525 
 526     /** Insert instance initializer code into initial constructor.
 527      *  @param md        The tree potentially representing a
 528      *                   constructor's definition.
 529      *  @param initCode  The list of instance initializer statements.
 530      *  @param initTAs  Type annotations from the initializer expression.
 531      */
 532     void normalizeMethod(JCMethodDecl md, List<JCStatement> initCode, List<TypeCompound> initTAs) {
 533         if (md.name == names.init && TreeInfo.isInitialConstructor(md)) {
 534             // We are seeing a constructor that does not call another
 535             // constructor of the same class.
 536             List<JCStatement> stats = md.body.stats;
 537             ListBuffer<JCStatement> newstats = new ListBuffer<>();
 538 
 539             if (stats.nonEmpty()) {
 540                 // Copy initializers of synthetic variables generated in


 790 
 791         @Override
 792         public void visitTree(JCTree tree) {}
 793 
 794         @Override
 795         public void visitBinary(JCBinary tree) {
 796             tree.lhs.accept(this);
 797             tree.rhs.accept(this);
 798         }
 799 
 800         @Override
 801         public void visitSelect(JCFieldAccess tree) {
 802             if (tree.selected.type.hasTag(CLASS)) {
 803                 makeRef(tree.selected.pos(), tree.selected.type);
 804             }
 805         }
 806 
 807         @Override
 808         public void visitIdent(JCIdent tree) {
 809             if (tree.sym.owner instanceof ClassSymbol) {
 810                 poolWriter.putClass((ClassSymbol)tree.sym.owner);
 811             }
 812         }
 813 
 814         @Override
 815         public void visitConditional(JCConditional tree) {
 816             tree.cond.accept(this);
 817             tree.truepart.accept(this);
 818             tree.falsepart.accept(this);
 819         }
 820 
 821         @Override
 822         public void visitUnary(JCUnary tree) {
 823             tree.arg.accept(this);
 824         }
 825 
 826         @Override
 827         public void visitParens(JCParens tree) {
 828             tree.expr.accept(this);
 829         }
 830 


 851                 Symbol sym = TreeInfo.symbol(tree);
 852                 if (sym != null && isConstantDynamic(sym)) {
 853                     result = items.makeDynamicItem(sym);
 854                 } else {
 855                     result = items.makeImmediateItem(tree.type, tree.type.constValue());
 856                 }
 857             } else {
 858                 this.pt = pt;
 859                 tree.accept(this);
 860             }
 861             return result.coerce(pt);
 862         } catch (CompletionFailure ex) {
 863             chk.completionError(tree.pos(), ex);
 864             code.state.stacksize = 1;
 865             return items.makeStackItem(pt);
 866         } finally {
 867             this.pt = prevPt;
 868         }
 869     }
 870 
 871     public boolean isConstantDynamic(Symbol sym) {
 872         return sym.kind == VAR &&
 873                 sym instanceof DynamicVarSymbol &&
 874                 ((DynamicVarSymbol)sym).isDynamic();
 875     }
 876 
 877     /** Derived visitor method: generate code for a list of method arguments.
 878      *  @param trees    The argument expressions to be visited.
 879      *  @param pts      The expression's expected types (i.e. the formal parameter
 880      *                  types of the invoked method).
 881      */
 882     public void genArgs(List<JCExpression> trees, List<Type> pts) {
 883         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail) {
 884             genExpr(l.head, pts.head).load();
 885             pts = pts.tail;
 886         }
 887         // require lists be of same length
 888         Assert.check(pts.isEmpty());
 889     }
 890 
 891 /* ************************************************************************
 892  * Visitor methods for statements and definitions
 893  *************************************************************************/
 894 
 895     /** Thrown when the byte code size exceeds limit.
 896      */


1002 
1003                 // Fill in type annotation positions for exception parameters
1004                 code.fillExceptionParameterPositions();
1005             }
1006         }
1007 
1008         private int initCode(JCMethodDecl tree, Env<GenContext> env, boolean fatcode) {
1009             MethodSymbol meth = tree.sym;
1010 
1011             // Create a new code structure.
1012             meth.code = code = new Code(meth,
1013                                         fatcode,
1014                                         lineDebugInfo ? toplevel.lineMap : null,
1015                                         varDebugInfo,
1016                                         stackMap,
1017                                         debugCode,
1018                                         genCrt ? new CRTable(tree, env.toplevel.endPositions)
1019                                                : null,
1020                                         syms,
1021                                         types,
1022                                         poolWriter);
1023             items = new Items(poolWriter, code, syms, types);
1024             if (code.debugCode) {
1025                 System.err.println(meth + " for body " + tree);
1026             }
1027 
1028             // If method is not static, create a new local variable address
1029             // for `this'.
1030             if ((tree.mods.flags & STATIC) == 0) {
1031                 Type selfType = meth.owner.type;
1032                 if (meth.isConstructor() && selfType != syms.objectType)
1033                     selfType = UninitializedType.uninitializedThis(selfType);
1034                 code.setDefined(
1035                         code.newLocal(
1036                             new VarSymbol(FINAL, names._this, selfType, meth.owner)));
1037             }
1038 
1039             // Mark all parameters as defined from the beginning of
1040             // the method.
1041             for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
1042                 checkDimension(l.head.pos(), l.head.sym.type);
1043                 code.setDefined(code.newLocal(l.head.sym));
1044             }
1045 
1046             // Get ready to generate code for method body.
1047             int startpcCrt = genCrt ? code.curCP() : 0;
1048             code.entryPoint();
1049 
1050             // Suppress initial stackmap
1051             code.pendingStackMap = false;
1052 
1053             return startpcCrt;
1054         }
1055 
1056     public void visitVarDef(JCVariableDecl tree) {
1057         VarSymbol v = tree.sym;
1058         if (tree.init != null) {
1059             checkStringConstant(tree.init.pos(), v.getConstValue());
1060             if (v.getConstValue() == null || varDebugInfo) {



1061                 Assert.check(code.isStatementStart());
1062                 code.newLocal(v);
1063                 genExpr(tree.init, v.erasure(types)).load();
1064                 items.makeLocalItem(v).store();
1065                 Assert.check(code.isStatementStart());
1066             }
1067         } else {
1068             code.newLocal(v);
1069         }
1070         checkDimension(tree.pos(), v.type);
1071     }
1072 
1073     public void visitSkip(JCSkip tree) {
1074     }
1075 
1076     public void visitBlock(JCBlock tree) {
1077         int limit = code.nextreg;
1078         Env<GenContext> localEnv = env.dup(tree, new GenContext());
1079         genStats(tree.stats, localEnv);
1080         // End the scope of all block-local variables in variable info.


1794             code.pendingStatPos = tmpPos;
1795             code.emitop0(return_);
1796         }
1797         endFinalizerGaps(env, targetEnv);
1798         code.endScopes(limit);
1799     }
1800 
1801     public void visitThrow(JCThrow tree) {
1802         Assert.check(code.isStatementStart());
1803         genExpr(tree.expr, tree.expr.type).load();
1804         code.emitop0(athrow);
1805         Assert.check(code.isStatementStart());
1806     }
1807 
1808 /* ************************************************************************
1809  * Visitor methods for expressions
1810  *************************************************************************/
1811 
1812     public void visitApply(JCMethodInvocation tree) {
1813         setTypeAnnotationPositions(tree.pos);
1814         // Generate code for method.
1815         Item m = genExpr(tree.meth, methodType);
1816         // Generate code for all arguments, where the expected types are
1817         // the parameters of the method's external type (that is, any implicit
1818         // outer instance of a super(...) call appears as first parameter).
1819         MethodSymbol msym = (MethodSymbol)TreeInfo.symbol(tree.meth);
1820         genArgs(tree.args,
1821                 msym.externalType(types).getParameterTypes());
1822         if (!msym.isDynamic()) {
1823             code.statBegin(tree.pos);




















1824         }
1825         result = m.invoke();
1826     }
1827 
1828     public void visitConditional(JCConditional tree) {
1829         Chain thenExit = null;
1830         code.statBegin(tree.cond.pos);
1831         CondItem c = genCond(tree.cond, CRT_FLOW_CONTROLLER);
1832         Chain elseChain = c.jumpFalse();
1833         if (!c.isFalse()) {
1834             code.resolve(c.trueJumps);
1835             int startpc = genCrt ? code.curCP() : 0;
1836             code.statBegin(tree.truepart.pos);
1837             genExpr(tree.truepart, pt).load();
1838             code.state.forceStackTop(tree.type);
1839             if (genCrt) code.crt.put(tree.truepart, CRT_FLOW_TARGET,
1840                                      startpc, code.curCP());
1841             thenExit = code.branch(goto_);
1842         }
1843         if (elseChain != null) {
1844             code.resolve(elseChain);
1845             int startpc = genCrt ? code.curCP() : 0;


1881         for (Symbol s : new com.sun.tools.javac.model.FilteredMemberList(clazz.members())) {
1882             if (!s.getKind().isField())
1883                 continue;
1884 
1885             for (Attribute.TypeCompound ta : s.getRawTypeAttributes()) {
1886                 if (ta.hasUnknownPosition())
1887                     ta.tryFixPosition();
1888 
1889                 if (ta.position.matchesPos(treePos))
1890                     ta.position.updatePosOffset(code.cp);
1891             }
1892         }
1893     }
1894 
1895     public void visitNewClass(JCNewClass tree) {
1896         // Enclosing instances or anonymous classes should have been eliminated
1897         // by now.
1898         Assert.check(tree.encl == null && tree.def == null);
1899         setTypeAnnotationPositions(tree.pos);
1900 
1901         code.emitop2(new_, checkDimension(tree.pos(), tree.type), PoolWriter::putClass);
1902         code.emitop0(dup);
1903 
1904         // Generate code for all arguments, where the expected types are
1905         // the parameters of the constructor's external type (that is,
1906         // any implicit outer instance appears as first parameter).
1907         genArgs(tree.args, tree.constructor.externalType(types).getParameterTypes());
1908 
1909         items.makeMemberItem(tree.constructor, true).invoke();
1910         result = items.makeStackItem(tree.type);
1911     }
1912 
1913     public void visitNewArray(JCNewArray tree) {
1914         setTypeAnnotationPositions(tree.pos);
1915 
1916         if (tree.elems != null) {
1917             Type elemtype = types.elemtype(tree.type);
1918             loadIntConst(tree.elems.length());
1919             Item arr = makeNewArray(tree.pos(), tree.type, 1);
1920             int i = 0;
1921             for (List<JCExpression> l = tree.elems; l.nonEmpty(); l = l.tail) {


2157             }
2158             if (opcode >= ifeq && opcode <= if_acmpne ||
2159                 opcode == if_acmp_null || opcode == if_acmp_nonnull) {
2160                 return items.makeCondItem(opcode);
2161             } else {
2162                 code.emitop0(opcode);
2163                 return items.makeStackItem(optype.restype);
2164             }
2165         }
2166 
2167     public void visitTypeCast(JCTypeCast tree) {
2168         result = genExpr(tree.expr, tree.clazz.type).load();
2169         setTypeAnnotationPositions(tree.pos);
2170         // Additional code is only needed if we cast to a reference type
2171         // which is not statically a supertype of the expression's type.
2172         // For basic types, the coerce(...) in genExpr(...) will do
2173         // the conversion.
2174         if (!tree.clazz.type.isPrimitive() &&
2175            !types.isSameType(tree.expr.type, tree.clazz.type) &&
2176            types.asSuper(tree.expr.type, tree.clazz.type.tsym) == null) {
2177             code.emitop2(checkcast, checkDimension(tree.pos(), tree.clazz.type), PoolWriter::putClass);
2178         }
2179     }
2180 
2181     public void visitWildcard(JCWildcard tree) {
2182         throw new AssertionError(this.getClass().getName());
2183     }
2184 
2185     public void visitTypeTest(JCInstanceOf tree) {
2186         genExpr(tree.expr, tree.expr.type).load();
2187         setTypeAnnotationPositions(tree.pos);
2188         code.emitop2(instanceof_, makeRef(tree.pos(), tree.clazz.type));
2189         result = items.makeStackItem(syms.booleanType);
2190     }
2191 
2192     public void visitIndexed(JCArrayAccess tree) {
2193         genExpr(tree.indexed, tree.indexed.type).load();
2194         genExpr(tree.index, syms.intType).load();
2195         result = items.makeIndexedItem(tree.type);
2196     }
2197 
2198     public void visitIdent(JCIdent tree) {
2199         Symbol sym = tree.sym;
2200         if (tree.name == names._this || tree.name == names._super) {
2201             Item res = tree.name == names._this
2202                 ? items.makeThisItem()
2203                 : items.makeSuperItem();
2204             if (sym.kind == MTH) {
2205                 // Generate code to address the constructor.
2206                 res.load();
2207                 res = items.makeMemberItem(sym, true);
2208             }
2209             result = res;
2210        } else if (isInvokeDynamic(sym) || isConstantDynamic(sym)) {
2211             if (isConstantDynamic(sym)) {
2212                 setTypeAnnotationPositions(tree.pos);
2213             }
2214             result = items.makeDynamicItem(sym);
2215         } else if (sym.kind == VAR && (sym.owner.kind == MTH || sym.owner.kind == VAR)) {
2216             result = items.makeLocalItem((VarSymbol)sym);
2217         } else if ((sym.flags() & STATIC) != 0) {
2218             if (!isAccessSuper(env.enclMethod))
2219                 sym = binaryQualifier(sym, env.enclClass.type);
2220             result = items.makeStaticItem(sym);
2221         } else {
2222             items.makeThisItem().load();
2223             sym = binaryQualifier(sym, env.enclClass.type);
2224             result = items.makeMemberItem(sym, nonVirtualForPrivateAccess(sym));
2225         }
2226     }
2227 
2228     //where
2229     private boolean nonVirtualForPrivateAccess(Symbol sym) {
2230         boolean useVirtual = target.hasVirtualPrivateInvoke() &&
2231                              !disableVirtualizedPrivateInvoke;
2232         return !useVirtual && ((sym.flags() & PRIVATE) != 0);
2233     }
2234 






2235     public void visitSelect(JCFieldAccess tree) {
2236         Symbol sym = tree.sym;
2237 
2238         if (tree.name == names._class) {
2239             code.emitLdc((LoadableConstant)checkDimension(tree.pos(), tree.selected.type));
2240             result = items.makeStackItem(pt);
2241             return;
2242        }
2243 
2244         Symbol ssym = TreeInfo.symbol(tree.selected);
2245 
2246         // Are we selecting via super?
2247         boolean selectSuper =
2248             ssym != null && (ssym.kind == TYP || ssym.name == names._super);
2249 
2250         // Are we accessing a member of the superclass in an access method
2251         // resulting from a qualified super?
2252         boolean accessSuper = isAccessSuper(env.enclMethod);
2253 
2254         Item base = (selectSuper)
2255             ? items.makeSuperItem()
2256             : genExpr(tree.selected, tree.selected.type);
2257 
2258         if (sym.kind == VAR && ((VarSymbol) sym).getConstValue() != null) {
2259             // We are seeing a variable that is constant but its selecting


2292                                        selectSuper || accessSuper);
2293                 }
2294             }
2295         }
2296     }
2297 
2298     public boolean isInvokeDynamic(Symbol sym) {
2299         return sym.kind == MTH && ((MethodSymbol)sym).isDynamic();
2300     }
2301 
2302     public void visitLiteral(JCLiteral tree) {
2303         if (tree.type.hasTag(BOT)) {
2304             code.emitop0(aconst_null);
2305             result = items.makeStackItem(tree.type);
2306         }
2307         else
2308             result = items.makeImmediateItem(tree.type, tree.value);
2309     }
2310 
2311     public void visitLetExpr(LetExpr tree) {
2312         code.resolvePending();
2313 
2314         int limit = code.nextreg;
2315         int prevLetExprStart = code.setLetExprStackPos(code.state.stacksize);
2316         try {
2317             genStats(tree.defs, env);
2318         } finally {
2319             code.setLetExprStackPos(prevLetExprStart);
2320         }
2321         result = genExpr(tree.expr, tree.expr.type).load();
2322         code.endScopes(limit);
2323     }
2324 
2325     private void generateReferencesToPrunedTree(ClassSymbol classSymbol) {
2326         List<JCTree> prunedInfo = lower.prunedTree.get(classSymbol);
2327         if (prunedInfo != null) {
2328             for (JCTree prunedTree: prunedInfo) {
2329                 prunedTree.accept(classReferenceVisitor);
2330             }
2331         }
2332     }
2333 
2334 /* ************************************************************************
2335  * main method
2336  *************************************************************************/
2337 
2338     /** Generate code for a class definition.
2339      *  @param env   The attribution environment that belongs to the
2340      *               outermost class containing this class definition.
2341      *               We need this for resolving some additional symbols.
2342      *  @param cdef  The tree representing the class definition.
2343      *  @return      True if code is generated with no errors.
2344      */
2345     public boolean genClass(Env<AttrContext> env, JCClassDecl cdef) {
2346         try {
2347             attrEnv = env;
2348             ClassSymbol c = cdef.sym;
2349             this.toplevel = env.toplevel;
2350             this.endPosTable = toplevel.endPositions;


2351             /* method normalizeDefs() can add references to external classes into the constant pool
2352              */
2353             cdef.defs = normalizeDefs(cdef.defs, c);
2354             generateReferencesToPrunedTree(c);
2355             Env<GenContext> localEnv = new Env<>(cdef, new GenContext());
2356             localEnv.toplevel = env.toplevel;
2357             localEnv.enclClass = cdef;
2358 
2359             for (List<JCTree> l = cdef.defs; l.nonEmpty(); l = l.tail) {
2360                 genDef(l.head, localEnv);
2361             }
2362             if (poolWriter.size() > PoolWriter.MAX_ENTRIES) {
2363                 log.error(cdef.pos(), Errors.LimitPool);
2364                 nerrs++;
2365             }
2366             if (nerrs != 0) {
2367                 // if errors, discard code
2368                 for (List<JCTree> l = cdef.defs; l.nonEmpty(); l = l.tail) {
2369                     if (l.head.hasTag(METHODDEF))
2370                         ((JCMethodDecl) l.head).sym.code = null;
2371                 }
2372             }
2373             cdef.defs = List.nil(); // discard trees
2374             return nerrs == 0;
2375         } finally {
2376             // note: this method does NOT support recursion.
2377             attrEnv = null;
2378             this.env = null;
2379             toplevel = null;
2380             endPosTable = null;
2381             nerrs = 0;
2382         }


   1 /*
   2  * Copyright (c) 1999, 2018, 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 
  29 import java.util.Optional;
  30 
  31 import com.sun.tools.javac.tree.TreeInfo.PosKind;
  32 import com.sun.tools.javac.util.*;
  33 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
  34 import com.sun.tools.javac.util.List;
  35 import com.sun.tools.javac.code.*;
  36 import com.sun.tools.javac.code.Attribute.TypeCompound;
  37 import com.sun.tools.javac.code.Source.Feature;
  38 import com.sun.tools.javac.code.Symbol.VarSymbol;
  39 import com.sun.tools.javac.comp.*;
  40 import com.sun.tools.javac.resources.CompilerProperties.Errors;
  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.EndPosTable;
  49 import com.sun.tools.javac.tree.JCTree.*;
  50 
  51 import static com.sun.tools.javac.code.Flags.*;
  52 import static com.sun.tools.javac.code.Kinds.Kind.*;
  53 import static com.sun.tools.javac.code.TypeTag.*;
  54 import static com.sun.tools.javac.jvm.ByteCodes.*;
  55 import static com.sun.tools.javac.jvm.CRTFlags.*;
  56 import static com.sun.tools.javac.main.Option.*;
  57 import static com.sun.tools.javac.tree.JCTree.Tag.*;
  58 
  59 /** This pass maps flat Java (i.e. without inner classes) to bytecodes.
  60  *
  61  *  <p><b>This is NOT part of any supported API.
  62  *  If you write code that depends on this, you do so at your own risk.
  63  *  This code and its internal interfaces are subject to change or
  64  *  deletion without notice.</b>
  65  */
  66 public class Gen extends JCTree.Visitor {
  67     protected static final Context.Key<Gen> genKey = new Context.Key<>();
  68 
  69     private final Log log;
  70     private final Symtab syms;
  71     private final Check chk;
  72     private final Resolve rs;
  73     private final TreeMaker make;
  74     private final Names names;
  75     private final Target target;
  76     private final Name accessDollar;
  77     private final Types types;
  78     private final Lower lower;
  79     private final Annotate annotate;
  80     private final StringConcat concat;
  81     private final Constables constables;
  82 
  83     /** Format of stackmap tables to be generated. */
  84     private final Code.StackMapFormat stackMap;
  85 
  86     /** A type that serves as the expected type for all method expressions.
  87      */
  88     private final Type methodType;
  89 
  90     public static Gen instance(Context context) {
  91         Gen instance = context.get(genKey);
  92         if (instance == null)
  93             instance = new Gen(context);
  94         return instance;
  95     }
  96 
  97     /** Constant pool, reset by genClass.
  98      */
  99     private final Pool pool;
 100 
 101     protected Gen(Context context) {
 102         context.put(genKey, this);
 103 
 104         names = Names.instance(context);
 105         log = Log.instance(context);
 106         syms = Symtab.instance(context);
 107         chk = Check.instance(context);
 108         rs = Resolve.instance(context);
 109         make = TreeMaker.instance(context);
 110         target = Target.instance(context);
 111         types = Types.instance(context);
 112         concat = StringConcat.instance(context);
 113         constables = Constables.instance(context);
 114 
 115         methodType = new MethodType(null, null, null, syms.methodClass);
 116         accessDollar = names.
 117             fromString("access" + target.syntheticNameChar());
 118         lower = Lower.instance(context);
 119 
 120         Options options = Options.instance(context);
 121         lineDebugInfo =
 122             options.isUnset(G_CUSTOM) ||
 123             options.isSet(G_CUSTOM, "lines");
 124         varDebugInfo =
 125             options.isUnset(G_CUSTOM)
 126             ? options.isSet(G)
 127             : options.isSet(G_CUSTOM, "vars");
 128         genCrt = options.isSet(XJCOV);
 129         debugCode = options.isSet("debug.code");
 130         // format: -XDfolding=true, which is the default, or -XDfolding=false
 131         String foldingOp = options.get("folding");
 132         Source source = Source.instance(context);
 133         doConstantFold = foldingOp != null ?
 134                 foldingOp.equals("true") :
 135                 Feature.CONSTABLES.allowedInSource(source);
 136         disableVirtualizedPrivateInvoke = options.isSet("disableVirtualizedPrivateInvoke");
 137         pool = new Pool(types);
 138 
 139         // ignore cldc because we cannot have both stackmap formats
 140         this.stackMap = StackMapFormat.JSR202;
 141         annotate = Annotate.instance(context);
 142     }
 143 
 144     /** Switches
 145      */
 146     private final boolean lineDebugInfo;
 147     private final boolean varDebugInfo;
 148     private final boolean genCrt;
 149     private final boolean debugCode;
 150     private final boolean doConstantFold;
 151     private boolean disableVirtualizedPrivateInvoke;
 152 
 153     /** Code buffer, set by genMethod.
 154      */
 155     private Code code;
 156 
 157     /** Items structure, set by genMethod.
 158      */
 159     private Items items;
 160 
 161     /** Environment for symbol lookup, set by genClass
 162      */
 163     private Env<AttrContext> attrEnv;
 164 
 165     /** The top level tree.
 166      */
 167     private JCCompilationUnit toplevel;
 168 
 169     /** The number of code-gen errors in this class.
 170      */


 249 
 250         if (sym.owner == site.tsym ||
 251             (sym.flags() & (STATIC | SYNTHETIC)) == (STATIC | SYNTHETIC)) {
 252             return sym;
 253         }
 254 
 255         // leave alone methods inherited from Object
 256         // JLS 13.1.
 257         if (sym.owner == syms.objectType.tsym)
 258             return sym;
 259 
 260         return sym.clone(site.tsym);
 261     }
 262 
 263     /** Insert a reference to given type in the constant pool,
 264      *  checking for an array with too many dimensions;
 265      *  return the reference's index.
 266      *  @param type   The type for which a reference is inserted.
 267      */
 268     int makeRef(DiagnosticPosition pos, Type type) {
 269         checkDimension(pos, type);
 270         if (type.isAnnotated()) {
 271             return pool.put((Object)type);
 272         } else {
 273             return pool.put(type.hasTag(CLASS) ? (Object)type.tsym : (Object)type);
 274         }
 275     }
 276 
 277     /** Check if the given type is an array with too many dimensions.
 278      */
 279     private void checkDimension(DiagnosticPosition pos, Type t) {





 280         switch (t.getTag()) {
 281         case METHOD:
 282             checkDimension(pos, t.getReturnType());
 283             for (List<Type> args = t.getParameterTypes(); args.nonEmpty(); args = args.tail)
 284                 checkDimension(pos, args.head);
 285             break;
 286         case ARRAY:
 287             if (types.dimensions(t) > ClassFile.MAX_DIMENSIONS) {
 288                 log.error(pos, Errors.LimitDimensions);
 289                 nerrs++;
 290             }
 291             break;
 292         default:
 293             break;
 294         }
 295     }
 296 
 297     /** Create a tempory variable.
 298      *  @param type   The variable's type.
 299      */


 435                 if ((block.flags & STATIC) != 0)
 436                     clinitCode.append(block);
 437                 else if ((block.flags & SYNTHETIC) == 0)
 438                     initCode.append(block);
 439                 break;
 440             case METHODDEF:
 441                 methodDefs.append(def);
 442                 break;
 443             case VARDEF:
 444                 JCVariableDecl vdef = (JCVariableDecl) def;
 445                 VarSymbol sym = vdef.sym;
 446                 checkDimension(vdef.pos(), sym.type);
 447                 if (vdef.init != null) {
 448                     if ((sym.flags() & STATIC) == 0) {
 449                         // Always initialize instance variables.
 450                         JCStatement init = make.at(vdef.pos()).
 451                             Assignment(sym, vdef.init);
 452                         initCode.append(init);
 453                         endPosTable.replaceTree(vdef, init);
 454                         initTAs.addAll(getAndRemoveNonFieldTAs(sym));
 455                     } else if (sym.getConstValue() == null ||
 456                             (doConstantFold && !constables.skipCodeGeneration(vdef))) {
 457                         // Initialize class (static) variables only if
 458                         // they are not compile-time constants.
 459                         JCStatement init = make.at(vdef.pos).
 460                             Assignment(sym, vdef.init);
 461                         clinitCode.append(init);
 462                         endPosTable.replaceTree(vdef, init);
 463                         clinitTAs.addAll(getAndRemoveNonFieldTAs(sym));
 464                     } else {
 465                         checkStringConstant(vdef.init.pos(), sym.getConstValue());
 466                         /* if the init contains a reference to an external class, add it to the
 467                          * constant's pool
 468                          */
 469                         vdef.init.accept(classReferenceVisitor);
 470                     }
 471                 }
 472                 break;
 473             default:
 474                 Assert.error();
 475             }
 476         }


 514         ListBuffer<Attribute.TypeCompound> nonfieldTAs = new ListBuffer<>();
 515         for (TypeCompound ta : tas) {
 516             Assert.check(ta.getPosition().type != TargetType.UNKNOWN);
 517             if (ta.getPosition().type == TargetType.FIELD) {
 518                 fieldTAs.add(ta);
 519             } else {
 520                 nonfieldTAs.add(ta);
 521             }
 522         }
 523         sym.setTypeAttributes(fieldTAs.toList());
 524         return nonfieldTAs.toList();
 525     }
 526 
 527     /** Check a constant value and report if it is a string that is
 528      *  too large.
 529      */
 530     private void checkStringConstant(DiagnosticPosition pos, Object constValue) {
 531         if (nerrs != 0 || // only complain about a long string once
 532             constValue == null ||
 533             !(constValue instanceof String) ||
 534             ((String)constValue).length() < Pool.MAX_STRING_LENGTH)
 535             return;
 536         log.error(pos, Errors.LimitString);
 537         nerrs++;
 538     }
 539 
 540     /** Insert instance initializer code into initial constructor.
 541      *  @param md        The tree potentially representing a
 542      *                   constructor's definition.
 543      *  @param initCode  The list of instance initializer statements.
 544      *  @param initTAs  Type annotations from the initializer expression.
 545      */
 546     void normalizeMethod(JCMethodDecl md, List<JCStatement> initCode, List<TypeCompound> initTAs) {
 547         if (md.name == names.init && TreeInfo.isInitialConstructor(md)) {
 548             // We are seeing a constructor that does not call another
 549             // constructor of the same class.
 550             List<JCStatement> stats = md.body.stats;
 551             ListBuffer<JCStatement> newstats = new ListBuffer<>();
 552 
 553             if (stats.nonEmpty()) {
 554                 // Copy initializers of synthetic variables generated in


 804 
 805         @Override
 806         public void visitTree(JCTree tree) {}
 807 
 808         @Override
 809         public void visitBinary(JCBinary tree) {
 810             tree.lhs.accept(this);
 811             tree.rhs.accept(this);
 812         }
 813 
 814         @Override
 815         public void visitSelect(JCFieldAccess tree) {
 816             if (tree.selected.type.hasTag(CLASS)) {
 817                 makeRef(tree.selected.pos(), tree.selected.type);
 818             }
 819         }
 820 
 821         @Override
 822         public void visitIdent(JCIdent tree) {
 823             if (tree.sym.owner instanceof ClassSymbol) {
 824                 pool.put(tree.sym.owner);
 825             }
 826         }
 827 
 828         @Override
 829         public void visitConditional(JCConditional tree) {
 830             tree.cond.accept(this);
 831             tree.truepart.accept(this);
 832             tree.falsepart.accept(this);
 833         }
 834 
 835         @Override
 836         public void visitUnary(JCUnary tree) {
 837             tree.arg.accept(this);
 838         }
 839 
 840         @Override
 841         public void visitParens(JCParens tree) {
 842             tree.expr.accept(this);
 843         }
 844 


 865                 Symbol sym = TreeInfo.symbol(tree);
 866                 if (sym != null && isConstantDynamic(sym)) {
 867                     result = items.makeDynamicItem(sym);
 868                 } else {
 869                     result = items.makeImmediateItem(tree.type, tree.type.constValue());
 870                 }
 871             } else {
 872                 this.pt = pt;
 873                 tree.accept(this);
 874             }
 875             return result.coerce(pt);
 876         } catch (CompletionFailure ex) {
 877             chk.completionError(tree.pos(), ex);
 878             code.state.stacksize = 1;
 879             return items.makeStackItem(pt);
 880         } finally {
 881             this.pt = prevPt;
 882         }
 883     }
 884 






 885     /** Derived visitor method: generate code for a list of method arguments.
 886      *  @param trees    The argument expressions to be visited.
 887      *  @param pts      The expression's expected types (i.e. the formal parameter
 888      *                  types of the invoked method).
 889      */
 890     public void genArgs(List<JCExpression> trees, List<Type> pts) {
 891         for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail) {
 892             genExpr(l.head, pts.head).load();
 893             pts = pts.tail;
 894         }
 895         // require lists be of same length
 896         Assert.check(pts.isEmpty());
 897     }
 898 
 899 /* ************************************************************************
 900  * Visitor methods for statements and definitions
 901  *************************************************************************/
 902 
 903     /** Thrown when the byte code size exceeds limit.
 904      */


1010 
1011                 // Fill in type annotation positions for exception parameters
1012                 code.fillExceptionParameterPositions();
1013             }
1014         }
1015 
1016         private int initCode(JCMethodDecl tree, Env<GenContext> env, boolean fatcode) {
1017             MethodSymbol meth = tree.sym;
1018 
1019             // Create a new code structure.
1020             meth.code = code = new Code(meth,
1021                                         fatcode,
1022                                         lineDebugInfo ? toplevel.lineMap : null,
1023                                         varDebugInfo,
1024                                         stackMap,
1025                                         debugCode,
1026                                         genCrt ? new CRTable(tree, env.toplevel.endPositions)
1027                                                : null,
1028                                         syms,
1029                                         types,
1030                                         pool);
1031             items = new Items(pool, code, syms, types);
1032             if (code.debugCode) {
1033                 System.err.println(meth + " for body " + tree);
1034             }
1035 
1036             // If method is not static, create a new local variable address
1037             // for `this'.
1038             if ((tree.mods.flags & STATIC) == 0) {
1039                 Type selfType = meth.owner.type;
1040                 if (meth.isConstructor() && selfType != syms.objectType)
1041                     selfType = UninitializedType.uninitializedThis(selfType);
1042                 code.setDefined(
1043                         code.newLocal(
1044                             new VarSymbol(FINAL, names._this, selfType, meth.owner)));
1045             }
1046 
1047             // Mark all parameters as defined from the beginning of
1048             // the method.
1049             for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
1050                 checkDimension(l.head.pos(), l.head.sym.type);
1051                 code.setDefined(code.newLocal(l.head.sym));
1052             }
1053 
1054             // Get ready to generate code for method body.
1055             int startpcCrt = genCrt ? code.curCP() : 0;
1056             code.entryPoint();
1057 
1058             // Suppress initial stackmap
1059             code.pendingStackMap = false;
1060 
1061             return startpcCrt;
1062         }
1063 
1064     public void visitVarDef(JCVariableDecl tree) {
1065         VarSymbol v = tree.sym;
1066         if (tree.init != null) {
1067             checkStringConstant(tree.init.pos(), v.getConstValue());
1068             if (v.getConstValue() == null ||
1069                     varDebugInfo ||
1070                     (doConstantFold && !constables.skipCodeGeneration(tree))) {
1071                 code.newLocal(v);
1072                 Assert.check(code.isStatementStart());
1073                 code.newLocal(v);
1074                 genExpr(tree.init, v.erasure(types)).load();
1075                 items.makeLocalItem(v).store();
1076                 Assert.check(code.isStatementStart());
1077             }
1078         } else {
1079             code.newLocal(v);
1080         }
1081         checkDimension(tree.pos(), v.type);
1082     }
1083 
1084     public void visitSkip(JCSkip tree) {
1085     }
1086 
1087     public void visitBlock(JCBlock tree) {
1088         int limit = code.nextreg;
1089         Env<GenContext> localEnv = env.dup(tree, new GenContext());
1090         genStats(tree.stats, localEnv);
1091         // End the scope of all block-local variables in variable info.


1805             code.pendingStatPos = tmpPos;
1806             code.emitop0(return_);
1807         }
1808         endFinalizerGaps(env, targetEnv);
1809         code.endScopes(limit);
1810     }
1811 
1812     public void visitThrow(JCThrow tree) {
1813         Assert.check(code.isStatementStart());
1814         genExpr(tree.expr, tree.expr.type).load();
1815         code.emitop0(athrow);
1816         Assert.check(code.isStatementStart());
1817     }
1818 
1819 /* ************************************************************************
1820  * Visitor methods for expressions
1821  *************************************************************************/
1822 
1823     public void visitApply(JCMethodInvocation tree) {
1824         setTypeAnnotationPositions(tree.pos);





1825         MethodSymbol msym = (MethodSymbol)TreeInfo.symbol(tree.meth);
1826         Item m;
1827         if (msym.isIntrinsicsLDC()) {
1828             Object constant = ((IntrinsicsLDCMethodSymbol)msym).getConstant();
1829             // primitives special case
1830             if (constant instanceof VarSymbol && ((VarSymbol)constant).name == names.TYPE) {
1831                 m = items.makeStaticItem((Symbol)constant);
1832             } else if (constant instanceof Pool.DynamicVariable) {
1833                 m = items.makeCondyItem((Pool.DynamicVariable)constant);
1834             } else {
1835                 m = items.makeImmediateItem(pt, constant);
1836             }
1837             result = m.coerce(pt).load();
1838         } else {
1839             // Generate code for method.
1840             m = genExpr(tree.meth, methodType);
1841             // Generate code for all arguments, where the expected types are
1842             // the parameters of the method's external type (that is, any implicit
1843             // outer instance of a super(...) call appears as first parameter).
1844             genArgs(tree.args,
1845                     msym.externalType(types).getParameterTypes());
1846             if (!msym.isDynamic()) {
1847                 code.statBegin(tree.pos);
1848             }
1849             result = m.invoke();
1850         }

1851     }
1852 
1853     public void visitConditional(JCConditional tree) {
1854         Chain thenExit = null;
1855         code.statBegin(tree.cond.pos);
1856         CondItem c = genCond(tree.cond, CRT_FLOW_CONTROLLER);
1857         Chain elseChain = c.jumpFalse();
1858         if (!c.isFalse()) {
1859             code.resolve(c.trueJumps);
1860             int startpc = genCrt ? code.curCP() : 0;
1861             code.statBegin(tree.truepart.pos);
1862             genExpr(tree.truepart, pt).load();
1863             code.state.forceStackTop(tree.type);
1864             if (genCrt) code.crt.put(tree.truepart, CRT_FLOW_TARGET,
1865                                      startpc, code.curCP());
1866             thenExit = code.branch(goto_);
1867         }
1868         if (elseChain != null) {
1869             code.resolve(elseChain);
1870             int startpc = genCrt ? code.curCP() : 0;


1906         for (Symbol s : new com.sun.tools.javac.model.FilteredMemberList(clazz.members())) {
1907             if (!s.getKind().isField())
1908                 continue;
1909 
1910             for (Attribute.TypeCompound ta : s.getRawTypeAttributes()) {
1911                 if (ta.hasUnknownPosition())
1912                     ta.tryFixPosition();
1913 
1914                 if (ta.position.matchesPos(treePos))
1915                     ta.position.updatePosOffset(code.cp);
1916             }
1917         }
1918     }
1919 
1920     public void visitNewClass(JCNewClass tree) {
1921         // Enclosing instances or anonymous classes should have been eliminated
1922         // by now.
1923         Assert.check(tree.encl == null && tree.def == null);
1924         setTypeAnnotationPositions(tree.pos);
1925 
1926         code.emitop2(new_, makeRef(tree.pos(), tree.type));
1927         code.emitop0(dup);
1928 
1929         // Generate code for all arguments, where the expected types are
1930         // the parameters of the constructor's external type (that is,
1931         // any implicit outer instance appears as first parameter).
1932         genArgs(tree.args, tree.constructor.externalType(types).getParameterTypes());
1933 
1934         items.makeMemberItem(tree.constructor, true).invoke();
1935         result = items.makeStackItem(tree.type);
1936     }
1937 
1938     public void visitNewArray(JCNewArray tree) {
1939         setTypeAnnotationPositions(tree.pos);
1940 
1941         if (tree.elems != null) {
1942             Type elemtype = types.elemtype(tree.type);
1943             loadIntConst(tree.elems.length());
1944             Item arr = makeNewArray(tree.pos(), tree.type, 1);
1945             int i = 0;
1946             for (List<JCExpression> l = tree.elems; l.nonEmpty(); l = l.tail) {


2182             }
2183             if (opcode >= ifeq && opcode <= if_acmpne ||
2184                 opcode == if_acmp_null || opcode == if_acmp_nonnull) {
2185                 return items.makeCondItem(opcode);
2186             } else {
2187                 code.emitop0(opcode);
2188                 return items.makeStackItem(optype.restype);
2189             }
2190         }
2191 
2192     public void visitTypeCast(JCTypeCast tree) {
2193         result = genExpr(tree.expr, tree.clazz.type).load();
2194         setTypeAnnotationPositions(tree.pos);
2195         // Additional code is only needed if we cast to a reference type
2196         // which is not statically a supertype of the expression's type.
2197         // For basic types, the coerce(...) in genExpr(...) will do
2198         // the conversion.
2199         if (!tree.clazz.type.isPrimitive() &&
2200            !types.isSameType(tree.expr.type, tree.clazz.type) &&
2201            types.asSuper(tree.expr.type, tree.clazz.type.tsym) == null) {
2202             code.emitop2(checkcast, makeRef(tree.pos(), tree.clazz.type));
2203         }
2204     }
2205 
2206     public void visitWildcard(JCWildcard tree) {
2207         throw new AssertionError(this.getClass().getName());
2208     }
2209 
2210     public void visitTypeTest(JCInstanceOf tree) {
2211         genExpr(tree.expr, tree.expr.type).load();
2212         setTypeAnnotationPositions(tree.pos);
2213         code.emitop2(instanceof_, makeRef(tree.pos(), tree.clazz.type));
2214         result = items.makeStackItem(syms.booleanType);
2215     }
2216 
2217     public void visitIndexed(JCArrayAccess tree) {
2218         genExpr(tree.indexed, tree.indexed.type).load();
2219         genExpr(tree.index, syms.intType).load();
2220         result = items.makeIndexedItem(tree.type);
2221     }
2222 
2223     public void visitIdent(JCIdent tree) {
2224         Symbol sym = tree.sym;
2225         if (tree.name == names._this || tree.name == names._super) {
2226             Item res = tree.name == names._this
2227                 ? items.makeThisItem()
2228                 : items.makeSuperItem();
2229             if (sym.kind == MTH) {
2230                 // Generate code to address the constructor.
2231                 res.load();
2232                 res = items.makeMemberItem(sym, true);
2233             }
2234             result = res;
2235         } else if (isInvokeDynamic(sym) || isConstantDynamic(sym)) {
2236             if (isConstantDynamic(sym)) {
2237                 setTypeAnnotationPositions(tree.pos);
2238             }
2239             result = items.makeDynamicItem(sym);
2240         } else if (sym.kind == VAR && (sym.owner.kind == MTH || sym.owner.kind == VAR)) {
2241             result = items.makeLocalItem((VarSymbol)sym);
2242         } else if ((sym.flags() & STATIC) != 0) {
2243             if (!isAccessSuper(env.enclMethod))
2244                 sym = binaryQualifier(sym, env.enclClass.type);
2245             result = items.makeStaticItem(sym);
2246         } else {
2247             items.makeThisItem().load();
2248             sym = binaryQualifier(sym, env.enclClass.type);
2249             result = items.makeMemberItem(sym, nonVirtualForPrivateAccess(sym));
2250         }
2251     }
2252 
2253     //where
2254     private boolean nonVirtualForPrivateAccess(Symbol sym) {
2255         boolean useVirtual = target.hasVirtualPrivateInvoke() &&
2256                              !disableVirtualizedPrivateInvoke;
2257         return !useVirtual && ((sym.flags() & PRIVATE) != 0);
2258     }
2259 
2260     public boolean isConstantDynamic(Symbol sym) {
2261         return sym.kind == VAR &&
2262                 sym instanceof DynamicVarSymbol &&
2263                 ((DynamicVarSymbol)sym).isDynamic();
2264     }
2265 
2266     public void visitSelect(JCFieldAccess tree) {
2267         Symbol sym = tree.sym;
2268 
2269         if (tree.name == names._class) {
2270             code.emitLdc(makeRef(tree.pos(), tree.selected.type));
2271             result = items.makeStackItem(pt);
2272             return;
2273        }
2274 
2275         Symbol ssym = TreeInfo.symbol(tree.selected);
2276 
2277         // Are we selecting via super?
2278         boolean selectSuper =
2279             ssym != null && (ssym.kind == TYP || ssym.name == names._super);
2280 
2281         // Are we accessing a member of the superclass in an access method
2282         // resulting from a qualified super?
2283         boolean accessSuper = isAccessSuper(env.enclMethod);
2284 
2285         Item base = (selectSuper)
2286             ? items.makeSuperItem()
2287             : genExpr(tree.selected, tree.selected.type);
2288 
2289         if (sym.kind == VAR && ((VarSymbol) sym).getConstValue() != null) {
2290             // We are seeing a variable that is constant but its selecting


2323                                        selectSuper || accessSuper);
2324                 }
2325             }
2326         }
2327     }
2328 
2329     public boolean isInvokeDynamic(Symbol sym) {
2330         return sym.kind == MTH && ((MethodSymbol)sym).isDynamic();
2331     }
2332 
2333     public void visitLiteral(JCLiteral tree) {
2334         if (tree.type.hasTag(BOT)) {
2335             code.emitop0(aconst_null);
2336             result = items.makeStackItem(tree.type);
2337         }
2338         else
2339             result = items.makeImmediateItem(tree.type, tree.value);
2340     }
2341 
2342     public void visitLetExpr(LetExpr tree) {


2343         int limit = code.nextreg;
2344         int prevLetExprStart = code.setLetExprStackPos(code.state.stacksize);
2345         try {
2346             genStats(tree.defs, env);
2347         } finally {
2348             code.setLetExprStackPos(prevLetExprStart);
2349         }
2350         result = genExpr(tree.expr, tree.expr.type).load();
2351         code.endScopes(limit);
2352     }
2353 
2354     private void generateReferencesToPrunedTree(ClassSymbol classSymbol, Pool pool) {
2355         List<JCTree> prunedInfo = lower.prunedTree.get(classSymbol);
2356         if (prunedInfo != null) {
2357             for (JCTree prunedTree: prunedInfo) {
2358                 prunedTree.accept(classReferenceVisitor);
2359             }
2360         }
2361     }
2362 
2363 /* ************************************************************************
2364  * main method
2365  *************************************************************************/
2366 
2367     /** Generate code for a class definition.
2368      *  @param env   The attribution environment that belongs to the
2369      *               outermost class containing this class definition.
2370      *               We need this for resolving some additional symbols.
2371      *  @param cdef  The tree representing the class definition.
2372      *  @return      True if code is generated with no errors.
2373      */
2374     public boolean genClass(Env<AttrContext> env, JCClassDecl cdef) {
2375         try {
2376             attrEnv = env;
2377             ClassSymbol c = cdef.sym;
2378             this.toplevel = env.toplevel;
2379             this.endPosTable = toplevel.endPositions;
2380             c.pool = pool;
2381             pool.reset();
2382             /* method normalizeDefs() can add references to external classes into the constant pool
2383              */
2384             cdef.defs = normalizeDefs(cdef.defs, c);
2385             generateReferencesToPrunedTree(c, pool);
2386             Env<GenContext> localEnv = new Env<>(cdef, new GenContext());
2387             localEnv.toplevel = env.toplevel;
2388             localEnv.enclClass = cdef;
2389 
2390             for (List<JCTree> l = cdef.defs; l.nonEmpty(); l = l.tail) {
2391                 genDef(l.head, localEnv);
2392             }
2393             if (pool.numEntries() > Pool.MAX_ENTRIES) {
2394                 log.error(cdef.pos(), Errors.LimitPool);
2395                 nerrs++;
2396             }
2397             if (nerrs != 0) {
2398                 // if errors, discard code
2399                 for (List<JCTree> l = cdef.defs; l.nonEmpty(); l = l.tail) {
2400                     if (l.head.hasTag(METHODDEF))
2401                         ((JCMethodDecl) l.head).sym.code = null;
2402                 }
2403             }
2404             cdef.defs = List.nil(); // discard trees
2405             return nerrs == 0;
2406         } finally {
2407             // note: this method does NOT support recursion.
2408             attrEnv = null;
2409             this.env = null;
2410             toplevel = null;
2411             endPosTable = null;
2412             nerrs = 0;
2413         }


< prev index next >