Package com.google.gwt.dev.util.log.speedtracer.SpeedTracerLogger

Examples of com.google.gwt.dev.util.log.speedtracer.SpeedTracerLogger.Event


        List<JsSourceMap> sourceInfoMaps, PermutationResult permutationResult)
        throws IOException, UnableToCompleteException {

      assert internedLiteralByVariableName != null;

      Event event = SpeedTracerLogger.start(CompilerEventType.PERMUTATION_ARTIFACTS);

      CompilationMetricsArtifact compilationMetrics = addCompilerMetricsArtifact(
          unifiedAst, permutation, startTimeMs, sizeBreakdowns, permutationResult);
      addSoycArtifacts(unifiedAst, permutationId, jjsmap, dependenciesAndRecorder,
          internedLiteralByVariableName, jsFragments, sizeBreakdowns, sourceInfoMaps,
          permutationResult, compilationMetrics);
      addSourceMapArtifacts(permutationId, jjsmap, dependenciesAndRecorder, isSourceMapsEnabled,
          sizeBreakdowns, sourceInfoMaps, permutationResult);
      maybeAddGeneratedArtifacts(permutationResult);

      event.end();
    }
View Full Code Here


     */
    private void generateJavaScriptCode(JavaToJavaScriptMap jjsMap, String[] jsFragments,
        StatementRanges[] ranges, SizeBreakdown[] sizeBreakdowns,
        List<JsSourceMap> sourceInfoMaps, boolean sourceMapsEnabled) {

      Event generateJavascriptEvent =
          SpeedTracerLogger.start(CompilerEventType.GENERATE_JAVASCRIPT);

      boolean useClosureCompiler = options.isClosureCompilerEnabled();
      if (useClosureCompiler) {
        ClosureJsRunner runner = new ClosureJsRunner();
        runner.compile(jprogram, jsProgram, jsFragments, options.getOutput());
        generateJavascriptEvent.end();
        return;
      }

      for (int i = 0; i < jsFragments.length; i++) {
        DefaultTextOutput out = new DefaultTextOutput(options.getOutput().shouldMinimize());
        JsReportGenerationVisitor v = new JsReportGenerationVisitor(out, jjsMap,
            options.isJsonSoycEnabled());
        v.accept(jsProgram.getFragmentBlock(i));

        StatementRanges statementRanges = v.getStatementRanges();
        String code = out.toString();
        JsSourceMap infoMap = (sourceInfoMaps != null) ? v.getSourceInfoMap() : null;

        JsAbstractTextTransformer transformer =
            new JsNoopTransformer(code, statementRanges, infoMap);

        /**
         * Cut generated JS up on class boundaries and re-link the source (possibly making use of
         * source from previous compiles, thus making it possible to perform partial recompiles).
         */
        if (options.isIncrementalCompileEnabled()) {
          transformer = new JsTypeLinker(logger, transformer, v.getClassRanges(),
              v.getProgramClassRange(), getMinimalRebuildCache(), jprogram.typeOracle);
          transformer.exec();
        }

        /**
         * Reorder function decls to improve compression ratios. Also restructures the top level
         * blocks into sub-blocks if they exceed 32767 statements.
         */
        Event functionClusterEvent = SpeedTracerLogger.start(CompilerEventType.FUNCTION_CLUSTER);
        // TODO(cromwellian) move to the Js AST optimization, re-enable sourcemaps + clustering
        if (!sourceMapsEnabled && options.shouldClusterSimilarFunctions()
            && options.getNamespace() == JsNamespaceOption.NONE
            && options.getOutput() == JsOutputOption.OBFUSCATED) {
          transformer = new JsFunctionClusterer(transformer);
          transformer.exec();
        }
        functionClusterEvent.end();

        jsFragments[i] = transformer.getJs();
        ranges[i] = transformer.getStatementRanges();
        if (sizeBreakdowns != null) {
          sizeBreakdowns[i] = v.getSizeBreakdown();
View Full Code Here

      Memory.maybeDumpMemory("makeSoycArtifactsStart");
      List<SyntheticArtifact> soycArtifacts = new ArrayList<SyntheticArtifact>();

      ByteArrayOutputStream baos = new ByteArrayOutputStream();

      Event soycEvent = SpeedTracerLogger.start(CompilerEventType.MAKE_SOYC_ARTIFACTS);

      Event recordSplitPoints = SpeedTracerLogger.start(
          CompilerEventType.MAKE_SOYC_ARTIFACTS, "phase", "recordSplitPoints");
      SplitPointRecorder.recordSplitPoints(jprogram, baos, logger);
      SyntheticArtifact splitPoints = new SyntheticArtifact(
          SoycReportLinker.class, "splitPoints" + permutationId + ".xml.gz", baos.toByteArray());
      soycArtifacts.add(splitPoints);
      recordSplitPoints.end();

      SyntheticArtifact sizeMaps = null;
      if (sizeBreakdowns != null) {
        Event recordSizeMap = SpeedTracerLogger.start(
            CompilerEventType.MAKE_SOYC_ARTIFACTS, "phase", "recordSizeMap");
        baos.reset();
        SizeMapRecorder.recordMap(logger, baos, sizeBreakdowns, jjsmap,
            internedLiteralByVariableName);
        sizeMaps = new SyntheticArtifact(
            SoycReportLinker.class, "stories" + permutationId + ".xml.gz", baos.toByteArray());
        soycArtifacts.add(sizeMaps);
        recordSizeMap.end();
      }

      if (sourceInfoMaps != null) {
        Event recordStories = SpeedTracerLogger.start(
            CompilerEventType.MAKE_SOYC_ARTIFACTS, "phase", "recordStories");
        baos.reset();
        StoryRecorder.recordStories(logger, baos, sourceInfoMaps, js);
        soycArtifacts.add(new SyntheticArtifact(
            SoycReportLinker.class, "detailedStories" + permutationId + ".xml.gz",
            baos.toByteArray()));
        recordStories.end();
      }

      if (dependencies != null) {
        soycArtifacts.add(dependencies);
      }

      // Set all of the main SOYC artifacts private.
      for (SyntheticArtifact soycArtifact : soycArtifacts) {
        soycArtifact.setVisibility(Visibility.Private);
      }

      if (!htmlReportsDisabled && sizeBreakdowns != null) {
        Event generateCompileReport = SpeedTracerLogger.start(
            CompilerEventType.MAKE_SOYC_ARTIFACTS, "phase", "generateCompileReport");
        ArtifactsOutputDirectory outDir = new ArtifactsOutputDirectory();
        SoycDashboard dashboard = new SoycDashboard(outDir);
        dashboard.startNewPermutation(Integer.toString(permutationId));
        try {
          dashboard.readSplitPoints(openWithGunzip(splitPoints));
          if (sizeMaps != null) {
            dashboard.readSizeMaps(openWithGunzip(sizeMaps));
          }
          if (dependencies != null) {
            dashboard.readDependencies(openWithGunzip(dependencies));
          }
          Memory.maybeDumpMemory("soycReadDependenciesEnd");
        } catch (ParserConfigurationException e) {
          throw new InternalCompilerException(
              "Error reading compile report information that was just generated", e);
        } catch (SAXException e) {
          throw new InternalCompilerException(
              "Error reading compile report information that was just generated", e);
        }
        dashboard.generateForOnePermutation();
        if (moduleMetricsArtifact != null && precompilationMetricsArtifact != null
            && compilationMetrics != null) {
          dashboard.generateCompilerMetricsForOnePermutation(
              moduleMetricsArtifact, precompilationMetricsArtifact, compilationMetrics);
        }
        soycArtifacts.addAll(outDir.getArtifacts());
        generateCompileReport.end();
      }

      soycEvent.end();

      return soycArtifacts;
View Full Code Here

      while (true) {
        counter++;
        if (Thread.interrupted()) {
          throw new InterruptedException();
        }
        Event optimizeJsEvent = SpeedTracerLogger.start(CompilerEventType.OPTIMIZE_JS);

        OptimizerStats stats = new OptimizerStats("Pass " + counter);

        // Remove unused functions if possible.
        stats.add(JsStaticEval.exec(jsProgram));
        // Inline Js function invocations
        stats.add(JsInliner.exec(jsProgram, toInline));
        // Remove unused functions if possible.
        stats.add(JsUnusedFunctionRemover.exec(jsProgram));

        // Save the stats to print out after optimizers finish.
        allOptimizerStats.add(stats);

        optimizeJsEvent.end();
        if ((optimizationLevel < OptionOptimize.OPTIMIZE_LEVEL_MAX && counter > optimizationLevel)
            || !stats.didChange()) {
          break;
        }
      }
View Full Code Here

  /**
   * Load everything cached on disk into memory.
   */
  private void loadUnitMap(TreeLogger logger, File currentCacheFile) {
    Event loadPersistentUnitEvent =
        SpeedTracerLogger.start(DevModeEventType.LOAD_PERSISTENT_UNIT_CACHE);
    if (logger.isLoggable(TreeLogger.TRACE)) {
      logger.log(TreeLogger.TRACE, "Looking for previously cached Compilation Units in "
          + cacheDirectory.getAbsolutePath());
    }
    try {
      if (cacheDirectory.isDirectory() && cacheDirectory.canRead()) {
        File[] files = getCacheFiles(cacheDirectory, true);
        for (File cacheFile : files) {
          FileInputStream fis = null;
          BufferedInputStream bis = null;
          ObjectInputStream inputStream = null;
          if (cacheFile.equals(currentCacheFile)) {
            continue;
          }
          boolean deleteCacheFile = false;
          try {
            fis = new FileInputStream(cacheFile);
            bis = new BufferedInputStream(fis);
            /*
             * It is possible for the next call to throw an exception, leaving
             * inputStream null and fis still live.
             */
            inputStream = new StringInterningObjectInputStream(bis);
            while (true) {
              CachedCompilationUnit unit = (CachedCompilationUnit) inputStream.readObject();
              if (unit == null) {
                break;
              }
              if (unit.getTypesSerializedVersion() != GwtAstBuilder.getSerializationVersion()) {
                continue;
              }
              UnitCacheEntry entry = new UnitCacheEntry(unit, UnitOrigin.PERSISTENT);
              UnitCacheEntry existingEntry = unitMap.get(unit.getResourcePath());
              /*
               * Don't assume that an existing entry is stale - an entry might
               * have been loaded already from another source like a
               * CompilationUnitArchive that is more up to date. If the
               * timestamps are the same, accept the latest version. If it turns
               * out to be stale, it will be recompiled and the updated unit
               * will win this test the next time the session starts.
               */
              if (existingEntry != null
                  && unit.getLastModified() >= existingEntry.getUnit().getLastModified()) {
                super.remove(existingEntry.getUnit());
                unitMap.put(unit.getResourcePath(), entry);
                unitMapByContentId.put(unit.getContentId(), entry);
              } else if (existingEntry == null) {
                unitMap.put(unit.getResourcePath(), entry);
                unitMapByContentId.put(unit.getContentId(), entry);
              }
            }
          } catch (EOFException ex) {
            // Go on to the next file.
          } catch (IOException ex) {
            deleteCacheFile = true;
            if (logger.isLoggable(TreeLogger.TRACE)) {
              logger.log(TreeLogger.TRACE, "Ignoring and deleting cache log "
                  + cacheFile.getAbsolutePath() + " due to read error.", ex);
            }
          } catch (ClassNotFoundException ex) {
            deleteCacheFile = true;
            if (logger.isLoggable(TreeLogger.TRACE)) {
              logger.log(TreeLogger.TRACE, "Ignoring and deleting cache log "
                  + cacheFile.getAbsolutePath() + " due to deserialization error.", ex);
            }
          } finally {
            Utility.close(inputStream);
            Utility.close(bis);
            Utility.close(fis);
          }
          if (deleteCacheFile) {
            cacheFile.delete();
          } else {
            if (logger.isLoggable(TreeLogger.TRACE)) {
              logger.log(TreeLogger.TRACE, cacheFile.getName() + ": Load complete");
            }
          }
        }
      } else {
        logger
            .log(TreeLogger.TRACE,
                "Starting with empty Cache: CompilationUnit cache "
                    + "directory does not exist or is not readable.");
      }
    } finally {
      loadPersistentUnitEvent.end();
    }
  }
View Full Code Here

   * @param anonymousClassMap a map between the anonymous class names of java
   *          compiler used to compile code and jdt. Emma-specific.
   */
  public byte[] rewrite(TypeOracle typeOracle, String className,
      byte[] classBytes, Map<String, String> anonymousClassMap) {
    Event classBytesRewriteEvent =
        SpeedTracerLogger.start(DevModeEventType.CLASS_BYTES_REWRITE, "Class Name", className);
    String desc = toDescriptor(className);
    assert (!jsoIntfDescs.contains(desc));

    // The ASM model is to chain a bunch of visitors together.
    ClassWriter writer = new ClassWriter(0);
    ClassVisitor v = writer;

    // v = new CheckClassAdapter(v);
    // v = new TraceClassVisitor(v, new PrintWriter(System.out));
    v = new UseMirroredClasses(v, className);

    v = new RewriteSingleJsoImplDispatches(v, typeOracle, jsoData);

    v = new RewriteRefsToJsoClasses(v, jsoIntfDescs, mapper);

    if (jsoImplDescs.contains(desc)) {
      v = WriteJsoImpl.create(v, desc, jsoIntfDescs, mapper, jsoData);
    }

    v = new RewriteJsniMethods(v, anonymousClassMap);

    if (Double.parseDouble(System.getProperty("java.class.version")) < Opcodes.V1_6) {
      v = new ForceClassVersion15(v);
    }

    new ClassReader(classBytes).accept(v, 0);
    classBytesRewriteEvent.end();
    return writer.toByteArray();
  }
View Full Code Here

  public abstract UnifiedAst precompile(RebindPermutationOracle rpo, String[] entryPointTypeNames,
      String[] additionalRootTypes, boolean singlePermutation,
      PrecompilationMetricsArtifact precompilationMetrics) throws UnableToCompleteException;

  protected final void optimizeJavaToFixedPoint() throws InterruptedException {
    Event optimizeEvent = SpeedTracerLogger.start(CompilerEventType.OPTIMIZE);

    List<OptimizerStats> allOptimizerStats = new ArrayList<OptimizerStats>();
    int passCount = 0;
    int nodeCount = jprogram.getNodeCount();
    int lastNodeCount;

    boolean atMaxLevel = options.getOptimizationLevel() == OptionOptimize.OPTIMIZE_LEVEL_MAX;
    int passLimit = atMaxLevel ? MAX_PASSES : options.getOptimizationLevel();
    float minChangeRate = atMaxLevel ? FIXED_POINT_CHANGE_RATE : EFFICIENT_CHANGE_RATE;
    while (true) {
      passCount++;
      if (passCount > passLimit) {
        break;
      }
      if (Thread.interrupted()) {
        optimizeEvent.end();
        throw new InterruptedException();
      }
      AstDumper.maybeDumpAST(jprogram);
      OptimizerStats stats = optimizeJavaOneTime("Pass " + passCount, nodeCount);
      allOptimizerStats.add(stats);
      lastNodeCount = nodeCount;
      nodeCount = jprogram.getNodeCount();

      float nodeChangeRate = stats.getNumMods() / (float) lastNodeCount;
      float sizeChangeRate = (lastNodeCount - nodeCount) / (float) lastNodeCount;
      if (nodeChangeRate <= minChangeRate && sizeChangeRate <= minChangeRate) {
        break;
      }
    }

    if (options.shouldOptimizeDataflow()) {
      // Just run it once, because it is very time consuming
      allOptimizerStats.add(DataflowOptimizer.exec(jprogram));
    }

    printJavaOptimizeTrace(allOptimizerStats);

    optimizeEvent.end();
  }
View Full Code Here

      eot.logResultsDetailed(logger, TreeLogger.WARN);
    }
  }

  private OptimizerStats optimizeJavaOneTime(String passName, int numNodes) {
    Event optimizeEvent = SpeedTracerLogger.start(CompilerEventType.OPTIMIZE, "phase", "loop");
    // Clinits might have become empty become empty.
    jprogram.typeOracle.recomputeAfterOptimizations(jprogram.getDeclaredTypes());
    OptimizerStats stats = new OptimizerStats(passName);
    stats.add(Pruner.exec(jprogram, true).recordVisits(numNodes));
    stats.add(Finalizer.exec(jprogram).recordVisits(numNodes));
    stats.add(MakeCallsStatic.exec(jprogram, options.shouldAddRuntimeChecks())
        .recordVisits(numNodes));
    stats.add(TypeTightener.exec(jprogram).recordVisits(numNodes));
    stats.add(MethodCallTightener.exec(jprogram).recordVisits(numNodes));
    // Note: Specialization should be done before inlining.
    stats.add(MethodCallSpecializer.exec(jprogram).recordVisits(numNodes));
    stats.add(DeadCodeElimination.exec(jprogram).recordVisits(numNodes));
    stats.add(MethodInliner.exec(jprogram).recordVisits(numNodes));
    if (options.shouldInlineLiteralParameters()) {
      stats.add(SameParameterValueOptimizer.exec(jprogram).recordVisits(numNodes));
    }
    if (options.shouldOrdinalizeEnums()) {
      stats.add(EnumOrdinalizer.exec(jprogram).recordVisits(numNodes));
    }
    optimizeEvent.end();
    return stats;
  }
View Full Code Here

  /**
   * Static entry point used by JavaToJavaScriptCompiler.
   */
  public static OptimizerStats exec(JsProgram program, Collection<JsNode> toInline) {
    Event optimizeJsEvent = SpeedTracerLogger.start(
        CompilerEventType.OPTIMIZE_JS, "optimizer", NAME);
    OptimizerStats stats = execImpl(program, toInline);
    optimizeJsEvent.end("didChange", "" + stats.didChange());
    return stats;
  }
View Full Code Here

  @Override
  public void onModuleReady(ModuleSpace readySpace)
      throws UnableToCompleteException {
    this.space = readySpace;

    Event moduleSpaceHostReadyEvent = SpeedTracerLogger.start(DevModeEventType.MODULE_SPACE_HOST_READY);
    try {
      // Establish an environment for JavaScript property providers to run.
      //
      ModuleSpacePropertyOracle propOracle = new ModuleSpacePropertyOracle(
          module.getProperties(), module.getActiveLinkerNames(), readySpace);

      // Set up the rebind oracle for the module.
      // It has to wait until now because we need to inject javascript.
      //
      Rules rules = module.getRules();
      PrecompileTaskOptionsImpl options = new PrecompileTaskOptionsImpl();
      options.setGenDir(genDir);
      CompilerContext compilerContext =
          new CompilerContext.Builder().module(module).options(options).build();
      StandardGeneratorContext genCtx =
          new StandardGeneratorContext(compilerContext, compilationState, new ArtifactSet(), false);

      // Only enable generator result caching if we have a valid rebindCache
      genCtx.setGeneratorResultCachingEnabled((rebindCache != null));

      rebindOracle = new StandardRebindOracle(propOracle, rules, genCtx);
      rebindOracle.setRebindCache(rebindCache);

      // Create a completely isolated class loader which owns all classes
      // associated with a particular module. This effectively builds a
      // separate 'domain' for each running module, so that they all behave as
      // though they are running separately. This allows the shell to run
      // multiple modules, both in succession and simultaneously, without getting
      // confused.
      //
      // Note that the compiling class loader has no parent. This keeps it from
      // accidentally 'escaping' its domain and loading classes from the system
      // class loader (the one that loaded the shell itself).
      //
      classLoader = new CompilingClassLoader(logger, compilationState, readySpace);
    } finally {
      moduleSpaceHostReadyEvent.end();
    }
  }
View Full Code Here

TOP

Related Classes of com.google.gwt.dev.util.log.speedtracer.SpeedTracerLogger.Event

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.