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

Improved compile speed by running multi-threaded library discovery. #2625

Open
wants to merge 28 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
6eb7b61
Removed unused field/parameter
cmaglie May 30, 2024
b4262e0
Moved Result structure into his own package
cmaglie May 30, 2024
3daa69f
Moving sourceFile object in his own file
cmaglie May 31, 2024
5fc9a84
Moved uniqueSourceFileQueue in his own file
cmaglie May 31, 2024
7ff78b3
Moved includeCache in his own file and made it a field of detector
cmaglie May 31, 2024
68a9748
Fixed comment
cmaglie May 31, 2024
db0db78
Renamed variable (typo)
cmaglie Jun 5, 2024
e937db8
Simplified handling of de-duplication of cache hit messages
cmaglie May 31, 2024
e4f9927
Implemented a better include-cache
cmaglie May 31, 2024
80ab805
Remove the old, no longer used, includeCache
cmaglie May 31, 2024
94b4b3d
Simplified error reporting in library detection
cmaglie May 31, 2024
fc7779f
Remove useless targetFilePath variable
cmaglie Jun 1, 2024
d072f10
Slight improvement of removeBuildFromSketchFiles
cmaglie Jun 2, 2024
55021c8
Rename variables for clarity
cmaglie Jun 2, 2024
39f2000
Removed hardcoded build.warn_data_percentage in build.options file
cmaglie Jun 2, 2024
9c19adf
Renamed variables for clarity
cmaglie Jun 2, 2024
4f06901
Renamed variables for clarity
cmaglie Jun 2, 2024
a808c17
Pre-compute sourceFile fields, and save the in the includes.cache
cmaglie Jun 3, 2024
f1f8327
Added ObjFileIsUpToDate method to sourceFile
cmaglie Jun 3, 2024
86bdc5f
Implemented parallel task runner
cmaglie Jun 4, 2024
bfe6d8c
Simplify use of properties.SplitQuotedString
cmaglie Jun 4, 2024
f81fdbc
Use runner.Task in GCC preprocessor
cmaglie Jun 5, 2024
8f3155f
Parallelize library discovery phase in compile
cmaglie Jun 5, 2024
8833b28
The number of jobs in library detection now follows --jobs flag
cmaglie Jun 11, 2024
bc97f3d
Reordered properties construction for clarity
cmaglie Jun 13, 2024
60e6c8f
Reordered compileFileWithRecipe for clarity
cmaglie Jun 13, 2024
8237ac6
Added integration test
cmaglie Jun 12, 2024
87765a4
fix: libraries are recompiled if the list of include paths changes
cmaglie Jun 13, 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
25 changes: 13 additions & 12 deletions commands/service_compile.go
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ func (s *arduinoCoreServerImpl) Compile(req *rpc.CompileRequest, stream rpc.Ardu
if buildPathArg := req.GetBuildPath(); buildPathArg != "" {
buildPath = paths.New(req.GetBuildPath()).Canonical()
if in, _ := buildPath.IsInsideDir(sk.FullPath); in && buildPath.IsDir() {
if sk.AdditionalFiles, err = removeBuildFromSketchFiles(sk.AdditionalFiles, buildPath); err != nil {
if sk.AdditionalFiles, err = removeBuildPathFromSketchFiles(sk.AdditionalFiles, buildPath); err != nil {
return err
}
}
Expand Down Expand Up @@ -214,10 +214,6 @@ func (s *arduinoCoreServerImpl) Compile(req *rpc.CompileRequest, stream rpc.Ardu
return err
}

actualPlatform := buildPlatform
otherLibrariesDirs := paths.NewPathList(req.GetLibraries()...)
otherLibrariesDirs.Add(s.settings.LibrariesDir())

var libsManager *librariesmanager.LibrariesManager
if pme.GetProfile() != nil {
libsManager = lm
Expand All @@ -240,6 +236,11 @@ func (s *arduinoCoreServerImpl) Compile(req *rpc.CompileRequest, stream rpc.Ardu
Message: &rpc.CompileResponse_Progress{Progress: p},
})
}

librariesDirs := paths.NewPathList(req.GetLibraries()...) // Array of collection of libraries directories
librariesDirs.Add(s.settings.LibrariesDir())
libraryDirs := paths.NewPathList(req.GetLibrary()...) // Array of single-library directories

sketchBuilder, err := builder.NewBuilder(
ctx,
sk,
Expand All @@ -251,16 +252,16 @@ func (s *arduinoCoreServerImpl) Compile(req *rpc.CompileRequest, stream rpc.Ardu
int(req.GetJobs()),
req.GetBuildProperties(),
s.settings.HardwareDirectories(),
otherLibrariesDirs,
librariesDirs,
s.settings.IDEBuiltinLibrariesDir(),
fqbn,
req.GetClean(),
req.GetSourceOverride(),
req.GetCreateCompilationDatabaseOnly(),
targetPlatform, actualPlatform,
targetPlatform, buildPlatform,
req.GetSkipLibrariesDiscovery(),
libsManager,
paths.NewPathList(req.GetLibrary()...),
libraryDirs,
outStream, errStream, req.GetVerbose(), req.GetWarnings(),
progressCB,
pme.GetEnvVarsForSpawnedProcess(),
Expand Down Expand Up @@ -434,15 +435,15 @@ func maybePurgeBuildCache(compilationsBeforePurge uint, cacheTTL time.Duration)
buildcache.New(paths.TempDir().Join("arduino", "sketches")).Purge(cacheTTL)
}

// removeBuildFromSketchFiles removes the files contained in the build directory from
// removeBuildPathFromSketchFiles removes the files contained in the build directory from
// the list of the sketch files
func removeBuildFromSketchFiles(files paths.PathList, build *paths.Path) (paths.PathList, error) {
func removeBuildPathFromSketchFiles(files paths.PathList, build *paths.Path) (paths.PathList, error) {
var res paths.PathList
ignored := false
for _, file := range files {
if isInside, _ := file.IsInsideDir(build); !isInside {
res = append(res, file)
} else if !ignored {
res.Add(file)
} else {
ignored = true
}
}
Expand Down
6 changes: 1 addition & 5 deletions commands/service_monitor.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ import (
"github.com/arduino/arduino-cli/internal/arduino/cores"
"github.com/arduino/arduino-cli/internal/arduino/cores/packagemanager"
pluggableMonitor "github.com/arduino/arduino-cli/internal/arduino/monitor"
"github.com/arduino/arduino-cli/internal/i18n"
rpc "github.com/arduino/arduino-cli/rpc/cc/arduino/cli/commands/v1"
"github.com/arduino/go-properties-orderedmap"
"github.com/djherbis/buffer"
Expand Down Expand Up @@ -264,10 +263,7 @@ func findMonitorAndSettingsForProtocolAndBoard(pme *packagemanager.Explorer, pro
} else if recipe, ok := boardPlatform.MonitorsDevRecipes[protocol]; ok {
// If we have a recipe we must resolve it
cmdLine := boardProperties.ExpandPropsInString(recipe)
cmdArgs, err := properties.SplitQuotedString(cmdLine, `"'`, false)
if err != nil {
return nil, nil, &cmderrors.InvalidArgumentError{Message: i18n.Tr("Invalid recipe in platform.txt"), Cause: err}
}
cmdArgs, _ := properties.SplitQuotedString(cmdLine, `"'`, false)
id := fmt.Sprintf("%s-%s", boardPlatform, protocol)
return pluggableMonitor.New(id, cmdArgs...), boardSettings, nil
}
Expand Down
5 changes: 1 addition & 4 deletions commands/service_upload.go
Original file line number Diff line number Diff line change
Expand Up @@ -703,10 +703,7 @@ func runTool(recipeID string, props *properties.Map, outStream, errStream io.Wri
return errors.New(i18n.Tr("no upload port provided"))
}
cmdLine := props.ExpandPropsInString(recipe)
cmdArgs, err := properties.SplitQuotedString(cmdLine, `"'`, false)
if err != nil {
return errors.New(i18n.Tr("invalid recipe '%[1]s': %[2]s", recipe, err))
}
cmdArgs, _ := properties.SplitQuotedString(cmdLine, `"'`, false)

// Run Tool
logrus.WithField("phase", "upload").Tracef("Executing upload tool: %s", cmdLine)
Expand Down
78 changes: 42 additions & 36 deletions internal/arduino/builder/builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,6 @@ type Builder struct {
// Parallel processes
jobs int

// Custom build properties defined by user (line by line as "key=value" pairs)
customBuildProperties []string

// core related
coreBuildCachePath *paths.Path
extraCoreBuildCachePaths paths.PathList
Expand Down Expand Up @@ -88,7 +85,7 @@ type Builder struct {
lineOffset int

targetPlatform *cores.PlatformRelease
actualPlatform *cores.PlatformRelease
buildPlatform *cores.PlatformRelease

buildArtifacts *buildArtifacts

Expand Down Expand Up @@ -124,19 +121,20 @@ func NewBuilder(
coreBuildCachePath *paths.Path,
extraCoreBuildCachePaths paths.PathList,
jobs int,
requestBuildProperties []string,
hardwareDirs, otherLibrariesDirs paths.PathList,
customBuildProperties []string,
hardwareDirs paths.PathList,
librariesDirs paths.PathList,
builtInLibrariesDirs *paths.Path,
fqbn *cores.FQBN,
clean bool,
sourceOverrides map[string]string,
onlyUpdateCompilationDatabase bool,
targetPlatform, actualPlatform *cores.PlatformRelease,
targetPlatform, buildPlatform *cores.PlatformRelease,
useCachedLibrariesResolution bool,
librariesManager *librariesmanager.LibrariesManager,
libraryDirs paths.PathList,
customLibraryDirs paths.PathList,
stdout, stderr io.Writer, verbose bool, warningsLevel string,
progresCB rpc.TaskProgressCB,
progressCB rpc.TaskProgressCB,
toolEnv []string,
) (*Builder, error) {
buildProperties := properties.NewMap()
Expand All @@ -145,14 +143,12 @@ func NewBuilder(
}
if sk != nil {
buildProperties.SetPath("sketch_path", sk.FullPath)
buildProperties.Set("build.project_name", sk.MainFile.Base())
buildProperties.SetPath("build.source.path", sk.FullPath)
}
if buildPath != nil {
buildProperties.SetPath("build.path", buildPath)
}
if sk != nil {
buildProperties.Set("build.project_name", sk.MainFile.Base())
buildProperties.SetPath("build.source.path", sk.FullPath)
}
if optimizeForDebug {
if debugFlags, ok := buildProperties.GetOk("compiler.optimization_flags.debug"); ok {
buildProperties.Set("compiler.optimization_flags", debugFlags)
Expand All @@ -164,12 +160,11 @@ func NewBuilder(
}

// Add user provided custom build properties
customBuildProperties, err := properties.LoadFromSlice(requestBuildProperties)
if err != nil {
if p, err := properties.LoadFromSlice(customBuildProperties); err == nil {
buildProperties.Merge(p)
} else {
return nil, fmt.Errorf("invalid build properties: %w", err)
}
buildProperties.Merge(customBuildProperties)
customBuildPropertiesArgs := append(requestBuildProperties, "build.warn_data_percentage=75")

sketchBuildPath, err := buildPath.Join("sketch").Abs()
if err != nil {
Expand All @@ -189,16 +184,20 @@ func NewBuilder(
}

logger := logger.New(stdout, stderr, verbose, warningsLevel)
libsManager, libsResolver, verboseOut, err := detector.LibrariesLoader(
useCachedLibrariesResolution, librariesManager,
builtInLibrariesDirs, libraryDirs, otherLibrariesDirs,
actualPlatform, targetPlatform,
libsResolver, libsLoadingWarnings, err := detector.LibrariesLoader(
useCachedLibrariesResolution,
librariesManager,
builtInLibrariesDirs,
customLibraryDirs,
librariesDirs,
buildPlatform,
targetPlatform,
)
if err != nil {
return nil, err
}
if logger.Verbose() {
logger.Warn(string(verboseOut))
logger.Warn(string(libsLoadingWarnings))
}

diagnosticStore := diagnostics.NewStore()
Expand All @@ -211,25 +210,26 @@ func NewBuilder(
coreBuildPath: coreBuildPath,
librariesBuildPath: librariesBuildPath,
jobs: jobs,
customBuildProperties: customBuildPropertiesArgs,
coreBuildCachePath: coreBuildCachePath,
extraCoreBuildCachePaths: extraCoreBuildCachePaths,
logger: logger,
clean: clean,
sourceOverrides: sourceOverrides,
onlyUpdateCompilationDatabase: onlyUpdateCompilationDatabase,
compilationDatabase: compilation.NewDatabase(buildPath.Join("compile_commands.json")),
Progress: progress.New(progresCB),
Progress: progress.New(progressCB),
executableSectionsSize: []ExecutableSectionSize{},
buildArtifacts: &buildArtifacts{},
targetPlatform: targetPlatform,
actualPlatform: actualPlatform,
buildPlatform: buildPlatform,
toolEnv: toolEnv,
buildOptions: newBuildOptions(
hardwareDirs, otherLibrariesDirs,
builtInLibrariesDirs, buildPath,
hardwareDirs,
librariesDirs,
builtInLibrariesDirs,
buildPath,
sk,
customBuildPropertiesArgs,
customBuildProperties,
fqbn,
clean,
buildProperties.Get("compiler.optimization_flags"),
Expand All @@ -238,7 +238,7 @@ func NewBuilder(
),
diagnosticStore: diagnosticStore,
libsDetector: detector.NewSketchLibrariesDetector(
libsManager, libsResolver,
libsResolver,
useCachedLibrariesResolution,
onlyUpdateCompilationDatabase,
logger,
Expand Down Expand Up @@ -321,10 +321,19 @@ func (b *Builder) preprocess() error {
b.librariesBuildPath,
b.buildProperties,
b.targetPlatform.Platform.Architecture,
b.jobs,
)
if err != nil {
return err
}
if b.libsDetector.IncludeFoldersChanged() && b.librariesBuildPath.Exist() {
if b.logger.Verbose() {
b.logger.Info(i18n.Tr("The list of included libraries has been changed... rebuilding all libraries."))
}
if err := b.librariesBuildPath.RemoveAll(); err != nil {
return err
}
}
b.Progress.CompleteStep()

b.warnAboutArchIncompatibleLibraries(b.libsDetector.ImportedLibraries())
Expand Down Expand Up @@ -493,29 +502,26 @@ func (b *Builder) prepareCommandForRecipe(buildProperties *properties.Map, recip
commandLine = properties.DeleteUnexpandedPropsFromString(commandLine)
}

parts, err := properties.SplitQuotedString(commandLine, `"'`, false)
if err != nil {
return nil, err
}
args, _ := properties.SplitQuotedString(commandLine, `"'`, false)

// if the overall commandline is too long for the platform
// try reducing the length by making the filenames relative
// and changing working directory to build.path
var relativePath string
if len(commandLine) > 30000 {
relativePath = buildProperties.Get("build.path")
for i, arg := range parts {
for i, arg := range args {
if _, err := os.Stat(arg); os.IsNotExist(err) {
continue
}
rel, err := filepath.Rel(relativePath, arg)
if err == nil && !strings.Contains(rel, "..") && len(rel) < len(arg) {
parts[i] = rel
args[i] = rel
}
}
}

command, err := paths.NewProcess(b.toolEnv, parts...)
command, err := paths.NewProcess(b.toolEnv, args...)
if err != nil {
return nil, err
}
Expand Down
Loading
Loading