1 /*
   2  * Copyright (c) 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.comp;
  27 
  28 import com.sun.tools.javac.code.Attribute.Compound;
  29 import com.sun.tools.javac.code.Symbol;
  30 import com.sun.tools.javac.code.Symbol.ClassSymbol;
  31 import com.sun.tools.javac.code.Symbol.DynamicMethodSymbol;
  32 import com.sun.tools.javac.code.Symbol.MethodSymbol;
  33 import com.sun.tools.javac.code.Symtab;
  34 import com.sun.tools.javac.code.Type;
  35 import com.sun.tools.javac.code.Type.MethodType;
  36 import com.sun.tools.javac.code.Types;
  37 import com.sun.tools.javac.intrinsics.Intrinsics;
  38 import com.sun.tools.javac.intrinsics.IntrinsicProcessor.Result;
  39 import com.sun.tools.javac.jvm.ClassFile;
  40 import com.sun.tools.javac.jvm.PoolConstant;
  41 import com.sun.tools.javac.tree.JCTree.JCExpression;
  42 import com.sun.tools.javac.tree.JCTree.JCFieldAccess;
  43 import com.sun.tools.javac.tree.JCTree.JCMethodInvocation;
  44 import com.sun.tools.javac.tree.JCTree;
  45 import com.sun.tools.javac.tree.TreeInfo;
  46 import com.sun.tools.javac.tree.TreeMaker;
  47 import com.sun.tools.javac.tree.TreeTranslator;
  48 import com.sun.tools.javac.util.Assert;
  49 import com.sun.tools.javac.util.Context;
  50 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
  51 import com.sun.tools.javac.util.JCDiagnostic.SimpleDiagnosticPosition;
  52 import com.sun.tools.javac.util.List;
  53 import com.sun.tools.javac.util.ListBuffer;
  54 import com.sun.tools.javac.util.Name;
  55 import com.sun.tools.javac.util.Names;
  56 import com.sun.tools.javac.util.Options;
  57 
  58 import java.lang.constant.ClassDesc;
  59 import java.lang.constant.ConstantDesc;
  60 import java.lang.constant.ConstantDescs;
  61 import java.lang.constant.DirectMethodHandleDesc;
  62 import java.lang.constant.DynamicCallSiteDesc;
  63 import java.lang.constant.MethodTypeDesc;
  64 
  65 import java.lang.invoke.MethodHandles;
  66 
  67 import static com.sun.tools.javac.code.Flags.STATIC;
  68 import static com.sun.tools.javac.code.TypeTag.BOT;
  69 import static com.sun.tools.javac.tree.JCTree.Tag.SELECT;
  70 
  71 /**
  72  *  <p><b>This is NOT part of any supported API.
  73  *  If you write code that depends on this, you do so at your own risk.
  74  *  This code and its internal interfaces are subject to change or
  75  *  deletion without notice.</b>
  76  */
  77 public class IntrinsicsVisitor {
  78     protected static final Context.Key<IntrinsicsVisitor> intrinsicsVisitorKey = new Context.Key<>();
  79 
  80     private boolean enableIntrinsics;
  81 
  82     private final Names names;
  83     private final Symtab syms;
  84     private final Resolve rs;
  85     private final Types types;
  86     private final TreeMaker make;
  87     private final Intrinsics intrinsics;
  88     private final MethodHandles.Lookup lookup;
  89 
  90     private Env<AttrContext> attrEnv;
  91     private DiagnosticPosition nopos;
  92 
  93     public static IntrinsicsVisitor instance(Context context) {
  94         IntrinsicsVisitor instance = context.get(intrinsicsVisitorKey);
  95 
  96         if (instance == null)
  97             instance = new IntrinsicsVisitor(context);
  98         return instance;
  99     }
 100 
 101     IntrinsicsVisitor(Context context) {
 102         context.put(intrinsicsVisitorKey, this);
 103         Options options = Options.instance(context);
 104         String opt = Options.instance(context).get("intrinsify");
 105         enableIntrinsics = opt != null && opt.equals("all");
 106         names = Names.instance(context);
 107         syms = Symtab.instance(context);
 108         rs = Resolve.instance(context);
 109         types = Types.instance(context);
 110         make = TreeMaker.instance(context);
 111         lookup = MethodHandles.lookup();
 112         intrinsics = Intrinsics.instance(context);
 113     }
 114 
 115     public JCTree analyzeTree(JCTree tree, Env<AttrContext> attrEnv) {
 116         if (!enableIntrinsics ||
 117                 !(tree instanceof JCTree.JCClassDecl) ||
 118                 tree.type.tsym.packge().modle == syms.java_base) {
 119             return tree;
 120         }
 121         this.attrEnv = attrEnv;
 122         return translator.translate(tree);
 123     }
 124 
 125     class TransformIntrinsic {
 126         private final MethodSymbol msym;
 127 
 128         TransformIntrinsic(MethodSymbol msym) {
 129             this.msym = msym;
 130         }
 131 
 132         private ConstantDesc makeConstantDesc(Type type) {
 133             Object constant = type.constValue();
 134 
 135             if (constant == null) {
 136                 return null;
 137             } else if (type.getTag() == BOT) {
 138                 return ConstantDescs.NULL;
 139             }
 140 
 141             return constant instanceof ConstantDesc ? (ConstantDesc)constant : null;
 142         }
 143 
 144         private Object resolveConstantDesc(ConstantDesc constantDesc) {
 145             try {
 146                 return constantDesc.resolveConstantDesc(lookup);
 147             } catch (ReflectiveOperationException ex) {
 148                 // do nothing
 149             }
 150             return null;
 151         }
 152 
 153         private Name fullName(ClassDesc cd) {
 154             if (cd.packageName().isEmpty()) {
 155                 return names.fromString(cd.displayName());
 156             }
 157 
 158             return names.fromString(cd.packageName() + "." + cd.displayName());
 159         }
 160 
 161         public JCTree translate(JCMethodInvocation tree, JCTree.JCClassDecl currentClass) {
 162             ClassDesc owner = ClassDesc.of(msym.owner.toString());
 163             String methodName = msym.name.toString();
 164             MethodTypeDesc methodTypeDesc = MethodTypeDesc.ofDescriptor(signature(msym.type));
 165             boolean isStatic = (msym.flags() & STATIC) != 0;
 166             List<JCExpression>args = tree.args;
 167             int argSize = args.size();
 168             int offset = isStatic ? 0 : 1;
 169 
 170             int allArgsSize = offset + argSize;
 171             JCExpression[] allArgs = new JCExpression[allArgsSize];
 172             ClassDesc[] argClassDescs = new ClassDesc[allArgsSize];
 173             ConstantDesc[] constantArgs = new ConstantDesc[allArgsSize];
 174 
 175             if (!isStatic) {
 176                 JCExpression qualifierExpr = tree.meth.hasTag(SELECT) ?
 177                         ((JCFieldAccess)tree.meth).selected :
 178                         make.at(tree).This(currentClass.sym.erasure(types));
 179                 allArgs[0] = qualifierExpr;
 180                 argClassDescs[0] = ClassDesc.ofDescriptor(signature(qualifierExpr.type));
 181                 constantArgs[0] = makeConstantDesc(qualifierExpr.type);
 182             }
 183 
 184             for (int i = 0; i < argSize; i++) {
 185                 JCExpression arg = args.get(i);
 186 
 187                 if (arg == null) {
 188                     return tree;
 189                 }
 190 
 191                 int io = i + offset;
 192                 allArgs[io] = arg;
 193                 argClassDescs[io] = ClassDesc.ofDescriptor(signature(arg.type));
 194                 constantArgs[io] = makeConstantDesc(arg.type);
 195             }
 196 
 197             // Compiler env object
 198             Result result = intrinsics.tryIntrinsify(
 199                     owner,
 200                     methodName,
 201                     methodTypeDesc,
 202                     isStatic,
 203                     argClassDescs,
 204                     constantArgs
 205             );
 206 
 207             switch (result.getKind()) {
 208                 case NONE: return tree;
 209                 case LDC:
 210                     Result.Ldc ldc = (Result.Ldc)result;
 211                     Object constant = resolveConstantDesc(ldc.constant());
 212 
 213                     return constant == null ? make.Literal(BOT, null).setType(syms.botType) :
 214                             make.Literal(constant);
 215                 case INDY:
 216                     Result.Indy indy = (Result.Indy)result;
 217                     DynamicCallSiteDesc callSite = indy.indy();
 218                     String invocationName = callSite.invocationName();
 219                     DirectMethodHandleDesc bootstrapMethod = (DirectMethodHandleDesc)callSite.bootstrapMethod();
 220                     ClassDesc ownerClass = bootstrapMethod.owner();
 221                     String bootstrapName = bootstrapMethod.methodName();
 222                     List<Object> staticArgs = List.nil();
 223 
 224                     for (ConstantDesc constantDesc : callSite.bootstrapArgs()) {
 225                         staticArgs = staticArgs.append(resolveConstantDesc(constantDesc));
 226                     }
 227 
 228                     List<JCExpression> indyArgs = List.nil();
 229 
 230                     for (int i : indy.args()) {
 231                         indyArgs = indyArgs.append(allArgs[i]);
 232                     }
 233 
 234                     List<Type> argTypes = List.nil();
 235 
 236                     for (JCExpression arg : indyArgs) {
 237                         if (arg.type == syms.botType) {
 238                             argTypes = argTypes.append(syms.objectType);
 239                         } else {
 240                             argTypes = argTypes.append(arg.type);
 241                         }
 242                     }
 243 
 244                     Type returnType = msym.type.getReturnType();
 245                     MethodType indyType = new MethodType(argTypes, returnType,  List.nil(), syms.methodClass);
 246                     ClassSymbol classSymbol = syms.enterClass(msym.packge().modle, fullName(ownerClass));
 247 
 248                     return makeDynamicCall(
 249                             new SimpleDiagnosticPosition(tree.pos),
 250                             classSymbol.type,
 251                             names.fromString(bootstrapName),
 252                             staticArgs,
 253                             indyType,
 254                             indyArgs,
 255                             names.fromString(invocationName)
 256                     );
 257                     default:
 258                         throw new AssertionError("tryIntrinsifyMethod result unknown");
 259             }
 260         }
 261     }
 262 
 263     Translator translator = new Translator();
 264     class Translator extends TreeTranslator {
 265         JCTree.JCClassDecl currentClass;
 266 
 267         @Override
 268         public void visitApply(JCMethodInvocation tree) {
 269             super.visitApply(tree);
 270             Name methName = TreeInfo.name(tree.meth);
 271 
 272             if (methName == names._this || methName == names._super) {
 273                 return;
 274             }
 275 
 276             MethodSymbol msym = (MethodSymbol)TreeInfo.symbol(tree.meth);
 277             Compound attr = msym.attribute(syms.intrinsicCandidateType.tsym);
 278 
 279             if (attr != null) {
 280                 TransformIntrinsic transform = new TransformIntrinsic(msym);
 281                 result = transform.translate(tree, currentClass);
 282             }
 283         }
 284 
 285         @Override
 286         public void visitClassDef(JCTree.JCClassDecl tree) {
 287             JCTree.JCClassDecl previousClass = currentClass;
 288             try {
 289                 currentClass = tree;
 290                 super.visitClassDef(tree);
 291             } finally {
 292                 currentClass = previousClass;
 293             }
 294         }
 295     }
 296 
 297     private JCExpression makeDynamicCall(DiagnosticPosition pos, Type site, Name bsmName,
 298                                          List<Object> staticArgs, MethodType indyType,
 299                                          List<JCExpression> indyArgs,
 300                                          Name methName) {
 301         int prevPos = make.pos;
 302         try {
 303             make.at(pos);
 304             List<Type> bsm_staticArgs = List.of(syms.methodHandleLookupType,
 305                     syms.stringType,
 306                     syms.methodTypeType).appendList(bsmStaticArgToTypes(staticArgs));
 307             Symbol bsm = rs.resolveQualifiedMethod(pos, attrEnv, site,
 308                     bsmName, bsm_staticArgs, List.nil());
 309             PoolConstant.LoadableConstant[] loadableConstantsArr = objToLoadableConstantArr(staticArgs);
 310             DynamicMethodSymbol dynSym =
 311                     new DynamicMethodSymbol(methName,
 312                             syms.noSymbol,
 313                             ((MethodSymbol)bsm).asHandle(),
 314                             indyType,
 315                             loadableConstantsArr);
 316 
 317             JCFieldAccess qualifier = make.Select(make.QualIdent(site.tsym), bsmName);
 318             qualifier.sym = dynSym;
 319             qualifier.type = indyType;
 320             JCMethodInvocation proxyCall = make.Apply(List.nil(), qualifier, indyArgs);
 321             proxyCall.type = indyType.getReturnType();
 322 
 323             return proxyCall;
 324         } finally {
 325             make.at(prevPos);
 326         }
 327     }
 328 
 329     private List<Type> bsmStaticArgToTypes(List<Object> args) {
 330         ListBuffer<Type> argtypes = new ListBuffer<>();
 331 
 332         for (Object arg : args) {
 333             argtypes.append(bsmStaticArgToType(arg));
 334         }
 335 
 336         return argtypes.toList();
 337     }
 338 
 339     private Type bsmStaticArgToType(Object arg) {
 340         if (arg instanceof ClassSymbol) {
 341             return syms.classType;
 342         } else if (arg instanceof Integer) {
 343             return syms.intType;
 344         } else if (arg instanceof Long) {
 345             return syms.longType;
 346         } else if (arg instanceof Float) {
 347             return syms.floatType;
 348         } else if (arg instanceof Double) {
 349             return syms.doubleType;
 350         } else if (arg instanceof String) {
 351             return syms.stringType;
 352         } else {
 353             Assert.error("bad static arg " + arg);
 354             return null;
 355         }
 356     }
 357 
 358     private PoolConstant.LoadableConstant[] objToLoadableConstantArr(List<Object> args) {
 359         PoolConstant.LoadableConstant[] loadableConstants = new PoolConstant.LoadableConstant[args.size()];
 360         int index = 0;
 361         for (Object arg : args) {
 362             loadableConstants[index++] = objToLoadableConstant(arg);
 363         }
 364         return loadableConstants;
 365     }
 366 
 367     PoolConstant.LoadableConstant objToLoadableConstant(Object o) {
 368         if (o instanceof Integer) {
 369             return PoolConstant.LoadableConstant.Int((int)o);
 370         } else if (o instanceof Float) {
 371             return PoolConstant.LoadableConstant.Float((float)o);
 372         } else if (o instanceof Long) {
 373             return PoolConstant.LoadableConstant.Long((long)o);
 374         } else if (o instanceof Double) {
 375             return PoolConstant.LoadableConstant.Double((double)o);
 376         } else if (o instanceof String) {
 377             return PoolConstant.LoadableConstant.String((String)o);
 378         } else {
 379             throw new AssertionError("unexpected constant: " + o);
 380         }
 381     }
 382 
 383     private String signature(Type type) {
 384         SignatureGenerator generator = new SignatureGenerator();
 385         generator.assembleSig(type.getTag() == BOT ? syms.objectType : type);
 386 
 387         return generator.toString();
 388     }
 389 
 390     private class SignatureGenerator extends Types.SignatureGenerator {
 391         StringBuilder sb = new StringBuilder();
 392 
 393         SignatureGenerator() {
 394             super(types);
 395         }
 396 
 397         @Override
 398         protected void append(char ch) {
 399             sb.append(ch);
 400         }
 401 
 402         @Override
 403         protected void append(byte[] ba) {
 404             sb.append(new String(ba));
 405         }
 406 
 407         @Override
 408         protected void append(Name name) {
 409             sb.append(name.toString());
 410         }
 411 
 412         @Override
 413         public String toString() {
 414             return sb.toString();
 415         }
 416     }
 417 }