Ejemplo n.º 1
0
    /**
     * Returns a <code>ThrowableSet</code> representing the set of exceptions included in <code>
     * include</code> minus the set of exceptions included in <code>exclude</code>. Creates a new
     * <code>ThrowableSet</code> only if there was not already one whose contents correspond to
     * <code>include</code> - <code>exclude</code>.
     *
     * @param include A set of {@link RefLikeType} objects representing exception types included in
     *     the result; may be <code>null</code> if there are no included types.
     * @param exclude A set of {@link AnySubType} objects representing exception types excluded from
     *     the result; may be <code>null</code> if there are no excluded types.
     * @return a <code>ThrowableSet</code> representing the set of exceptions corresponding to
     *     <code>include</code> - <code>exclude</code>.
     */
    private ThrowableSet registerSetIfNew(Set include, Set exclude) {
      if (INSTRUMENTING) {
        registrationCalls++;
      }
      if (include == null) {
        include = Collections.EMPTY_SET;
      }
      if (exclude == null) {
        exclude = Collections.EMPTY_SET;
      }
      int size = include.size() + exclude.size();
      Integer sizeKey = new Integer(size);

      List sizeList = (List) sizeToSets.get(sizeKey);
      if (sizeList == null) {
        sizeList = new LinkedList();
        sizeToSets.put(sizeKey, sizeList);
      }
      for (Iterator i = sizeList.iterator(); i.hasNext(); ) {
        ThrowableSet set = (ThrowableSet) i.next();
        if (set.exceptionsIncluded.equals(include) && set.exceptionsExcluded.equals(exclude)) {
          return set;
        }
      }
      if (INSTRUMENTING) {
        registeredSets++;
      }
      ThrowableSet result = new ThrowableSet(include, exclude);
      sizeList.add(result);
      return result;
    }
Ejemplo n.º 2
0
  private void addBoxToPatch(String aLabelName, UnitBox aUnitBox) {
    List patchList = (List) mLabelToPatchList.get(aLabelName);
    if (patchList == null) {
      patchList = new ArrayList();
      mLabelToPatchList.put(aLabelName, patchList);
    }

    patchList.add(aUnitBox);
  }
Ejemplo n.º 3
0
  /**
   * Traverse the statements in the given body, looking for aggregation possibilities; that is,
   * given a def d and a use u, d has no other uses, u has no other defs, collapse d and u.
   *
   * <p>option: only-stack-locals; if this is true, only aggregate variables starting with $
   */
  protected void internalTransform(Body b, String phaseName, Map<String, String> options) {
    StmtBody body = (StmtBody) b;
    boolean onlyStackVars = PhaseOptions.getBoolean(options, "only-stack-locals");

    int aggregateCount = 1;

    if (Options.v().time()) Timers.v().aggregationTimer.start();
    boolean changed = false;

    Map<ValueBox, Zone> boxToZone =
        new HashMap<ValueBox, Zone>(body.getUnits().size() * 2 + 1, 0.7f);

    // Determine the zone of every box
    {
      Zonation zonation = new Zonation(body);

      for (Unit u : body.getUnits()) {
        Zone zone = zonation.getZoneOf(u);

        for (ValueBox box : u.getUseBoxes()) {
          boxToZone.put(box, zone);
        }

        for (ValueBox box : u.getDefBoxes()) {
          boxToZone.put(box, zone);
        }
      }
    }

    do {
      if (Options.v().verbose())
        G.v()
            .out
            .println(
                "["
                    + body.getMethod().getName()
                    + "] Aggregating iteration "
                    + aggregateCount
                    + "...");

      // body.printTo(new java.io.PrintWriter(G.v().out, true));

      changed = internalAggregate(body, boxToZone, onlyStackVars);

      aggregateCount++;
    } while (changed);

    if (Options.v().time()) Timers.v().aggregationTimer.end();
  }
Ejemplo n.º 4
0
 protected void buildMaps(PegGraph pg) {
   exceHandlers.addAll(pg.getExceHandlers());
   startToThread.putAll(pg.getStartToThread());
   startToAllocNodes.putAll(pg.getStartToAllocNodes());
   startToBeginNodes.putAll(pg.getStartToBeginNodes());
   waitingNodes.putAll(pg.getWaitingNodes());
   notifyAll.putAll(pg.getNotifyAll());
   canNotBeCompacted.addAll(pg.getCanNotBeCompacted());
   synch.addAll(pg.getSynch());
   threadNameToStart.putAll(pg.getThreadNameToStart());
   specialJoin.addAll(pg.getSpecialJoin());
   joinStmtToThread.putAll(pg.getJoinStmtToThread());
   threadAllocSites.addAll(pg.getThreadAllocSites());
   allocNodeToThread.putAll(pg.getAllocNodeToThread());
 }
Ejemplo n.º 5
0
  public void outALocalImmediate(ALocalImmediate node) {
    String local = (String) mProductions.removeLast();

    Local l = (Local) mLocals.get(local);
    if (l == null) throw new RuntimeException("did not find local: " + local);
    mProductions.addLast(l);
  }
Ejemplo n.º 6
0
  public void outANonstaticInvokeExpr(ANonstaticInvokeExpr node) {
    List args;

    if (node.getArgList() != null) args = (List) mProductions.removeLast();
    else args = new ArrayList();

    SootMethodRef method = (SootMethodRef) mProductions.removeLast();

    String local = (String) mProductions.removeLast();

    Local l = (Local) mLocals.get(local);
    if (l == null) throw new RuntimeException("did not find local: " + local);

    Node invokeType = (Node) node.getNonstaticInvoke();
    Expr invokeExpr;

    if (invokeType instanceof ASpecialNonstaticInvoke) {
      invokeExpr = Jimple.v().newSpecialInvokeExpr(l, method, args);
    } else if (invokeType instanceof AVirtualNonstaticInvoke) {
      invokeExpr = Jimple.v().newVirtualInvokeExpr(l, method, args);
    } else {
      if (debug)
        if (!(invokeType instanceof AInterfaceNonstaticInvoke))
          throw new RuntimeException("expected interface invoke.");
      invokeExpr = Jimple.v().newInterfaceInvokeExpr(l, method, args);
    }

    mProductions.addLast(invokeExpr);
  }
Ejemplo n.º 7
0
  public void outAIdentityNoTypeStatement(AIdentityNoTypeStatement node) {
    mProductions.removeLast(); // get rid of @caughtexception string presently on top of the stack
    Value local =
        (Value) mLocals.get(mProductions.removeLast()); // the local ref from it's identifier

    Unit u = Jimple.v().newIdentityStmt(local, Jimple.v().newCaughtExceptionRef());
    mProductions.addLast(u);
  }
Ejemplo n.º 8
0
  public void outAArrayRef(AArrayRef node) {
    Value immediate = (Value) mProductions.removeLast();
    String identifier = (String) mProductions.removeLast();

    Local l = (Local) mLocals.get(identifier);
    if (l == null) throw new RuntimeException("did not find local: " + identifier);

    mProductions.addLast(Jimple.v().newArrayRef(l, immediate));
  }
Ejemplo n.º 9
0
  public void outALocalFieldRef(ALocalFieldRef node) {
    SootFieldRef field = (SootFieldRef) mProductions.removeLast();

    String local = (String) mProductions.removeLast();

    Local l = (Local) mLocals.get(local);
    if (l == null) throw new RuntimeException("did not find local: " + local);

    mProductions.addLast(Jimple.v().newInstanceFieldRef(l, field));
  }
Ejemplo n.º 10
0
  public void outADeclaration(ADeclaration node) {
    List localNameList = (List) mProductions.removeLast();
    Type type = (Type) mProductions.removeLast();
    Iterator it = localNameList.iterator();
    List localList = new ArrayList();

    while (it.hasNext()) {
      Local l = Jimple.v().newLocal((String) it.next(), type);
      mLocals.put(l.getName(), l);
      localList.add(l);
    }
    mProductions.addLast(localList);
  }
Ejemplo n.º 11
0
  protected void testJoinStmtToThread() {
    System.out.println("=====test JoinStmtToThread");
    Set maps = threadNameToStart.entrySet();
    for (Iterator iter = maps.iterator(); iter.hasNext(); ) {
      Map.Entry entry = (Map.Entry) iter.next();
      Object key = entry.getKey();

      System.out.println("---key=  " + key);

      System.out.println("value: " + entry.getValue());
    }
    System.out.println("=========JoinStmtToThread--ends--------");
  }
Ejemplo n.º 12
0
  public void computeMonitorObjs() {
    Set maps = monitor.entrySet();
    for (Iterator iter = maps.iterator(); iter.hasNext(); ) {
      Map.Entry entry = (Map.Entry) iter.next();

      FlowSet fs = (FlowSet) entry.getValue();
      Iterator it = fs.iterator();
      while (it.hasNext()) {
        Object obj = it.next();
        if (!monitorObjs.contains(obj)) monitorObjs.add(obj);
      }
    }
  }
Ejemplo n.º 13
0
 /**
  * Report the counts collected by instrumentation (for now, at least, there is no need to
  * provide access to the individual values as numbers).
  *
  * @return a string listing the counts.
  */
 public String reportInstrumentation() {
   int setCount = 0;
   for (Iterator it = sizeToSets.values().iterator(); it.hasNext(); ) {
     List sizeList = (List) it.next();
     setCount += sizeList.size();
   }
   if (setCount != registeredSets) {
     throw new IllegalStateException(
         "ThrowableSet.reportInstrumentation() assertion failure: registeredSets != list count");
   }
   StringBuffer buf =
       new StringBuffer("registeredSets: ")
           .append(setCount)
           .append("\naddsOfRefType: ")
           .append(addsOfRefType)
           .append("\naddsOfAnySubType: ")
           .append(addsOfAnySubType)
           .append("\naddsOfSet: ")
           .append(addsOfSet)
           .append("\naddsInclusionFromMap: ")
           .append(addsInclusionFromMap)
           .append("\naddsInclusionFromMemo: ")
           .append(addsInclusionFromMemo)
           .append("\naddsInclusionFromSearch: ")
           .append(addsInclusionFromSearch)
           .append("\naddsInclusionInterrupted: ")
           .append(addsInclusionInterrupted)
           .append("\naddsExclusionWithoutSearch: ")
           .append(addsExclusionWithoutSearch)
           .append("\naddsExclusionWithSearch: ")
           .append(addsExclusionWithSearch)
           .append("\nremovesOfAnySubType: ")
           .append(removesOfAnySubType)
           .append("\nremovesFromMap: ")
           .append(removesFromMap)
           .append("\nremovesFromMemo: ")
           .append(removesFromMemo)
           .append("\nremovesFromSearch: ")
           .append(removesFromSearch)
           .append("\nregistrationCalls: ")
           .append(registrationCalls)
           .append("\ncatchableAsQueries: ")
           .append(catchableAsQueries)
           .append("\ncatchableAsFromMap: ")
           .append(catchableAsFromMap)
           .append("\ncatchableAsFromSearch: ")
           .append(catchableAsFromSearch)
           .append('\n');
   return buf.toString();
 }
Ejemplo n.º 14
0
  protected void testThreadNameToStart() {
    System.out.println("=====test ThreadNameToStart");
    Set maps = threadNameToStart.entrySet();
    for (Iterator iter = maps.iterator(); iter.hasNext(); ) {
      Map.Entry entry = (Map.Entry) iter.next();
      Object key = entry.getKey();

      System.out.println("---key=  " + key);
      JPegStmt stmt = (JPegStmt) entry.getValue();
      Tag tag1 = (Tag) stmt.getTags().get(0);
      System.out.println("value: " + tag1 + " " + stmt);
    }
    System.out.println("=========ThreadNameToStart--ends--------");
  }
Ejemplo n.º 15
0
  public void testMonitor() {
    System.out.println("=====test monitor size: " + monitor.size());
    Set maps = monitor.entrySet();
    for (Iterator iter = maps.iterator(); iter.hasNext(); ) {
      Map.Entry entry = (Map.Entry) iter.next();
      String key = (String) entry.getKey();

      System.out.println("---key=  " + key);
      FlowSet list = (FlowSet) entry.getValue();
      if (list.size() > 0) {

        System.out.println("**set:  " + list.size());
        Iterator it = list.iterator();
        while (it.hasNext()) {
          Object obj = it.next();
          if (obj instanceof JPegStmt) {
            JPegStmt stmt = (JPegStmt) obj;
            Tag tag1 = (Tag) stmt.getTags().get(0);
            System.out.println(tag1 + " " + stmt);
          } else {
            System.out.println("---list---");
            Iterator listIt = ((List) obj).iterator();
            while (listIt.hasNext()) {
              Object oo = listIt.next();
              if (oo instanceof JPegStmt) {
                JPegStmt unit = (JPegStmt) oo;
                Tag tag = (Tag) unit.getTags().get(0);
                System.out.println(tag + " " + unit);
              } else System.out.println(oo);
            }
            System.out.println("---list--end-");
          }
        }
      }
    }
    System.out.println("=========monitor--ends--------");
  }
Ejemplo n.º 16
0
  public void outAIdentityStatement(AIdentityStatement node) {
    Type identityRefType = (Type) mProductions.removeLast();
    String atClause = (String) mProductions.removeLast();
    Value local =
        (Value) mLocals.get(mProductions.removeLast()); // the local ref from it's identifier

    Value ref = null;
    if (atClause.startsWith("@this")) {
      ref = Jimple.v().newThisRef((RefType) identityRefType);
    } else if (atClause.startsWith("@parameter")) {
      int index = Integer.parseInt(atClause.substring(10, atClause.length() - 1));

      ref = Jimple.v().newParameterRef(identityRefType, index);
    } else
      throw new RuntimeException(
          "shouldn't @caughtexception be handled by outAIdentityNoTypeStatement: got" + atClause);

    Unit u = Jimple.v().newIdentityStmt(local, ref);
    mProductions.addLast(u);
  }
Ejemplo n.º 17
0
 /**
  * Returns a <code>ThrowableSet</code> which contains all the exceptions in <code>s</code> in
  * addition to those in this <code>ThrowableSet</code>.
  *
  * @param s set of exceptions to add to this set.
  * @return the union of this set with <code>s</code>
  * @throws ThrowableSet.AlreadyHasExclusionsException if this <code>ThrowableSet</code> or <code>s
  *     </code> is the result of a {@link #whichCatchableAs(RefType)} operation, so that it is not
  *     possible to represent the addition of <code>s</code> to this <code>ThrowableSet</code>.
  */
 public ThrowableSet add(ThrowableSet s) throws ThrowableSet.AlreadyHasExclusionsException {
   if (INSTRUMENTING) {
     Manager.v().addsOfSet++;
   }
   if (exceptionsExcluded.size() > 0 || s.exceptionsExcluded.size() > 0) {
     throw new AlreadyHasExclusionsException(
         "ThrowableSet.Add(ThrowableSet): attempt to add to ["
             + this.toString()
             + "] after removals recorded.");
   }
   ThrowableSet result = getMemoizedAdds(s);
   if (result == null) {
     if (INSTRUMENTING) {
       Manager.v().addsInclusionFromSearch++;
       Manager.v().addsExclusionWithoutSearch++;
     }
     result = this.add(s.exceptionsIncluded);
     memoizedAdds.put(s, result);
   } else if (INSTRUMENTING) {
     Manager.v().addsInclusionFromMemo++;
     Manager.v().addsExclusionWithoutSearch++;
   }
   return result;
 }
Ejemplo n.º 18
0
 private ThrowableSet getMemoizedAdds(Object key) {
   if (memoizedAdds == null) {
     memoizedAdds = new HashMap();
   }
   return (ThrowableSet) memoizedAdds.get(key);
 }
Ejemplo n.º 19
0
  /**
   * Returns a <code>ThrowableSet</code> which contains <code>e</code> in addition to the exceptions
   * in this <code>ThrowableSet</code>.
   *
   * <p>Add <code>e</code> as a {@link RefType} when you know that the run-time class of the
   * exception you are representing is necessarily <code>e</code> and cannot be a subclass of <code>
   * e</code>.
   *
   * <p>For example, if you were recording the type of the exception thrown by
   *
   * <pre>
   * throw new IOException("Permission denied");
   * </pre>
   *
   * you would call
   *
   * <pre>
   * <code>add(Scene.v().getRefType("java.lang.Exception.IOException"))</code>
   * </pre>
   *
   * since the class of the exception is necessarily <code>IOException</code>.
   *
   * @param e the exception class
   * @return a set containing <code>e</code> as well as the exceptions in this set.
   * @throws {@link ThrowableSet.IllegalStateException} if this <code>ThrowableSet</code> is the
   *     result of a {@link #whichCatchableAs(RefType)} operation and, thus, unable to represent the
   *     addition of <code>e</code>.
   */
  public ThrowableSet add(RefType e) throws ThrowableSet.AlreadyHasExclusionsException {
    if (INSTRUMENTING) {
      Manager.v().addsOfRefType++;
    }
    if (this.exceptionsIncluded.contains(e)) {
      if (INSTRUMENTING) {
        Manager.v().addsInclusionFromMap++;
        Manager.v().addsExclusionWithoutSearch++;
      }
      return this;
    } else {
      ThrowableSet result = getMemoizedAdds(e);
      if (result != null) {
        if (INSTRUMENTING) {
          Manager.v().addsInclusionFromMemo++;
          Manager.v().addsExclusionWithoutSearch++;
        }
        return result;
      } else {
        if (INSTRUMENTING) {
          Manager.v().addsInclusionFromSearch++;
          if (exceptionsExcluded.size() != 0) {
            Manager.v().addsExclusionWithSearch++;
          } else {
            Manager.v().addsExclusionWithoutSearch++;
          }
        }
        FastHierarchy hierarchy = Scene.v().getOrMakeFastHierarchy();

        for (Iterator i = exceptionsExcluded.iterator(); i.hasNext(); ) {
          RefType exclusionBase = ((AnySubType) i.next()).getBase();
          if (hierarchy.canStoreType(e, exclusionBase)) {
            throw new AlreadyHasExclusionsException(
                "ThrowableSet.add(RefType): adding"
                    + e.toString()
                    + " to the set [ "
                    + this.toString()
                    + "] where "
                    + exclusionBase.toString()
                    + " is excluded.");
          }
        }

        for (Iterator i = exceptionsIncluded.iterator(); i.hasNext(); ) {
          RefLikeType incumbent = (RefLikeType) i.next();
          if (incumbent instanceof AnySubType) {
            // Need to use incumbent.getBase() because
            // hierarchy.canStoreType() assumes that parent
            // is not an AnySubType.
            RefType incumbentBase = ((AnySubType) incumbent).getBase();
            if (hierarchy.canStoreType(e, incumbentBase)) {
              memoizedAdds.put(e, this);
              return this;
            }
          } else if (!(incumbent instanceof RefType)) {
            // assertion failure.
            throw new IllegalStateException(
                "ThrowableSet.add(RefType): Set element "
                    + incumbent.toString()
                    + " is neither a RefType nor an AnySubType.");
          }
        }
        Set resultSet = new HashSet(this.exceptionsIncluded);
        resultSet.add(e);
        result = Manager.v().registerSetIfNew(resultSet, this.exceptionsExcluded);
        memoizedAdds.put(e, result);
        return result;
      }
    }
  }
Ejemplo n.º 20
0
  /**
   * Returns a <code>ThrowableSet</code> which contains <code>e</code> and all of its subclasses as
   * well as the exceptions in this set.
   *
   * <p><code>e</code> should be an instance of {@link AnySubType} if you know that the compile-time
   * type of the exception you are representing is <code>e</code>, but the exception may be
   * instantiated at run-time by a subclass of <code>e</code>.
   *
   * <p>For example, if you were recording the type of the exception thrown by
   *
   * <pre>
   * catch (IOException e) {
   *    throw e;
   * }
   * </pre>
   *
   * you would call
   *
   * <pre>
   * <code>add(AnySubtype.v(Scene.v().getRefType("java.lang.Exception.IOException")))</code>
   * </pre>
   *
   * since the handler might rethrow any subclass of <code>IOException</code>.
   *
   * @param e represents a subtree of the exception class hierarchy to add to this set.
   * @return a set containing <code>e</code> and all its subclasses, as well as the exceptions
   *     represented by this set.
   * @throws ThrowableSet.AlreadyHasExclusionsException if this <code>ThrowableSet</code> is the
   *     result of a {@link #whichCatchableAs(RefType)} operation and, thus, unable to represent the
   *     addition of <code>e</code>.
   */
  public ThrowableSet add(AnySubType e) throws ThrowableSet.AlreadyHasExclusionsException {
    if (INSTRUMENTING) {
      Manager.v().addsOfAnySubType++;
    }

    ThrowableSet result = getMemoizedAdds(e);
    if (result != null) {
      if (INSTRUMENTING) {
        Manager.v().addsInclusionFromMemo++;
        Manager.v().addsExclusionWithoutSearch++;
      }
      return result;
    } else {
      FastHierarchy hierarchy = Scene.v().getOrMakeFastHierarchy();
      RefType newBase = e.getBase();

      if (INSTRUMENTING) {
        if (exceptionsExcluded.size() != 0) {
          Manager.v().addsExclusionWithSearch++;
        } else {
          Manager.v().addsExclusionWithoutSearch++;
        }
      }
      for (Iterator i = exceptionsExcluded.iterator(); i.hasNext(); ) {
        RefType exclusionBase = ((AnySubType) i.next()).getBase();
        if (hierarchy.canStoreType(newBase, exclusionBase)
            || hierarchy.canStoreType(exclusionBase, newBase)) {
          if (INSTRUMENTING) {
            // To ensure that the subcategories total properly:
            Manager.v().addsInclusionInterrupted++;
          }
          throw new AlreadyHasExclusionsException(
              "ThrowableSet.add("
                  + e.toString()
                  + ") to the set [ "
                  + this.toString()
                  + "] where "
                  + exclusionBase.toString()
                  + " is excluded.");
        }
      }

      if (this.exceptionsIncluded.contains(e)) {
        if (INSTRUMENTING) {
          Manager.v().addsInclusionFromMap++;
        }
        return this;

      } else {
        if (INSTRUMENTING) {
          Manager.v().addsInclusionFromSearch++;
        }

        int changes = 0;
        boolean addNewException = true;
        Set resultSet = new HashSet();

        for (Iterator i = this.exceptionsIncluded.iterator(); i.hasNext(); ) {
          RefLikeType incumbent = (RefLikeType) i.next();
          if (incumbent instanceof RefType) {
            if (hierarchy.canStoreType(incumbent, newBase)) {
              // Omit incumbent from result.
              changes++;
            } else {
              resultSet.add(incumbent);
            }
          } else if (incumbent instanceof AnySubType) {
            RefType incumbentBase = ((AnySubType) incumbent).getBase();
            // We have to use the base types in these hierarchy calls
            // because we want to know if _all_ possible
            // types represented by e can be represented by
            // the incumbent, or vice versa.
            if (hierarchy.canStoreType(newBase, incumbentBase)) {
              addNewException = false;
              resultSet.add(incumbent);
            } else if (hierarchy.canStoreType(incumbentBase, newBase)) {
              // Omit incumbent from result;
              changes++;
            } else {
              resultSet.add(incumbent);
            }
          } else { // assertion failure.
            throw new IllegalStateException(
                "ThrowableSet.add(AnySubType): Set element "
                    + incumbent.toString()
                    + " is neither a RefType nor an AnySubType.");
          }
        }
        if (addNewException) {
          resultSet.add(e);
          changes++;
        }
        if (changes > 0) {
          result = Manager.v().registerSetIfNew(resultSet, this.exceptionsExcluded);
        } else {
          result = this;
        }
        memoizedAdds.put(e, result);
        return result;
      }
    }
  }
Ejemplo n.º 21
0
  public void outAFullMethodBody(AFullMethodBody node) {
    Object catchClause = null;
    JimpleBody jBody = Jimple.v().newBody();

    if (node.getCatchClause() != null) {
      int size = node.getCatchClause().size();
      for (int i = 0; i < size; i++) jBody.getTraps().addFirst((Trap) mProductions.removeLast());
    }

    if (node.getStatement() != null) {
      int size = node.getStatement().size();
      Unit lastStmt = null;
      for (int i = 0; i < size; i++) {
        Object o = mProductions.removeLast();
        if (o instanceof Unit) {
          jBody.getUnits().addFirst(o);
          lastStmt = (Unit) o;
        } else if (o instanceof String) {
          if (lastStmt == null) throw new RuntimeException("impossible");
          mLabelToStmtMap.put(o, lastStmt);
        } else throw new RuntimeException("impossible");
      }
    }

    if (node.getDeclaration() != null) {
      int size = node.getDeclaration().size();
      for (int i = 0; i < size; i++) {
        List localList = (List) mProductions.removeLast();

        int listSize = localList.size();
        for (int j = listSize - 1; j >= 0; j--) jBody.getLocals().addFirst(localList.get(j));
      }
    }

    Iterator it = mLabelToPatchList.keySet().iterator();
    while (it.hasNext()) {
      String label = (String) it.next();
      Unit target = (Unit) mLabelToStmtMap.get(label);

      Iterator patchIt = ((List) mLabelToPatchList.get(label)).iterator();
      while (patchIt.hasNext()) {
        UnitBox box = (UnitBox) patchIt.next();
        box.setUnit(target);
      }
    }

    /*
    Iterator it = mLabelToStmtMap.keySet().iterator();
    while(it.hasNext()) {
        String label = (String) it.next();
        Unit target = (Unit) mLabelToStmtMap.get(label);

        List l =         (List) mLabelToPatchList.get(label);
        if(l != null) {
            Iterator patchIt = l.iterator();
            while(patchIt.hasNext()) {
                UnitBox box = (UnitBox) patchIt.next();
                box.setUnit(target);
            }
        }
    }
    */

    mProductions.addLast(jBody);
  }
Ejemplo n.º 22
0
  private static boolean internalAggregate(
      StmtBody body, Map<ValueBox, Zone> boxToZone, boolean onlyStackVars) {
    LocalUses localUses;
    LocalDefs localDefs;
    ExceptionalUnitGraph graph;
    boolean hadAggregation = false;
    Chain<Unit> units = body.getUnits();

    graph = new ExceptionalUnitGraph(body);
    localDefs = new SmartLocalDefs(graph, new SimpleLiveLocals(graph));
    localUses = new SimpleLocalUses(graph, localDefs);

    List<Unit> unitList = new PseudoTopologicalOrderer<Unit>().newList(graph, false);
    for (Unit u : unitList) {
      if (!(u instanceof AssignStmt)) continue;
      AssignStmt s = (AssignStmt) u;

      Value lhs = s.getLeftOp();
      if (!(lhs instanceof Local)) continue;
      Local lhsLocal = (Local) lhs;

      if (onlyStackVars && !lhsLocal.getName().startsWith("$")) continue;

      List<UnitValueBoxPair> lu = localUses.getUsesOf(s);
      if (lu.size() != 1) continue;

      UnitValueBoxPair usepair = lu.get(0);
      Unit use = usepair.unit;
      ValueBox useBox = usepair.valueBox;

      List<Unit> ld = localDefs.getDefsOfAt(lhsLocal, use);
      if (ld.size() != 1) continue;

      // Check to make sure aggregation pair in the same zone
      if (boxToZone.get(s.getRightOpBox()) != boxToZone.get(usepair.valueBox)) {
        continue;
      }

      /* we need to check the path between def and use */
      /* to see if there are any intervening re-defs of RHS */
      /* in fact, we should check that this path is unique. */
      /* if the RHS uses only locals, then we know what
      to do; if RHS has a method invocation f(a, b,
      c) or field access, we must ban field writes, other method
      calls and (as usual) writes to a, b, c. */

      boolean cantAggr = false;
      boolean propagatingInvokeExpr = false;
      boolean propagatingFieldRef = false;
      boolean propagatingArrayRef = false;
      ArrayList<FieldRef> fieldRefList = new ArrayList<FieldRef>();

      LinkedList<Value> localsUsed = new LinkedList<Value>();
      for (ValueBox vb : s.getUseBoxes()) {
        Value v = vb.getValue();
        if (v instanceof Local) localsUsed.add(v);
        else if (v instanceof InvokeExpr) propagatingInvokeExpr = true;
        else if (v instanceof ArrayRef) propagatingArrayRef = true;
        else if (v instanceof FieldRef) {
          propagatingFieldRef = true;
          fieldRefList.add((FieldRef) v);
        }
      }

      // look for a path from s to use in graph.
      // only look in an extended basic block, though.

      List<Unit> path = graph.getExtendedBasicBlockPathBetween(s, use);

      if (path == null) continue;

      Iterator<Unit> pathIt = path.iterator();

      // skip s.
      if (pathIt.hasNext()) pathIt.next();

      while (pathIt.hasNext() && !cantAggr) {
        Stmt between = (Stmt) (pathIt.next());

        if (between != use) {
          // Check for killing definitions

          for (ValueBox vb : between.getDefBoxes()) {
            Value v = vb.getValue();
            if (localsUsed.contains(v)) {
              cantAggr = true;
              break;
            }

            if (propagatingInvokeExpr || propagatingFieldRef || propagatingArrayRef) {
              if (v instanceof FieldRef) {
                if (propagatingInvokeExpr) {
                  cantAggr = true;
                  break;
                } else if (propagatingFieldRef) {
                  // Can't aggregate a field access if passing a definition of a field
                  // with the same name, because they might be aliased
                  for (FieldRef fieldRef : fieldRefList) {
                    if (((FieldRef) v).getField() == fieldRef.getField()) {
                      cantAggr = true;
                      break;
                    }
                  }
                }
              } else if (v instanceof ArrayRef) {
                if (propagatingInvokeExpr) {
                  // Cannot aggregate an invoke expr past an array write
                  cantAggr = true;
                  break;
                } else if (propagatingArrayRef) {
                  // cannot aggregate an array read past a write
                  // this is somewhat conservative
                  // (if types differ they may not be aliased)

                  cantAggr = true;
                  break;
                }
              }
            }
          }

          // Make sure not propagating past a {enter,exit}Monitor
          if (propagatingInvokeExpr && between instanceof MonitorStmt) cantAggr = true;
        }

        // Check for intervening side effects due to method calls
        if (propagatingInvokeExpr || propagatingFieldRef || propagatingArrayRef) {
          for (final ValueBox box : between.getUseBoxes()) {
            if (between == use && box == useBox) {
              // Reached use point, stop looking for
              // side effects
              break;
            }

            Value v = box.getValue();

            if (v instanceof InvokeExpr
                || (propagatingInvokeExpr && (v instanceof FieldRef || v instanceof ArrayRef))) {
              cantAggr = true;
              break;
            }
          }
        }
      }

      // we give up: can't aggregate.
      if (cantAggr) {
        continue;
      }
      /* assuming that the d-u chains are correct, */
      /* we need not check the actual contents of ld */

      Value aggregatee = s.getRightOp();

      if (usepair.valueBox.canContainValue(aggregatee)) {
        boolean wasSimpleCopy = isSimpleCopy(usepair.unit);
        usepair.valueBox.setValue(aggregatee);
        units.remove(s);
        hadAggregation = true;
        // clean up the tags. If s was not a simple copy, the new statement should get
        // the tags of s.
        // OK, this fix was wrong. The condition should not be
        // "If s was not a simple copy", but rather "If usepair.unit
        // was a simple copy". This way, when there's a load of a constant
        // followed by an invoke, the invoke gets the tags.
        if (wasSimpleCopy) {
          // usepair.unit.removeAllTags();
          usepair.unit.addAllTagsOf(s);
        }
      } else {
        /*
        if(Options.v().verbose())
        {
            G.v().out.println("[debug] failed aggregation");
              G.v().out.println("[debug] tried to put "+aggregatee+
                             " into "+usepair.stmt +
                             ": in particular, "+usepair.valueBox);
              G.v().out.println("[debug] aggregatee instanceof Expr: "
                             +(aggregatee instanceof Expr));
        }*/
      }
    }
    return hadAggregation;
  }