Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize CodeGen for executable jar #41449

Closed
Show file tree
Hide file tree
Changes from 15 commits
Commits
Show all changes
186 commits
Select commit Hold shift + click to select a range
4446deb
Add DeadCodeAnalyzer
Thushara-Piyasekara Aug 6, 2023
8f59baa
Add dead code detection for functions and anonymous functions
Thushara-Piyasekara Aug 9, 2023
fe80423
Add comments and optimizations
Thushara-Piyasekara Aug 9, 2023
69ab405
Add Dead Code Detection for multiple modules
Thushara-Piyasekara Aug 17, 2023
4b81d66
Merge branch 'ballerina-platform:master' into dce-project
Thushara-Piyasekara Aug 17, 2023
c6f2f37
Merge branch 'ballerina-platform:master' into dce-project
Thushara-Piyasekara Aug 17, 2023
48c8eff
Add function invocation persistence through modifying BIR
Thushara-Piyasekara Sep 13, 2023
22b7f5c
Add deletion of unused top level functions from thin jars
Thushara-Piyasekara Sep 22, 2023
c470d66
Remove ModuleData class. Optimize DeadCodeAnalyzer
Thushara-Piyasekara Sep 26, 2023
a595764
Add comments. Fix certain langlib children not being updated
Thushara-Piyasekara Sep 26, 2023
e0dd9f1
Merge branch 'master' of https://github.com/ballerina-platform/baller…
Thushara-Piyasekara Sep 26, 2023
a20f735
Add file license signatures and optimizations
Thushara-Piyasekara Sep 26, 2023
5608d22
Minor optimizations
Thushara-Piyasekara Sep 27, 2023
95628fa
Fix certain child functions not being added to parent symbol
Thushara-Piyasekara Sep 27, 2023
defaf7a
Fix certain child functions not being added to parent symbol
Thushara-Piyasekara Sep 27, 2023
a0abba1
Optimize code according to best practices and suggestions
Thushara-Piyasekara Oct 2, 2023
18b3939
Refactor CompilerPhaseRunner
Thushara-Piyasekara Oct 3, 2023
0709ffd
Improve Resource function handling logic
Thushara-Piyasekara Oct 3, 2023
70012d7
Refactor licence and variable declarations
Thushara-Piyasekara Oct 5, 2023
5554b7e
Refactor file separator
Thushara-Piyasekara Oct 5, 2023
e5beb48
Add BIRDeadNodeAnalyzer
Thushara-Piyasekara Oct 12, 2023
b9f9136
Add detection and deletion of unused Type Definitions
Thushara-Piyasekara Oct 18, 2023
5c20bdb
Add optimized Thin JAR object generation
Thushara-Piyasekara Oct 27, 2023
188ca81
Add BIR TypeDefAnalyzer
Thushara-Piyasekara Oct 31, 2023
a9c077a
Add documentation for TypeDefAnalyzer
Thushara-Piyasekara Oct 31, 2023
e00b11b
Add analyzer support for cyclic typeDefs and typeDef function calls
Thushara-Piyasekara Nov 1, 2023
d7c9b67
Refactor the analyzer algorithm
Thushara-Piyasekara Nov 15, 2023
b0fb559
Add interop dependencies white listing
Thushara-Piyasekara Nov 20, 2023
01a3cd3
Merge with master
Thushara-Piyasekara Nov 20, 2023
42f882c
Fix TypeDefAnalyzer bugs and refactor code
Thushara-Piyasekara Dec 1, 2023
bec52b3
Handle null pointer exceptions in BIRNode.getPackageID
Thushara-Piyasekara Dec 1, 2023
f7c5625
Add new entries for interop-dependencies
Thushara-Piyasekara Dec 1, 2023
925203e
Refactor DeadBIRNodeAnalyzer
Thushara-Piyasekara Dec 1, 2023
e4e21f8
Add unused module elimination
Thushara-Piyasekara Dec 20, 2023
e727315
Add compilation support for langlibs
Thushara-Piyasekara Dec 20, 2023
51920be
Sync with master
Thushara-Piyasekara Dec 20, 2023
d34b75c
Add RecordDefaultFPLoad instruction optimization support
Thushara-Piyasekara Jan 8, 2024
9e72e0e
Merge branch 'ballerina-platform:master' into dce-project
Thushara-Piyasekara Jan 12, 2024
8c5ae60
Add native bytecode optimizer
Thushara-Piyasekara Jan 22, 2024
8ff9437
Revert langlib compilation
Thushara-Piyasekara Jan 23, 2024
edb1d5d
Merge branch 'master' of https://github.com/ballerina-platform/baller…
Thushara-Piyasekara Jan 24, 2024
5c6a813
Merge branch 'master' of https://github.com/ballerina-platform/baller…
Thushara-Piyasekara Feb 1, 2024
42e2b5c
Revert to original PackageID assignment
Thushara-Piyasekara Feb 1, 2024
23bf5c9
Add interop dependencies for ballerina/sql library
Thushara-Piyasekara Feb 2, 2024
a05d921
Add new CLI output for optimized build
Thushara-Piyasekara Feb 2, 2024
468f227
Add condition check for optimized build
Thushara-Piyasekara Feb 2, 2024
da7f9cb
Refactor deprecated analyzer names
Thushara-Piyasekara Feb 2, 2024
005e464
Refactor license signatures for newly added files
Thushara-Piyasekara Feb 2, 2024
1ad3fbd
Add null check for markSelfAndChildrenAsUsed function
Thushara-Piyasekara Feb 6, 2024
cf98615
Add logic for handling whitelisted packages
Thushara-Piyasekara Feb 6, 2024
2c59bcb
Refactor LargeMethodOptimizer
Thushara-Piyasekara Feb 6, 2024
13361ff
Add missed attribute analyzing for BStreamType
Thushara-Piyasekara Feb 6, 2024
010e323
Update interop-dependency version
Thushara-Piyasekara Feb 6, 2024
3362cc3
Add duration reports for codegen optimization
Thushara-Piyasekara Feb 6, 2024
8ef8c03
Refactor JBallerinaBackend
Thushara-Piyasekara Feb 6, 2024
c1dae94
Add reflection and driver class whitelisting
Thushara-Piyasekara Feb 6, 2024
1268c79
Add reflection handling for NativeDependencyOptimizer
Thushara-Piyasekara Feb 6, 2024
70dd025
Improve logic for function pointer handling
Thushara-Piyasekara Feb 6, 2024
e6303fd
Whitelist bal files with interop dependency types
Thushara-Piyasekara Feb 6, 2024
64060b3
Refactor UsedTypeDefAnalyzer function names
Thushara-Piyasekara Feb 6, 2024
7ea07cd
Refactor UsedTypeDefAnalyzer function names
Thushara-Piyasekara Feb 6, 2024
6b6c0f4
Merge branch 'dce-project' of https://github.com/Thushara-Piyasekara/…
Thushara-Piyasekara Feb 6, 2024
7028325
Merge branch 'master' of https://github.com/ballerina-platform/baller…
Thushara-Piyasekara Feb 6, 2024
d42be9b
Remove deprecated DCE algorithms
Thushara-Piyasekara Feb 6, 2024
d8dca7e
Refactor JBallerinaBackend
Thushara-Piyasekara Feb 7, 2024
66a4db4
Update interop-dependencies.properties
Thushara-Piyasekara Feb 7, 2024
1c55fce
Refactor NativeDependencyOptimizer
Thushara-Piyasekara Feb 8, 2024
f466f7c
Remove unused code in JBallerinaBackend
Thushara-Piyasekara Feb 8, 2024
8bc6b29
Remove unused code
Thushara-Piyasekara Feb 8, 2024
45c1b82
Remove unused code
Thushara-Piyasekara Feb 8, 2024
83d9fc1
Remove unused code and files
Thushara-Piyasekara Feb 8, 2024
7dd2615
Refactor logic for UsedBIRNodeAnalyzer and UsedTypeDefAnalyzer
Thushara-Piyasekara Feb 9, 2024
2d32ad0
Refactor high level logic for CodeGen optimization
Thushara-Piyasekara Feb 14, 2024
55027fb
Update interop-dependencies for latest http package
Thushara-Piyasekara Feb 16, 2024
aad44a0
Change builtin PackageID with parent PackageId
Thushara-Piyasekara Feb 16, 2024
565728c
Update TypeModelTest compatibility for Table types
Thushara-Piyasekara Feb 16, 2024
5a130dc
Add analyzer support for table type
Thushara-Piyasekara Feb 17, 2024
19310df
Add fix for handling multiple reference types for the same parent type
Thushara-Piyasekara Feb 17, 2024
21a02ef
Refactor duplicate code into single functions
Thushara-Piyasekara Feb 20, 2024
ca4f440
Fix review suggestions
Thushara-Piyasekara Feb 20, 2024
f8abff6
Refactor ClassNodeVisitor
Thushara-Piyasekara Feb 20, 2024
8685780
Change bir optimized jar file name
Thushara-Piyasekara Feb 20, 2024
fcf88bc
Fix record default fields containing function pointers not being dete…
Thushara-Piyasekara Feb 20, 2024
0918c07
Restore max memory heap size to original
Thushara-Piyasekara Feb 22, 2024
7578783
Refactor according to review suggestions
Thushara-Piyasekara Feb 26, 2024
a968f3e
Add optimization support for testablePkgs
Thushara-Piyasekara Feb 27, 2024
189fb92
Add bir optimization support for test command
Thushara-Piyasekara Mar 4, 2024
c13b0d8
Fix testablePkg birFunctions not being analyzed
Thushara-Piyasekara Mar 5, 2024
878c50c
Refactor optimized test CLI messages
Thushara-Piyasekara Mar 5, 2024
441e85a
Fix mock functions being labeled as UNUSED
Thushara-Piyasekara Mar 6, 2024
4862435
Add duplicate thin jar generation for testing
Thushara-Piyasekara Mar 14, 2024
74ac27d
Resolve merge conflicts
Thushara-Piyasekara Apr 3, 2024
ee5878c
Add working version of the duplicate codegen
Thushara-Piyasekara Apr 3, 2024
819c694
Add support for $moduleInit() chain invocation
Thushara-Piyasekara Apr 4, 2024
e9e76b2
Refactor _DUPLICATE prefix with _OPTIMIZED
Thushara-Piyasekara Apr 9, 2024
ea13e22
Refactor logic for adding optimized library paths
Thushara-Piyasekara Apr 9, 2024
cbdbf22
Resolve merge conflicts
Thushara-Piyasekara Apr 10, 2024
9fdd241
Merge branch 'master' of https://github.com/ballerina-platform/baller…
Thushara-Piyasekara Apr 10, 2024
bcf932a
Refactor immutable type optimization
Thushara-Piyasekara Apr 11, 2024
771d601
Merge branch 'dce-project' of https://github.com/Thushara-Piyasekara/…
Thushara-Piyasekara Apr 13, 2024
4644530
Fix checkStyle violations
Thushara-Piyasekara Apr 13, 2024
6f8ad58
Add json report generation for testing
Thushara-Piyasekara Apr 16, 2024
1573406
Fix function pointer types not being analyzed
Thushara-Piyasekara Apr 17, 2024
b26b426
Add bytecode optimization for single file projects
Thushara-Piyasekara Apr 17, 2024
b2fb96d
Fix error types being marked as unused
Thushara-Piyasekara Apr 17, 2024
79a220a
Add SingleFileProject tests
Thushara-Piyasekara Apr 19, 2024
f3ff3e7
Fix FPs not being marked as used in different bbs
Thushara-Piyasekara Apr 22, 2024
5f72553
Fix unused submodules not being optimized
Thushara-Piyasekara Apr 24, 2024
f393348
Add new SingleFileProject test cases
Thushara-Piyasekara Apr 24, 2024
81cd78f
Add initial build project tests
Thushara-Piyasekara May 6, 2024
1d2d0c0
Refactor test resources directory structure
Thushara-Piyasekara May 7, 2024
2fcfa82
Add verbose flag for report generation
Thushara-Piyasekara May 7, 2024
3dce8f0
Add NativeDependencyOptimizationReport generation
Thushara-Piyasekara May 7, 2024
04cee13
Add build project test cases
Thushara-Piyasekara May 8, 2024
8d364fa
Add initial tests for bytecode optimizer
Thushara-Piyasekara May 10, 2024
1069269
Add class compilation for test project native libs
Thushara-Piyasekara May 13, 2024
3ba106d
Add new tests
Thushara-Piyasekara May 13, 2024
71a4c50
Add worker related unit tests
Thushara-Piyasekara May 14, 2024
b2939cf
Add client and listener related unit tests
Thushara-Piyasekara May 15, 2024
37f6180
Add anonymous function usage tests
Thushara-Piyasekara May 15, 2024
dd1e18d
Add licencing headers for tests
Thushara-Piyasekara May 16, 2024
a0ec8d8
Fix wrong package name in unit test expected json
Thushara-Piyasekara May 22, 2024
09a7cbe
Add ExternalDependency white listing
Thushara-Piyasekara May 22, 2024
586711a
Add null check for annotation check
Thushara-Piyasekara May 27, 2024
2f3da76
Merge branch 'master' of https://github.com/ballerina-platform/baller…
Thushara-Piyasekara May 27, 2024
0c82b8e
Fix merge conflicts
Thushara-Piyasekara May 27, 2024
e5a6144
Add version independent typedef whitelisting
Thushara-Piyasekara May 27, 2024
d399873
Fix checkstyle violations
Thushara-Piyasekara May 28, 2024
e14fa37
Fix getJarFilePathsRequiredForExecution() overload
Thushara-Piyasekara May 28, 2024
6160a5d
Fix spotbugs violations
Thushara-Piyasekara May 28, 2024
79828e4
Fix spotbugs violations
Thushara-Piyasekara May 28, 2024
fa2644d
Add temporary fix for static field value retention
Thushara-Piyasekara May 29, 2024
62e1173
Add string constants for optimized jar identifier
Thushara-Piyasekara May 31, 2024
042adab
Refactor common dependency identification logic
Thushara-Piyasekara May 31, 2024
c4d9c98
Fix CNF error for optimized testing
Thushara-Piyasekara Jun 2, 2024
bcb7b14
Fix testable pkg dependencies being optimized
Thushara-Piyasekara Jun 2, 2024
7a6aba7
Fix optimized jars not being added to classpath
Thushara-Piyasekara Jun 3, 2024
e4e0670
Add temporary fix for test imports being optimized
Thushara-Piyasekara Jun 3, 2024
c3ed36e
Fix checkstyle violations
Thushara-Piyasekara Jun 3, 2024
0443dc3
Fix spotbugs violations
Thushara-Piyasekara Jun 3, 2024
591d916
Fix spotbugs violations
Thushara-Piyasekara Jun 3, 2024
c812e40
Add missing headers and javadoc comments
Thushara-Piyasekara Jun 3, 2024
244389f
Refactor according to review suggestions
Thushara-Piyasekara Jun 4, 2024
63f94e5
Update licensing and javadocs
Thushara-Piyasekara Jun 4, 2024
e7341c1
Fix testable pkg analysis affecting optimized JAR
Thushara-Piyasekara Jun 5, 2024
7ac189d
Add constants for String references
Thushara-Piyasekara Jun 5, 2024
48b2df1
Fix review suggestions
Thushara-Piyasekara Jun 6, 2024
aa8254a
Fix review suggestions
Thushara-Piyasekara Jun 6, 2024
b8e47f2
Fix review suggestions
Thushara-Piyasekara Jun 6, 2024
199a5c1
Fix imported global vars not being marked as used
Thushara-Piyasekara Jun 7, 2024
93679cf
Fix review suggestions
Thushara-Piyasekara Jun 7, 2024
348d281
Merge branch 'fix-42367' of https://github.com/Thushara-Piyasekara/ba…
Thushara-Piyasekara Jun 7, 2024
f1253d2
Fix merge conflicts
Thushara-Piyasekara Jun 7, 2024
ad9bfc4
Fix CheckStyle violations
Thushara-Piyasekara Jun 7, 2024
d8e6c2c
Fix NativeDependencyOptimizationTests failure
Thushara-Piyasekara Jun 10, 2024
da8a75f
Fix NativeDependencyOptimizationTests failure
Thushara-Piyasekara Jun 11, 2024
dcdf514
Fix checkstyle violations
Thushara-Piyasekara Jun 11, 2024
9996ad2
Fix review suggestions
Thushara-Piyasekara Jun 11, 2024
a944fe9
Add --verbose flag usage validation
Thushara-Piyasekara Jun 12, 2024
d5b3c1a
Add jacoco for NativeDependencyOptimizationTests
Thushara-Piyasekara Jun 12, 2024
1404541
Remove CLI optimization report emitter
Thushara-Piyasekara Jun 13, 2024
75a2ccc
Add tests for optimized test suite execution
Thushara-Piyasekara Jun 13, 2024
f2db0cb
Add unix output for OptimizedExecutableTestingTest
Thushara-Piyasekara Jun 14, 2024
1a166f6
Refactor "verbose" flag to "optimize-report"
Thushara-Piyasekara Jun 14, 2024
0090712
Fix review suggestions
Thushara-Piyasekara Jun 14, 2024
c4d7a21
Add conditional init for optimizer related fields
Thushara-Piyasekara Jun 14, 2024
39e2712
Add optimize flag validation for JarResolver
Thushara-Piyasekara Jun 14, 2024
6613f81
Add optimize flag validation for jar packing
Thushara-Piyasekara Jun 14, 2024
6c2a0bb
Refactor common dependency marking logic for tests
Thushara-Piyasekara Jun 17, 2024
52e8654
Refactor unusedPackageID variable names
Thushara-Piyasekara Jun 17, 2024
39f77f3
Make CodeGenOptimizationReportEmitter singleton
Thushara-Piyasekara Jun 17, 2024
c2811f5
Refactor optimization report path resolving logic
Thushara-Piyasekara Jun 19, 2024
faf3d74
Fix merge conflicts
Thushara-Piyasekara Jun 19, 2024
f1840d7
Fix review suggestions
Thushara-Piyasekara Jun 20, 2024
7a9bcba
Fix review suggestions
Thushara-Piyasekara Jun 24, 2024
b77a625
Fix review suggestions
Thushara-Piyasekara Jun 24, 2024
305ac9a
Merge branch 'master' of https://github.com/ballerina-platform/baller…
Thushara-Piyasekara Jun 24, 2024
4dd18cd
Move static compilation options to the builder
Thushara-Piyasekara Jun 25, 2024
808143a
Fix review suggestions
Thushara-Piyasekara Jun 25, 2024
ca52755
Use reflection to reset static fields in unit test
Thushara-Piyasekara Jun 25, 2024
4adf6aa
Fix review suggestions
Thushara-Piyasekara Jun 26, 2024
1c1deb1
Fix CheckStyle violations
Thushara-Piyasekara Jun 26, 2024
35878b7
Fix used submodules being marked as unused
Thushara-Piyasekara Jun 26, 2024
c8c56ff
Fix review suggestions
Thushara-Piyasekara Jun 26, 2024
4135956
Fix checkStyle violations
Thushara-Piyasekara Jun 27, 2024
eb164e9
Fix review suggestions
Thushara-Piyasekara Jun 27, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
* Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved.
Thushara-Piyasekara marked this conversation as resolved.
Show resolved Hide resolved
*
* WSO2 LLC. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.ballerina.projects;

import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;

import java.util.HashSet;

/**
* This visitor replaces unused functions with null
*/
public class DeadFunctionVisitor extends ClassVisitor {

private final HashSet<String> deadFunctionNames;

public DeadFunctionVisitor(int api, ClassWriter cw, HashSet<String> deadFunctionNames) {

Thushara-Piyasekara marked this conversation as resolved.
Show resolved Hide resolved
super(api, cw);
this.deadFunctionNames = deadFunctionNames;
}

@Override
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {

MethodVisitor methodVisitor;
if (!name.contains("init") && deadFunctionNames.contains(name)) {
methodVisitor = null;
Thushara-Piyasekara marked this conversation as resolved.
Show resolved Hide resolved
} else {
methodVisitor = super.visitMethod(access, name, desc, signature, exceptions);
}
return methodVisitor;
}
}
Thushara-Piyasekara marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
import org.apache.commons.compress.archivers.jar.JarArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntryPredicate;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.commons.compress.archivers.zip.ZipFile;
import org.apache.commons.io.FilenameUtils;
import org.ballerinalang.maven.Dependency;
import org.ballerinalang.maven.MavenResolver;
Expand All @@ -40,6 +39,8 @@
import org.wso2.ballerinalang.compiler.bir.codegen.CodeGenerator;
import org.wso2.ballerinalang.compiler.bir.codegen.interop.InteropValidator;
import org.wso2.ballerinalang.compiler.semantics.analyzer.ObservabilitySymbolCollectorRunner;
import org.wso2.ballerinalang.compiler.semantics.model.symbols.BInvokableSymbol;
import org.wso2.ballerinalang.compiler.semantics.model.symbols.BPackageSymbol;
import org.wso2.ballerinalang.compiler.spi.ObservabilitySymbolCollector;
import org.wso2.ballerinalang.compiler.tree.BLangPackage;
import org.wso2.ballerinalang.compiler.util.CompilerContext;
Expand Down Expand Up @@ -453,7 +454,10 @@ private Manifest createManifest() {
private void copyJar(ZipArchiveOutputStream outStream, JarLibrary jarLibrary,
HashMap<String, JarLibrary> copiedEntries, HashMap<String, StringBuilder> services) throws IOException {

ZipFile zipFile = new ZipFile(jarLibrary.path().toFile());
String pkgName = jarLibrary.packageName().get();
Thushara-Piyasekara marked this conversation as resolved.
Show resolved Hide resolved
HashMap<String, HashSet<String>> classWiseDeadFunctionMap = getDeadFunctionList(pkgName, this.compilerContext);
Thushara-Piyasekara marked this conversation as resolved.
Show resolved Hide resolved

OptimisedZipFile zipFile = new OptimisedZipFile(jarLibrary.path().toFile(),classWiseDeadFunctionMap);
Thushara-Piyasekara marked this conversation as resolved.
Show resolved Hide resolved
ZipArchiveEntryPredicate predicate = entry -> {
String entryName = entry.getName();
if (entryName.equals("META-INF/MANIFEST.MF")) {
Expand Down Expand Up @@ -501,10 +505,31 @@ private void copyJar(ZipArchiveOutputStream outStream, JarLibrary jarLibrary,

// Transfers selected entries from this zip file to the output stream, while preserving its compression and
// all the other original attributes.
zipFile.copyRawEntries(outStream, predicate);
zipFile.copyOptimisedRawEntries(outStream, predicate);
// zipFile.copyRawEntries(outStream, predicate);
zipFile.close();
}

private static HashMap<String, HashSet<String>> getDeadFunctionList(String pkgName, CompilerContext compilerContext) {
org.wso2.ballerinalang.compiler.PackageCache packageCache = org.wso2.ballerinalang.compiler.PackageCache.getInstance(compilerContext);
prakanth97 marked this conversation as resolved.
Show resolved Hide resolved

BPackageSymbol pkgSymbol = packageCache.getSymbol(pkgName);
int majorVersion = packageCache.getSymbol(pkgName).descriptor.version().value().major();

HashMap<String, HashSet<String>> classWiseDeadFunctionMap = new HashMap<>();

for (BInvokableSymbol deadFunction:pkgSymbol.deadFunctions) {
if (deadFunction.source != null) {
String className = deadFunction.source.replace(".bal", ".class");
String classLocationName = pkgName + "/" + majorVersion + "/" + className;
Thushara-Piyasekara marked this conversation as resolved.
Show resolved Hide resolved
classWiseDeadFunctionMap.putIfAbsent(classLocationName, new HashSet<>());
classWiseDeadFunctionMap.get(classLocationName).add(deadFunction.originalName.value);
}
}

return classWiseDeadFunctionMap;
}

private static boolean isCopiedEntry(String entryName, HashMap<String, JarLibrary> copiedEntries) {
return copiedEntries.keySet().contains(entryName);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
import org.ballerinalang.model.elements.Flag;
import org.ballerinalang.model.elements.PackageID;
import org.wso2.ballerinalang.compiler.BIRPackageSymbolEnter;
import org.wso2.ballerinalang.compiler.bir.model.BIRNode;
import org.wso2.ballerinalang.compiler.bir.writer.BIRBinaryWriter;
import org.wso2.ballerinalang.compiler.diagnostic.BLangDiagnosticLocation;
import org.wso2.ballerinalang.compiler.semantics.analyzer.SymbolEnter;
Expand All @@ -44,6 +45,7 @@

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
Expand All @@ -54,6 +56,7 @@
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;

import static org.ballerinalang.model.tree.SourceKind.REGULAR_SOURCE;
import static org.ballerinalang.model.tree.SourceKind.TEST_SOURCE;
Expand Down Expand Up @@ -298,7 +301,11 @@ ModuleCompilationState currentCompilationState() {
} else if (this.project().kind() == ProjectKind.BUILD_PROJECT
&& !this.project.buildOptions().enableCache()) {
moduleCompState = ModuleCompilationState.LOADED_FROM_SOURCES;
} else {
}
// else if (!this.moduleDescriptor.packageName().toString().contains("lang") && !this.moduleDescriptor.packageName().toString().contains("jballerina")) {
// moduleCompState = ModuleCompilationState.LOADED_FROM_SOURCES;
// }
else {
moduleCompState = ModuleCompilationState.LOADED_FROM_CACHE;
}
return moduleCompState;
Expand Down Expand Up @@ -476,6 +483,11 @@ static void generateCodeInternal(ModuleContext moduleContext,
return;
}

// Eliminates dead BIR function nodes from BUILD_PROJECT
if (moduleContext.project.kind().equals(ProjectKind.BUILD_PROJECT)) {
// eliminateDeadFunctionsFromBIR(moduleContext);
}

// Generate and write the thin JAR to the file system
compilerBackend.performCodeGen(moduleContext, moduleContext.compilationCache);

Expand Down Expand Up @@ -540,6 +552,41 @@ static void loadBirBytesInternal(ModuleContext moduleContext) {
moduleContext.birBytes = moduleContext.compilationCache.getBir(moduleContext.moduleName());
}

/**
* Removes the dead BIRFunction nodes from BIR of the package Symbol of the given context
* @param moduleContext Module context holding the bir
*/
public static void eliminateDeadFunctionsFromBIR(ModuleContext moduleContext) {
HashSet<String> deadFunctionNames = new HashSet<>();
moduleContext.bLangPackage().symbol.deadFunctions.forEach((deadSymbol) -> {
deadFunctionNames.add(deadSymbol.getName().value);
});

// Filtering out the unused topLevel BIRFunctions
List<BIRNode.BIRFunction> deadBIRFunctions = new ArrayList<>();
Predicate<BIRNode.BIRFunction> isTopLevelDeadFunction = birFunction -> deadFunctionNames.contains(birFunction.originalName.getValue());
for (BIRNode.BIRFunction birFunction : moduleContext.bLangPackage().symbol.bir.functions) {
if (isTopLevelDeadFunction.test(birFunction)) {
deadBIRFunctions.add(birFunction);
}
}
moduleContext.bLangPackage().symbol.bir.functions.removeAll(deadBIRFunctions);

// Filtering out the unused classLevel BIRFunctions
List<BIRNode.BIRTypeDefinition> typeDefs = moduleContext.bLangPackage.symbol.bir.typeDefs;
for (BIRNode.BIRTypeDefinition typeDefinition : typeDefs) {
Predicate<BIRNode.BIRFunction> isClassLevelDeadFunction = birFunction -> deadFunctionNames.contains(typeDefinition.name.getValue() + "." + birFunction.originalName.getValue());
List<BIRNode.BIRFunction> classLevelDeadFunctions = new ArrayList<>();
for (BIRNode.BIRFunction birFunction : typeDefinition.attachedFuncs) {
if (isClassLevelDeadFunction.test(birFunction)) {
classLevelDeadFunctions.add(birFunction);
}
}
typeDefinition.attachedFuncs.removeAll(classLevelDeadFunctions);
}
}


static void resolveDependenciesFromBALAInternal(ModuleContext moduleContext) {
// TODO implement
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/*
* Copyright (c) 2023, WSO2 LLC. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 LLC. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.ballerina.projects;

import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntryPredicate;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.commons.compress.archivers.zip.ZipFile;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;

import static java.util.Objects.requireNonNull;

/**
* Eliminates the unused methods from the output stream of the given zip file
*
*/
public class OptimisedZipFile extends ZipFile {
private final HashMap<String, HashSet<String>> deadFunctionMap;

public OptimisedZipFile(File file, HashMap<String, HashSet<String>> deadFunctionMap) throws IOException {
super(file);
this.deadFunctionMap = deadFunctionMap;
}

public void copyOptimisedRawEntries(final ZipArchiveOutputStream target, final ZipArchiveEntryPredicate predicate) throws IOException {
final Enumeration<ZipArchiveEntry> src = getEntriesInPhysicalOrder();
while (src.hasMoreElements()) {
final ZipArchiveEntry entry = src.nextElement();
if (predicate.test( entry)) {
Thushara-Piyasekara marked this conversation as resolved.
Show resolved Hide resolved
if (!entry.getName().contains("init.class") && deadFunctionMap.containsKey(entry.getName())) {
target.putArchiveEntry(entry);
target.write(getOptimizedEntry(entry));
target.closeArchiveEntry();
} else {
target.addRawArchiveEntry(entry, getRawInputStream(entry));
}
}
}
}

public byte[] getOptimizedEntry(ZipArchiveEntry originalEntry) throws IOException {
InputStream inputStream = getInputStream(originalEntry);

ClassReader classReader = new ClassReader(requireNonNull(inputStream));
ClassWriter classWriter = new ClassWriter(classReader, ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);
ClassVisitor classVisitor = new DeadFunctionVisitor(Opcodes.ASM7, classWriter, deadFunctionMap.get(originalEntry.getName()));
Thushara-Piyasekara marked this conversation as resolved.
Show resolved Hide resolved
classReader.accept(classVisitor, 0);

return classWriter.toByteArray();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import org.wso2.ballerinalang.compiler.semantics.analyzer.CodeAnalyzer;
import org.wso2.ballerinalang.compiler.semantics.analyzer.CompilerPluginRunner;
import org.wso2.ballerinalang.compiler.semantics.analyzer.DataflowAnalyzer;
import org.wso2.ballerinalang.compiler.semantics.analyzer.DeadCodeAnalyzer;
import org.wso2.ballerinalang.compiler.semantics.analyzer.DocumentationAnalyzer;
import org.wso2.ballerinalang.compiler.semantics.analyzer.IsolationAnalyzer;
import org.wso2.ballerinalang.compiler.semantics.analyzer.ObservabilitySymbolCollectorRunner;
Expand Down Expand Up @@ -71,6 +72,7 @@ public class CompilerPhaseRunner {
private final CompilerPhase compilerPhase;
private final DataflowAnalyzer dataflowAnalyzer;
private final IsolationAnalyzer isolationAnalyzer;
private final DeadCodeAnalyzer deadCodeAnalyzer;
private boolean isToolingCompilation;


Expand Down Expand Up @@ -102,6 +104,7 @@ private CompilerPhaseRunner(CompilerContext context) {
this.compilerPhase = this.options.getCompilerPhase();
this.dataflowAnalyzer = DataflowAnalyzer.getInstance(context);
this.isolationAnalyzer = IsolationAnalyzer.getInstance(context);
this.deadCodeAnalyzer = DeadCodeAnalyzer.getInstance(context);
this.isToolingCompilation = this.options.isSet(TOOLING_COMPILATION)
&& Boolean.parseBoolean(this.options.get(TOOLING_COMPILATION));
}
Expand All @@ -122,12 +125,17 @@ public void performTypeCheckPhases(BLangPackage pkgNode) {
}

dataflowAnalyze(pkgNode);
if (this.stopCompilation(pkgNode, CompilerPhase.DOCUMENTATION_ANALYZE)) {
if (this.stopCompilation(pkgNode, CompilerPhase.ISOLATION_ANALYZE)) {
return;
}

isolationAnalyze(pkgNode);
if (this.stopCompilation(pkgNode, CompilerPhase.ISOLATION_ANALYZE)) {
if (this.stopCompilation(pkgNode, CompilerPhase.DEAD_CODE_ANALYZE)) {
return;
}

deadCodeAnalyze(pkgNode);
if (this.stopCompilation(pkgNode, CompilerPhase.DOCUMENTATION_ANALYZE)) {
return;
}

Expand Down Expand Up @@ -223,6 +231,9 @@ public BLangPackage birGen(BLangPackage pkgNode) {
private BLangPackage birEmit(BLangPackage pkgNode) {
return this.birEmitter.emit(pkgNode);
}
private BLangPackage deadCodeAnalyze(BLangPackage pkgNode) {
Thushara-Piyasekara marked this conversation as resolved.
Show resolved Hide resolved
return this.deadCodeAnalyzer.analyze(pkgNode);
}

private boolean stopCompilation(BLangPackage pkgNode, CompilerPhase nextPhase) {
if (compilerPhase.compareTo(nextPhase) < 0) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ public enum CompilerPhase {

CONSTANT_PROPAGATION("constantPropagation"),

DEAD_CODE_ANALYZE("deadCodeAnalyze"),
COMPILER_PLUGIN("compilerPlugin"),

DESUGAR("desugar"),
Expand All @@ -50,6 +51,7 @@ public enum CompilerPhase {

CODE_GEN("codeGen");


private String value;

CompilerPhase(String value) {
Expand All @@ -68,6 +70,8 @@ public static CompilerPhase fromValue(String value) {
return DOCUMENTATION_ANALYZE;
case "constantPropagation":
return CONSTANT_PROPAGATION;
case "deadCodeAnalyze":
return DEAD_CODE_ANALYZE;
case "compilerPlugin":
return COMPILER_PLUGIN;
case "desugar":
Expand Down
Loading