Skip to content

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

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

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
ca07725
Removed unused field/parameter
cmaglie May 30, 2024
7f775a3
Moved Result structure into his own package
cmaglie May 30, 2024
c577505
Moving sourceFile object in his own file
cmaglie May 31, 2024
d55ec11
Moved uniqueSourceFileQueue in his own file
cmaglie May 31, 2024
c961b30
Moved includeCache in his own file and made it a field of detector
cmaglie May 31, 2024
b07b737
Fixed comment
cmaglie May 31, 2024
326434a
Renamed variable (typo)
cmaglie Jun 5, 2024
4356b1e
Simplified handling of de-duplication of cache hit messages
cmaglie May 31, 2024
808ad1b
Implemented a better include-cache
cmaglie May 31, 2024
60607ba
Remove the old, no longer used, includeCache
cmaglie May 31, 2024
68a1a5e
Simplified error reporting in library detection
cmaglie May 31, 2024
e61c935
Remove useless targetFilePath variable
cmaglie Jun 1, 2024
257b306
Slight improvement of removeBuildFromSketchFiles
cmaglie Jun 2, 2024
12b4c0b
Rename variables for clarity
cmaglie Jun 2, 2024
e9e7277
Removed hardcoded build.warn_data_percentage in build.options file
cmaglie Jun 2, 2024
5d9d3fc
Renamed variables for clarity
cmaglie Jun 2, 2024
bf60dd7
Renamed variables for clarity
cmaglie Jun 2, 2024
66b665e
Pre-compute sourceFile fields, and save the in the includes.cache
cmaglie Jun 3, 2024
d5abb31
Added ObjFileIsUpToDate method to sourceFile
cmaglie Jun 3, 2024
e2bf74d
Implemented parallel task runner
cmaglie Jun 4, 2024
7e1bdcd
Simplify use of properties.SplitQuotedString
cmaglie Jun 4, 2024
9f198b9
Use runner.Task in GCC preprocessor
cmaglie Jun 5, 2024
d7c2b1f
Parallelize library discovery phase in compile
cmaglie Jun 5, 2024
31aaa07
The number of jobs in library detection now follows --jobs flag
cmaglie Jun 11, 2024
3c37f60
Reordered properties construction for clarity
cmaglie Jun 13, 2024
bb80f9d
Reordered compileFileWithRecipe for clarity
cmaglie Jun 13, 2024
e8f3113
Added integration test
cmaglie Jun 12, 2024
1da775f
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 @@ -168,7 +168,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 @@ -219,10 +219,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 Down Expand Up @@ -252,6 +248,11 @@ func (s *arduinoCoreServerImpl) Compile(req *rpc.CompileRequest, stream rpc.Ardu
if req.GetVerbose() {
verbosity = logger.VerbosityVerbose
}

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 @@ -263,16 +264,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, verbosity, req.GetWarnings(),
progressCB,
pme.GetEnvVarsForSpawnedProcess(),
Expand Down Expand Up @@ -461,15 +462,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"
"github.com/arduino/arduino-cli/pkg/fqbn"
rpc "github.com/arduino/arduino-cli/rpc/cc/arduino/cli/commands/v1"
"github.com/arduino/go-properties-orderedmap"
Expand Down Expand Up @@ -265,10 +264,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 @@ -720,10 +720,7 @@ func runTool(ctx context.Context, recipeID string, props *properties.Map, outStr
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 @@ -59,9 +59,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 @@ -89,7 +86,7 @@ type Builder struct {
lineOffset int

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

buildArtifacts *buildArtifacts

Expand Down Expand Up @@ -125,19 +122,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 *fqbn.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, verbosity logger.Verbosity, warningsLevel string,
progresCB rpc.TaskProgressCB,
progressCB rpc.TaskProgressCB,
toolEnv []string,
) (*Builder, error) {
buildProperties := properties.NewMap()
Expand All @@ -146,14 +144,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 @@ -165,12 +161,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 @@ -190,16 +185,20 @@ func NewBuilder(
}

log := logger.New(stdout, stderr, verbosity, 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 log.VerbosityLevel() == logger.VerbosityVerbose {
log.Warn(string(verboseOut))
log.Warn(string(libsLoadingWarnings))
}

diagnosticStore := diagnostics.NewStore()
Expand All @@ -212,25 +211,26 @@ func NewBuilder(
coreBuildPath: coreBuildPath,
librariesBuildPath: librariesBuildPath,
jobs: jobs,
customBuildProperties: customBuildPropertiesArgs,
coreBuildCachePath: coreBuildCachePath,
extraCoreBuildCachePaths: extraCoreBuildCachePaths,
logger: log,
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 @@ -239,7 +239,7 @@ func NewBuilder(
),
diagnosticStore: diagnosticStore,
libsDetector: detector.NewSketchLibrariesDetector(
libsManager, libsResolver,
libsResolver,
useCachedLibrariesResolution,
onlyUpdateCompilationDatabase,
log,
Expand Down Expand Up @@ -322,10 +322,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.VerbosityLevel() == logger.VerbosityVerbose {
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 @@ -492,29 +501,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