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
e3b3885
Removed unused field/parameter
cmaglie May 30, 2024
31085df
Moved Result structure into his own package
cmaglie May 30, 2024
00db9e3
Moving sourceFile object in his own file
cmaglie May 31, 2024
4298a66
Moved uniqueSourceFileQueue in his own file
cmaglie May 31, 2024
03d7b48
Moved includeCache in his own file and made it a field of detector
cmaglie May 31, 2024
01aa021
Fixed comment
cmaglie May 31, 2024
64210c6
Renamed variable (typo)
cmaglie Jun 5, 2024
f67257c
Simplified handling of de-duplication of cache hit messages
cmaglie May 31, 2024
ed9958d
Implemented a better include-cache
cmaglie May 31, 2024
1060bb5
Remove the old, no longer used, includeCache
cmaglie May 31, 2024
b48c689
Simplified error reporting in library detection
cmaglie May 31, 2024
a94f938
Remove useless targetFilePath variable
cmaglie Jun 1, 2024
eff390d
Slight improvement of removeBuildFromSketchFiles
cmaglie Jun 2, 2024
47a01ac
Rename variables for clarity
cmaglie Jun 2, 2024
13d5d5e
Removed hardcoded build.warn_data_percentage in build.options file
cmaglie Jun 2, 2024
054e725
Renamed variables for clarity
cmaglie Jun 2, 2024
6bf928a
Renamed variables for clarity
cmaglie Jun 2, 2024
673aa61
Pre-compute sourceFile fields, and save the in the includes.cache
cmaglie Jun 3, 2024
9822275
Added ObjFileIsUpToDate method to sourceFile
cmaglie Jun 3, 2024
f4cabbb
Implemented parallel task runner
cmaglie Jun 4, 2024
5366520
Simplify use of properties.SplitQuotedString
cmaglie Jun 4, 2024
d81a36c
Use runner.Task in GCC preprocessor
cmaglie Jun 5, 2024
4ab7d7e
Parallelize library discovery phase in compile
cmaglie Jun 5, 2024
1d26cf9
The number of jobs in library detection now follows --jobs flag
cmaglie Jun 11, 2024
da71e60
Reordered properties construction for clarity
cmaglie Jun 13, 2024
cf110ab
Reordered compileFileWithRecipe for clarity
cmaglie Jun 13, 2024
8a632bf
Added integration test
cmaglie Jun 12, 2024
9536817
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 @@ -167,7 +167,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 @@ -218,10 +218,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 @@ -244,6 +240,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 @@ -255,16 +256,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 @@ -453,15 +454,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, verbose bool, 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(
}

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 @@ -212,25 +211,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 @@ -239,7 +239,7 @@ func NewBuilder(
),
diagnosticStore: diagnosticStore,
libsDetector: detector.NewSketchLibrariesDetector(
libsManager, libsResolver,
libsResolver,
useCachedLibrariesResolution,
onlyUpdateCompilationDatabase,
logger,
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.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 @@ -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
Loading