From f2cb035c8f931efff4a020b164e657f16f51934b Mon Sep 17 00:00:00 2001 From: Dmitry Vyukov Date: Fri, 17 Jan 2025 10:39:47 +0100 Subject: pkg/declextract: remove unused includes and defines This is nice on its own, but this will also help to prevent lots of problems when we export more info from the clang tool in future. The clang tool does not know what will end up in the final descriptions, so it exports info about all consts that it encounters. As the result we pull in lots of includes/defines, and lots of kernel includes/defines are broken or create problems. So the fewer we have, the better. --- pkg/compiler/check.go | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) (limited to 'pkg/compiler/check.go') diff --git a/pkg/compiler/check.go b/pkg/compiler/check.go index 92e3e5e03..fbf84857d 100644 --- a/pkg/compiler/check.go +++ b/pkg/compiler/check.go @@ -676,6 +676,44 @@ func CollectUnused(desc *ast.Description, target *targets.Target, eh ast.ErrorHa return nodes, nil } +// CollectUnusedConsts returns unused defines/includes. This is used only for auto-generated descriptions. +func CollectUnusedConsts(desc *ast.Description, target *targets.Target, includeUse map[string]string, + eh ast.ErrorHandler) ([]ast.Node, error) { + comp := createCompiler(desc, target, eh) + comp.typecheck() + if comp.errors > 0 { + return nil, errors.New("typecheck failed") + } + + var unused []ast.Node + for file, info := range comp.extractConsts() { + if !comp.fileMeta(ast.Pos{File: file}).Automatic { + continue + } + usedDefines := make(map[string]bool) + usedIncludes := make(map[string]bool) + for _, c := range info.Consts { + if c.Used { + usedDefines[c.Name] = true + usedIncludes[includeUse[c.Name]] = true + } + } + for _, decl := range comp.desc.Nodes { + switch n := decl.(type) { + case *ast.Define: + if n.Pos.File == file && !usedDefines[n.Name.Name] { + unused = append(unused, n) + } + case *ast.Include: + if n.Pos.File == file && !usedIncludes[n.File.Value] { + unused = append(unused, n) + } + } + } + } + return unused, nil +} + func (comp *compiler) collectUnused() []ast.Node { var unused []ast.Node -- cgit mrf-deployment