1 // Copyright 2020 The SwiftShader Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 // turbo-cov is a minimal re-implementation of LLVM's llvm-cov, that emits just
16 // the per segment coverage in a binary stream. This avoids the overhead of
17 // encoding to JSON.
18
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ProfileData/Coverage/CoverageMapping.h"
22 #include "llvm/ProfileData/InstrProfReader.h"
23
24 #include <cstdio>
25
26 using namespace llvm;
27 using namespace coverage;
28
29 namespace {
30
31 template<typename T>
emit(T v)32 void emit(T v)
33 {
34 fwrite(&v, sizeof(v), 1, stdout);
35 }
36
emit(const llvm::StringRef & str)37 void emit(const llvm::StringRef &str)
38 {
39 uint64_t len = str.size();
40 emit<uint32_t>(len);
41 fwrite(str.data(), len, 1, stdout);
42 }
43
44 } // namespace
45
main(int argc,const char ** argv)46 int main(int argc, const char **argv)
47 {
48 if(argc < 3)
49 {
50 fprintf(stderr, "turbo-cov <exe> <profdata>\n");
51 return 1;
52 }
53
54 auto exe = argv[1];
55 auto profdata = argv[2];
56
57 auto res = CoverageMapping::load({ exe }, profdata);
58 if(Error E = res.takeError())
59 {
60 fprintf(stderr, "Failed to load executable '%s': %s\n", exe, toString(std::move(E)).c_str());
61 return 1;
62 }
63
64 auto coverage = std::move(res.get());
65 if(!coverage)
66 {
67 fprintf(stderr, "Could not load coverage information\n");
68 return 1;
69 }
70
71 if(auto mismatched = coverage->getMismatchedCount())
72 {
73 fprintf(stderr, "%d functions have mismatched data\n", (int)mismatched);
74 return 1;
75 }
76
77 // uint32 num_files
78 // file[0]
79 // uint32 filename.length
80 // <data> filename.data
81 // uint32 num_segments
82 // file[0].segment[0]
83 // uint32 line
84 // uint32 col
85 // uint32 count
86 // uint8 hasCount
87 // file[0].segment[1]
88 // ...
89 // file[2]
90 // ...
91
92 auto files = coverage->getUniqueSourceFiles();
93 emit<uint32_t>(files.size());
94 for(auto &file : files)
95 {
96 emit(file);
97 auto fileCoverage = coverage->getCoverageForFile(file);
98 emit<uint32_t>(fileCoverage.end() - fileCoverage.begin());
99 for(auto &segment : fileCoverage)
100 {
101 emit<uint32_t>(segment.Line);
102 emit<uint32_t>(segment.Col);
103 emit<uint32_t>(segment.Count);
104 emit<uint8_t>(segment.HasCount ? 1 : 0);
105 }
106 }
107
108 return 0;
109 }
110