File: | lib/ProfileData/Coverage/CoverageMapping.cpp |
Warning: | line 607, column 29 Potential leak of memory pointed to by 'FileIDs.X' |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===- CoverageMapping.cpp - Code coverage mapping support ----------------===// | |||
2 | // | |||
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. | |||
4 | // See https://llvm.org/LICENSE.txt for license information. | |||
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | |||
6 | // | |||
7 | //===----------------------------------------------------------------------===// | |||
8 | // | |||
9 | // This file contains support for clang's and llvm's instrumentation based | |||
10 | // code coverage. | |||
11 | // | |||
12 | //===----------------------------------------------------------------------===// | |||
13 | ||||
14 | #include "llvm/ProfileData/Coverage/CoverageMapping.h" | |||
15 | #include "llvm/ADT/ArrayRef.h" | |||
16 | #include "llvm/ADT/DenseMap.h" | |||
17 | #include "llvm/ADT/None.h" | |||
18 | #include "llvm/ADT/Optional.h" | |||
19 | #include "llvm/ADT/SmallBitVector.h" | |||
20 | #include "llvm/ADT/SmallVector.h" | |||
21 | #include "llvm/ADT/StringRef.h" | |||
22 | #include "llvm/ProfileData/Coverage/CoverageMappingReader.h" | |||
23 | #include "llvm/ProfileData/InstrProfReader.h" | |||
24 | #include "llvm/Support/Debug.h" | |||
25 | #include "llvm/Support/Errc.h" | |||
26 | #include "llvm/Support/Error.h" | |||
27 | #include "llvm/Support/ErrorHandling.h" | |||
28 | #include "llvm/Support/ManagedStatic.h" | |||
29 | #include "llvm/Support/MemoryBuffer.h" | |||
30 | #include "llvm/Support/raw_ostream.h" | |||
31 | #include <algorithm> | |||
32 | #include <cassert> | |||
33 | #include <cstdint> | |||
34 | #include <iterator> | |||
35 | #include <map> | |||
36 | #include <memory> | |||
37 | #include <string> | |||
38 | #include <system_error> | |||
39 | #include <utility> | |||
40 | #include <vector> | |||
41 | ||||
42 | using namespace llvm; | |||
43 | using namespace coverage; | |||
44 | ||||
45 | #define DEBUG_TYPE"coverage-mapping" "coverage-mapping" | |||
46 | ||||
47 | Counter CounterExpressionBuilder::get(const CounterExpression &E) { | |||
48 | auto It = ExpressionIndices.find(E); | |||
49 | if (It != ExpressionIndices.end()) | |||
50 | return Counter::getExpression(It->second); | |||
51 | unsigned I = Expressions.size(); | |||
52 | Expressions.push_back(E); | |||
53 | ExpressionIndices[E] = I; | |||
54 | return Counter::getExpression(I); | |||
55 | } | |||
56 | ||||
57 | void CounterExpressionBuilder::extractTerms(Counter C, int Factor, | |||
58 | SmallVectorImpl<Term> &Terms) { | |||
59 | switch (C.getKind()) { | |||
60 | case Counter::Zero: | |||
61 | break; | |||
62 | case Counter::CounterValueReference: | |||
63 | Terms.emplace_back(C.getCounterID(), Factor); | |||
64 | break; | |||
65 | case Counter::Expression: | |||
66 | const auto &E = Expressions[C.getExpressionID()]; | |||
67 | extractTerms(E.LHS, Factor, Terms); | |||
68 | extractTerms( | |||
69 | E.RHS, E.Kind == CounterExpression::Subtract ? -Factor : Factor, Terms); | |||
70 | break; | |||
71 | } | |||
72 | } | |||
73 | ||||
74 | Counter CounterExpressionBuilder::simplify(Counter ExpressionTree) { | |||
75 | // Gather constant terms. | |||
76 | SmallVector<Term, 32> Terms; | |||
77 | extractTerms(ExpressionTree, +1, Terms); | |||
78 | ||||
79 | // If there are no terms, this is just a zero. The algorithm below assumes at | |||
80 | // least one term. | |||
81 | if (Terms.size() == 0) | |||
82 | return Counter::getZero(); | |||
83 | ||||
84 | // Group the terms by counter ID. | |||
85 | llvm::sort(Terms, [](const Term &LHS, const Term &RHS) { | |||
86 | return LHS.CounterID < RHS.CounterID; | |||
87 | }); | |||
88 | ||||
89 | // Combine terms by counter ID to eliminate counters that sum to zero. | |||
90 | auto Prev = Terms.begin(); | |||
91 | for (auto I = Prev + 1, E = Terms.end(); I != E; ++I) { | |||
92 | if (I->CounterID == Prev->CounterID) { | |||
93 | Prev->Factor += I->Factor; | |||
94 | continue; | |||
95 | } | |||
96 | ++Prev; | |||
97 | *Prev = *I; | |||
98 | } | |||
99 | Terms.erase(++Prev, Terms.end()); | |||
100 | ||||
101 | Counter C; | |||
102 | // Create additions. We do this before subtractions to avoid constructs like | |||
103 | // ((0 - X) + Y), as opposed to (Y - X). | |||
104 | for (auto T : Terms) { | |||
105 | if (T.Factor <= 0) | |||
106 | continue; | |||
107 | for (int I = 0; I < T.Factor; ++I) | |||
108 | if (C.isZero()) | |||
109 | C = Counter::getCounter(T.CounterID); | |||
110 | else | |||
111 | C = get(CounterExpression(CounterExpression::Add, C, | |||
112 | Counter::getCounter(T.CounterID))); | |||
113 | } | |||
114 | ||||
115 | // Create subtractions. | |||
116 | for (auto T : Terms) { | |||
117 | if (T.Factor >= 0) | |||
118 | continue; | |||
119 | for (int I = 0; I < -T.Factor; ++I) | |||
120 | C = get(CounterExpression(CounterExpression::Subtract, C, | |||
121 | Counter::getCounter(T.CounterID))); | |||
122 | } | |||
123 | return C; | |||
124 | } | |||
125 | ||||
126 | Counter CounterExpressionBuilder::add(Counter LHS, Counter RHS) { | |||
127 | return simplify(get(CounterExpression(CounterExpression::Add, LHS, RHS))); | |||
128 | } | |||
129 | ||||
130 | Counter CounterExpressionBuilder::subtract(Counter LHS, Counter RHS) { | |||
131 | return simplify( | |||
132 | get(CounterExpression(CounterExpression::Subtract, LHS, RHS))); | |||
133 | } | |||
134 | ||||
135 | void CounterMappingContext::dump(const Counter &C, raw_ostream &OS) const { | |||
136 | switch (C.getKind()) { | |||
137 | case Counter::Zero: | |||
138 | OS << '0'; | |||
139 | return; | |||
140 | case Counter::CounterValueReference: | |||
141 | OS << '#' << C.getCounterID(); | |||
142 | break; | |||
143 | case Counter::Expression: { | |||
144 | if (C.getExpressionID() >= Expressions.size()) | |||
145 | return; | |||
146 | const auto &E = Expressions[C.getExpressionID()]; | |||
147 | OS << '('; | |||
148 | dump(E.LHS, OS); | |||
149 | OS << (E.Kind == CounterExpression::Subtract ? " - " : " + "); | |||
150 | dump(E.RHS, OS); | |||
151 | OS << ')'; | |||
152 | break; | |||
153 | } | |||
154 | } | |||
155 | if (CounterValues.empty()) | |||
156 | return; | |||
157 | Expected<int64_t> Value = evaluate(C); | |||
158 | if (auto E = Value.takeError()) { | |||
159 | consumeError(std::move(E)); | |||
160 | return; | |||
161 | } | |||
162 | OS << '[' << *Value << ']'; | |||
163 | } | |||
164 | ||||
165 | Expected<int64_t> CounterMappingContext::evaluate(const Counter &C) const { | |||
166 | switch (C.getKind()) { | |||
167 | case Counter::Zero: | |||
168 | return 0; | |||
169 | case Counter::CounterValueReference: | |||
170 | if (C.getCounterID() >= CounterValues.size()) | |||
171 | return errorCodeToError(errc::argument_out_of_domain); | |||
172 | return CounterValues[C.getCounterID()]; | |||
173 | case Counter::Expression: { | |||
174 | if (C.getExpressionID() >= Expressions.size()) | |||
175 | return errorCodeToError(errc::argument_out_of_domain); | |||
176 | const auto &E = Expressions[C.getExpressionID()]; | |||
177 | Expected<int64_t> LHS = evaluate(E.LHS); | |||
178 | if (!LHS) | |||
179 | return LHS; | |||
180 | Expected<int64_t> RHS = evaluate(E.RHS); | |||
181 | if (!RHS) | |||
182 | return RHS; | |||
183 | return E.Kind == CounterExpression::Subtract ? *LHS - *RHS : *LHS + *RHS; | |||
184 | } | |||
185 | } | |||
186 | llvm_unreachable("Unhandled CounterKind")::llvm::llvm_unreachable_internal("Unhandled CounterKind", "/build/llvm-toolchain-snapshot-9~svn362543/lib/ProfileData/Coverage/CoverageMapping.cpp" , 186); | |||
187 | } | |||
188 | ||||
189 | void FunctionRecordIterator::skipOtherFiles() { | |||
190 | while (Current != Records.end() && !Filename.empty() && | |||
191 | Filename != Current->Filenames[0]) | |||
192 | ++Current; | |||
193 | if (Current == Records.end()) | |||
194 | *this = FunctionRecordIterator(); | |||
195 | } | |||
196 | ||||
197 | Error CoverageMapping::loadFunctionRecord( | |||
198 | const CoverageMappingRecord &Record, | |||
199 | IndexedInstrProfReader &ProfileReader) { | |||
200 | StringRef OrigFuncName = Record.FunctionName; | |||
201 | if (OrigFuncName.empty()) | |||
202 | return make_error<CoverageMapError>(coveragemap_error::malformed); | |||
203 | ||||
204 | if (Record.Filenames.empty()) | |||
205 | OrigFuncName = getFuncNameWithoutPrefix(OrigFuncName); | |||
206 | else | |||
207 | OrigFuncName = getFuncNameWithoutPrefix(OrigFuncName, Record.Filenames[0]); | |||
208 | ||||
209 | CounterMappingContext Ctx(Record.Expressions); | |||
210 | ||||
211 | std::vector<uint64_t> Counts; | |||
212 | if (Error E = ProfileReader.getFunctionCounts(Record.FunctionName, | |||
213 | Record.FunctionHash, Counts)) { | |||
214 | instrprof_error IPE = InstrProfError::take(std::move(E)); | |||
215 | if (IPE == instrprof_error::hash_mismatch) { | |||
216 | FuncHashMismatches.emplace_back(Record.FunctionName, Record.FunctionHash); | |||
217 | return Error::success(); | |||
218 | } else if (IPE != instrprof_error::unknown_function) | |||
219 | return make_error<InstrProfError>(IPE); | |||
220 | Counts.assign(Record.MappingRegions.size(), 0); | |||
221 | } | |||
222 | Ctx.setCounts(Counts); | |||
223 | ||||
224 | assert(!Record.MappingRegions.empty() && "Function has no regions")((!Record.MappingRegions.empty() && "Function has no regions" ) ? static_cast<void> (0) : __assert_fail ("!Record.MappingRegions.empty() && \"Function has no regions\"" , "/build/llvm-toolchain-snapshot-9~svn362543/lib/ProfileData/Coverage/CoverageMapping.cpp" , 224, __PRETTY_FUNCTION__)); | |||
225 | ||||
226 | // This coverage record is a zero region for a function that's unused in | |||
227 | // some TU, but used in a different TU. Ignore it. The coverage maps from the | |||
228 | // the other TU will either be loaded (providing full region counts) or they | |||
229 | // won't (in which case we don't unintuitively report functions as uncovered | |||
230 | // when they have non-zero counts in the profile). | |||
231 | if (Record.MappingRegions.size() == 1 && | |||
232 | Record.MappingRegions[0].Count.isZero() && Counts[0] > 0) | |||
233 | return Error::success(); | |||
234 | ||||
235 | FunctionRecord Function(OrigFuncName, Record.Filenames); | |||
236 | for (const auto &Region : Record.MappingRegions) { | |||
237 | Expected<int64_t> ExecutionCount = Ctx.evaluate(Region.Count); | |||
238 | if (auto E = ExecutionCount.takeError()) { | |||
239 | consumeError(std::move(E)); | |||
240 | return Error::success(); | |||
241 | } | |||
242 | Function.pushRegion(Region, *ExecutionCount); | |||
243 | } | |||
244 | ||||
245 | // Don't create records for (filenames, function) pairs we've already seen. | |||
246 | auto FilenamesHash = hash_combine_range(Record.Filenames.begin(), | |||
247 | Record.Filenames.end()); | |||
248 | if (!RecordProvenance[FilenamesHash].insert(hash_value(OrigFuncName)).second) | |||
249 | return Error::success(); | |||
250 | ||||
251 | Functions.push_back(std::move(Function)); | |||
252 | return Error::success(); | |||
253 | } | |||
254 | ||||
255 | Expected<std::unique_ptr<CoverageMapping>> CoverageMapping::load( | |||
256 | ArrayRef<std::unique_ptr<CoverageMappingReader>> CoverageReaders, | |||
257 | IndexedInstrProfReader &ProfileReader) { | |||
258 | auto Coverage = std::unique_ptr<CoverageMapping>(new CoverageMapping()); | |||
259 | ||||
260 | for (const auto &CoverageReader : CoverageReaders) { | |||
261 | for (auto RecordOrErr : *CoverageReader) { | |||
262 | if (Error E = RecordOrErr.takeError()) | |||
263 | return std::move(E); | |||
264 | const auto &Record = *RecordOrErr; | |||
265 | if (Error E = Coverage->loadFunctionRecord(Record, ProfileReader)) | |||
266 | return std::move(E); | |||
267 | } | |||
268 | } | |||
269 | ||||
270 | return std::move(Coverage); | |||
271 | } | |||
272 | ||||
273 | Expected<std::unique_ptr<CoverageMapping>> | |||
274 | CoverageMapping::load(ArrayRef<StringRef> ObjectFilenames, | |||
275 | StringRef ProfileFilename, ArrayRef<StringRef> Arches) { | |||
276 | auto ProfileReaderOrErr = IndexedInstrProfReader::create(ProfileFilename); | |||
277 | if (Error E = ProfileReaderOrErr.takeError()) | |||
278 | return std::move(E); | |||
279 | auto ProfileReader = std::move(ProfileReaderOrErr.get()); | |||
280 | ||||
281 | SmallVector<std::unique_ptr<CoverageMappingReader>, 4> Readers; | |||
282 | SmallVector<std::unique_ptr<MemoryBuffer>, 4> Buffers; | |||
283 | for (const auto &File : llvm::enumerate(ObjectFilenames)) { | |||
284 | auto CovMappingBufOrErr = MemoryBuffer::getFileOrSTDIN(File.value()); | |||
285 | if (std::error_code EC = CovMappingBufOrErr.getError()) | |||
286 | return errorCodeToError(EC); | |||
287 | StringRef Arch = Arches.empty() ? StringRef() : Arches[File.index()]; | |||
288 | auto CoverageReaderOrErr = | |||
289 | BinaryCoverageReader::create(CovMappingBufOrErr.get(), Arch); | |||
290 | if (Error E = CoverageReaderOrErr.takeError()) | |||
291 | return std::move(E); | |||
292 | Readers.push_back(std::move(CoverageReaderOrErr.get())); | |||
293 | Buffers.push_back(std::move(CovMappingBufOrErr.get())); | |||
294 | } | |||
295 | return load(Readers, *ProfileReader); | |||
296 | } | |||
297 | ||||
298 | namespace { | |||
299 | ||||
300 | /// Distributes functions into instantiation sets. | |||
301 | /// | |||
302 | /// An instantiation set is a collection of functions that have the same source | |||
303 | /// code, ie, template functions specializations. | |||
304 | class FunctionInstantiationSetCollector { | |||
305 | using MapT = std::map<LineColPair, std::vector<const FunctionRecord *>>; | |||
306 | MapT InstantiatedFunctions; | |||
307 | ||||
308 | public: | |||
309 | void insert(const FunctionRecord &Function, unsigned FileID) { | |||
310 | auto I = Function.CountedRegions.begin(), E = Function.CountedRegions.end(); | |||
311 | while (I != E && I->FileID != FileID) | |||
312 | ++I; | |||
313 | assert(I != E && "function does not cover the given file")((I != E && "function does not cover the given file") ? static_cast<void> (0) : __assert_fail ("I != E && \"function does not cover the given file\"" , "/build/llvm-toolchain-snapshot-9~svn362543/lib/ProfileData/Coverage/CoverageMapping.cpp" , 313, __PRETTY_FUNCTION__)); | |||
314 | auto &Functions = InstantiatedFunctions[I->startLoc()]; | |||
315 | Functions.push_back(&Function); | |||
316 | } | |||
317 | ||||
318 | MapT::iterator begin() { return InstantiatedFunctions.begin(); } | |||
319 | MapT::iterator end() { return InstantiatedFunctions.end(); } | |||
320 | }; | |||
321 | ||||
322 | class SegmentBuilder { | |||
323 | std::vector<CoverageSegment> &Segments; | |||
324 | SmallVector<const CountedRegion *, 8> ActiveRegions; | |||
325 | ||||
326 | SegmentBuilder(std::vector<CoverageSegment> &Segments) : Segments(Segments) {} | |||
327 | ||||
328 | /// Emit a segment with the count from \p Region starting at \p StartLoc. | |||
329 | // | |||
330 | /// \p IsRegionEntry: The segment is at the start of a new non-gap region. | |||
331 | /// \p EmitSkippedRegion: The segment must be emitted as a skipped region. | |||
332 | void startSegment(const CountedRegion &Region, LineColPair StartLoc, | |||
333 | bool IsRegionEntry, bool EmitSkippedRegion = false) { | |||
334 | bool HasCount = !EmitSkippedRegion && | |||
335 | (Region.Kind != CounterMappingRegion::SkippedRegion); | |||
336 | ||||
337 | // If the new segment wouldn't affect coverage rendering, skip it. | |||
338 | if (!Segments.empty() && !IsRegionEntry && !EmitSkippedRegion) { | |||
339 | const auto &Last = Segments.back(); | |||
340 | if (Last.HasCount == HasCount && Last.Count == Region.ExecutionCount && | |||
341 | !Last.IsRegionEntry) | |||
342 | return; | |||
343 | } | |||
344 | ||||
345 | if (HasCount) | |||
346 | Segments.emplace_back(StartLoc.first, StartLoc.second, | |||
347 | Region.ExecutionCount, IsRegionEntry, | |||
348 | Region.Kind == CounterMappingRegion::GapRegion); | |||
349 | else | |||
350 | Segments.emplace_back(StartLoc.first, StartLoc.second, IsRegionEntry); | |||
351 | ||||
352 | LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("coverage-mapping")) { { const auto &Last = Segments.back (); dbgs() << "Segment at " << Last.Line << ":" << Last.Col << " (count = " << Last.Count << ")" << (Last.IsRegionEntry ? ", RegionEntry" : "") << (!Last.HasCount ? ", Skipped" : "") << (Last .IsGapRegion ? ", Gap" : "") << "\n"; }; } } while (false ) | |||
353 | const auto &Last = Segments.back();do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("coverage-mapping")) { { const auto &Last = Segments.back (); dbgs() << "Segment at " << Last.Line << ":" << Last.Col << " (count = " << Last.Count << ")" << (Last.IsRegionEntry ? ", RegionEntry" : "") << (!Last.HasCount ? ", Skipped" : "") << (Last .IsGapRegion ? ", Gap" : "") << "\n"; }; } } while (false ) | |||
354 | dbgs() << "Segment at " << Last.Line << ":" << Last.Coldo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("coverage-mapping")) { { const auto &Last = Segments.back (); dbgs() << "Segment at " << Last.Line << ":" << Last.Col << " (count = " << Last.Count << ")" << (Last.IsRegionEntry ? ", RegionEntry" : "") << (!Last.HasCount ? ", Skipped" : "") << (Last .IsGapRegion ? ", Gap" : "") << "\n"; }; } } while (false ) | |||
355 | << " (count = " << Last.Count << ")"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("coverage-mapping")) { { const auto &Last = Segments.back (); dbgs() << "Segment at " << Last.Line << ":" << Last.Col << " (count = " << Last.Count << ")" << (Last.IsRegionEntry ? ", RegionEntry" : "") << (!Last.HasCount ? ", Skipped" : "") << (Last .IsGapRegion ? ", Gap" : "") << "\n"; }; } } while (false ) | |||
356 | << (Last.IsRegionEntry ? ", RegionEntry" : "")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("coverage-mapping")) { { const auto &Last = Segments.back (); dbgs() << "Segment at " << Last.Line << ":" << Last.Col << " (count = " << Last.Count << ")" << (Last.IsRegionEntry ? ", RegionEntry" : "") << (!Last.HasCount ? ", Skipped" : "") << (Last .IsGapRegion ? ", Gap" : "") << "\n"; }; } } while (false ) | |||
357 | << (!Last.HasCount ? ", Skipped" : "")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("coverage-mapping")) { { const auto &Last = Segments.back (); dbgs() << "Segment at " << Last.Line << ":" << Last.Col << " (count = " << Last.Count << ")" << (Last.IsRegionEntry ? ", RegionEntry" : "") << (!Last.HasCount ? ", Skipped" : "") << (Last .IsGapRegion ? ", Gap" : "") << "\n"; }; } } while (false ) | |||
358 | << (Last.IsGapRegion ? ", Gap" : "") << "\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("coverage-mapping")) { { const auto &Last = Segments.back (); dbgs() << "Segment at " << Last.Line << ":" << Last.Col << " (count = " << Last.Count << ")" << (Last.IsRegionEntry ? ", RegionEntry" : "") << (!Last.HasCount ? ", Skipped" : "") << (Last .IsGapRegion ? ", Gap" : "") << "\n"; }; } } while (false ) | |||
359 | })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("coverage-mapping")) { { const auto &Last = Segments.back (); dbgs() << "Segment at " << Last.Line << ":" << Last.Col << " (count = " << Last.Count << ")" << (Last.IsRegionEntry ? ", RegionEntry" : "") << (!Last.HasCount ? ", Skipped" : "") << (Last .IsGapRegion ? ", Gap" : "") << "\n"; }; } } while (false ); | |||
360 | } | |||
361 | ||||
362 | /// Emit segments for active regions which end before \p Loc. | |||
363 | /// | |||
364 | /// \p Loc: The start location of the next region. If None, all active | |||
365 | /// regions are completed. | |||
366 | /// \p FirstCompletedRegion: Index of the first completed region. | |||
367 | void completeRegionsUntil(Optional<LineColPair> Loc, | |||
368 | unsigned FirstCompletedRegion) { | |||
369 | // Sort the completed regions by end location. This makes it simple to | |||
370 | // emit closing segments in sorted order. | |||
371 | auto CompletedRegionsIt = ActiveRegions.begin() + FirstCompletedRegion; | |||
372 | std::stable_sort(CompletedRegionsIt, ActiveRegions.end(), | |||
373 | [](const CountedRegion *L, const CountedRegion *R) { | |||
374 | return L->endLoc() < R->endLoc(); | |||
375 | }); | |||
376 | ||||
377 | // Emit segments for all completed regions. | |||
378 | for (unsigned I = FirstCompletedRegion + 1, E = ActiveRegions.size(); I < E; | |||
379 | ++I) { | |||
380 | const auto *CompletedRegion = ActiveRegions[I]; | |||
381 | assert((!Loc || CompletedRegion->endLoc() <= *Loc) &&(((!Loc || CompletedRegion->endLoc() <= *Loc) && "Completed region ends after start of new region") ? static_cast <void> (0) : __assert_fail ("(!Loc || CompletedRegion->endLoc() <= *Loc) && \"Completed region ends after start of new region\"" , "/build/llvm-toolchain-snapshot-9~svn362543/lib/ProfileData/Coverage/CoverageMapping.cpp" , 382, __PRETTY_FUNCTION__)) | |||
382 | "Completed region ends after start of new region")(((!Loc || CompletedRegion->endLoc() <= *Loc) && "Completed region ends after start of new region") ? static_cast <void> (0) : __assert_fail ("(!Loc || CompletedRegion->endLoc() <= *Loc) && \"Completed region ends after start of new region\"" , "/build/llvm-toolchain-snapshot-9~svn362543/lib/ProfileData/Coverage/CoverageMapping.cpp" , 382, __PRETTY_FUNCTION__)); | |||
383 | ||||
384 | const auto *PrevCompletedRegion = ActiveRegions[I - 1]; | |||
385 | auto CompletedSegmentLoc = PrevCompletedRegion->endLoc(); | |||
386 | ||||
387 | // Don't emit any more segments if they start where the new region begins. | |||
388 | if (Loc && CompletedSegmentLoc == *Loc) | |||
389 | break; | |||
390 | ||||
391 | // Don't emit a segment if the next completed region ends at the same | |||
392 | // location as this one. | |||
393 | if (CompletedSegmentLoc == CompletedRegion->endLoc()) | |||
394 | continue; | |||
395 | ||||
396 | // Use the count from the last completed region which ends at this loc. | |||
397 | for (unsigned J = I + 1; J < E; ++J) | |||
398 | if (CompletedRegion->endLoc() == ActiveRegions[J]->endLoc()) | |||
399 | CompletedRegion = ActiveRegions[J]; | |||
400 | ||||
401 | startSegment(*CompletedRegion, CompletedSegmentLoc, false); | |||
402 | } | |||
403 | ||||
404 | auto Last = ActiveRegions.back(); | |||
405 | if (FirstCompletedRegion && Last->endLoc() != *Loc) { | |||
406 | // If there's a gap after the end of the last completed region and the | |||
407 | // start of the new region, use the last active region to fill the gap. | |||
408 | startSegment(*ActiveRegions[FirstCompletedRegion - 1], Last->endLoc(), | |||
409 | false); | |||
410 | } else if (!FirstCompletedRegion && (!Loc || *Loc != Last->endLoc())) { | |||
411 | // Emit a skipped segment if there are no more active regions. This | |||
412 | // ensures that gaps between functions are marked correctly. | |||
413 | startSegment(*Last, Last->endLoc(), false, true); | |||
414 | } | |||
415 | ||||
416 | // Pop the completed regions. | |||
417 | ActiveRegions.erase(CompletedRegionsIt, ActiveRegions.end()); | |||
418 | } | |||
419 | ||||
420 | void buildSegmentsImpl(ArrayRef<CountedRegion> Regions) { | |||
421 | for (const auto &CR : enumerate(Regions)) { | |||
422 | auto CurStartLoc = CR.value().startLoc(); | |||
423 | ||||
424 | // Active regions which end before the current region need to be popped. | |||
425 | auto CompletedRegions = | |||
426 | std::stable_partition(ActiveRegions.begin(), ActiveRegions.end(), | |||
427 | [&](const CountedRegion *Region) { | |||
428 | return !(Region->endLoc() <= CurStartLoc); | |||
429 | }); | |||
430 | if (CompletedRegions != ActiveRegions.end()) { | |||
431 | unsigned FirstCompletedRegion = | |||
432 | std::distance(ActiveRegions.begin(), CompletedRegions); | |||
433 | completeRegionsUntil(CurStartLoc, FirstCompletedRegion); | |||
434 | } | |||
435 | ||||
436 | bool GapRegion = CR.value().Kind == CounterMappingRegion::GapRegion; | |||
437 | ||||
438 | // Try to emit a segment for the current region. | |||
439 | if (CurStartLoc == CR.value().endLoc()) { | |||
440 | // Avoid making zero-length regions active. If it's the last region, | |||
441 | // emit a skipped segment. Otherwise use its predecessor's count. | |||
442 | const bool Skipped = (CR.index() + 1) == Regions.size(); | |||
443 | startSegment(ActiveRegions.empty() ? CR.value() : *ActiveRegions.back(), | |||
444 | CurStartLoc, !GapRegion, Skipped); | |||
445 | continue; | |||
446 | } | |||
447 | if (CR.index() + 1 == Regions.size() || | |||
448 | CurStartLoc != Regions[CR.index() + 1].startLoc()) { | |||
449 | // Emit a segment if the next region doesn't start at the same location | |||
450 | // as this one. | |||
451 | startSegment(CR.value(), CurStartLoc, !GapRegion); | |||
452 | } | |||
453 | ||||
454 | // This region is active (i.e not completed). | |||
455 | ActiveRegions.push_back(&CR.value()); | |||
456 | } | |||
457 | ||||
458 | // Complete any remaining active regions. | |||
459 | if (!ActiveRegions.empty()) | |||
460 | completeRegionsUntil(None, 0); | |||
461 | } | |||
462 | ||||
463 | /// Sort a nested sequence of regions from a single file. | |||
464 | static void sortNestedRegions(MutableArrayRef<CountedRegion> Regions) { | |||
465 | llvm::sort(Regions, [](const CountedRegion &LHS, const CountedRegion &RHS) { | |||
466 | if (LHS.startLoc() != RHS.startLoc()) | |||
467 | return LHS.startLoc() < RHS.startLoc(); | |||
468 | if (LHS.endLoc() != RHS.endLoc()) | |||
469 | // When LHS completely contains RHS, we sort LHS first. | |||
470 | return RHS.endLoc() < LHS.endLoc(); | |||
471 | // If LHS and RHS cover the same area, we need to sort them according | |||
472 | // to their kinds so that the most suitable region will become "active" | |||
473 | // in combineRegions(). Because we accumulate counter values only from | |||
474 | // regions of the same kind as the first region of the area, prefer | |||
475 | // CodeRegion to ExpansionRegion and ExpansionRegion to SkippedRegion. | |||
476 | static_assert(CounterMappingRegion::CodeRegion < | |||
477 | CounterMappingRegion::ExpansionRegion && | |||
478 | CounterMappingRegion::ExpansionRegion < | |||
479 | CounterMappingRegion::SkippedRegion, | |||
480 | "Unexpected order of region kind values"); | |||
481 | return LHS.Kind < RHS.Kind; | |||
482 | }); | |||
483 | } | |||
484 | ||||
485 | /// Combine counts of regions which cover the same area. | |||
486 | static ArrayRef<CountedRegion> | |||
487 | combineRegions(MutableArrayRef<CountedRegion> Regions) { | |||
488 | if (Regions.empty()) | |||
489 | return Regions; | |||
490 | auto Active = Regions.begin(); | |||
491 | auto End = Regions.end(); | |||
492 | for (auto I = Regions.begin() + 1; I != End; ++I) { | |||
493 | if (Active->startLoc() != I->startLoc() || | |||
494 | Active->endLoc() != I->endLoc()) { | |||
495 | // Shift to the next region. | |||
496 | ++Active; | |||
497 | if (Active != I) | |||
498 | *Active = *I; | |||
499 | continue; | |||
500 | } | |||
501 | // Merge duplicate region. | |||
502 | // If CodeRegions and ExpansionRegions cover the same area, it's probably | |||
503 | // a macro which is fully expanded to another macro. In that case, we need | |||
504 | // to accumulate counts only from CodeRegions, or else the area will be | |||
505 | // counted twice. | |||
506 | // On the other hand, a macro may have a nested macro in its body. If the | |||
507 | // outer macro is used several times, the ExpansionRegion for the nested | |||
508 | // macro will also be added several times. These ExpansionRegions cover | |||
509 | // the same source locations and have to be combined to reach the correct | |||
510 | // value for that area. | |||
511 | // We add counts of the regions of the same kind as the active region | |||
512 | // to handle the both situations. | |||
513 | if (I->Kind == Active->Kind) | |||
514 | Active->ExecutionCount += I->ExecutionCount; | |||
515 | } | |||
516 | return Regions.drop_back(std::distance(++Active, End)); | |||
517 | } | |||
518 | ||||
519 | public: | |||
520 | /// Build a sorted list of CoverageSegments from a list of Regions. | |||
521 | static std::vector<CoverageSegment> | |||
522 | buildSegments(MutableArrayRef<CountedRegion> Regions) { | |||
523 | std::vector<CoverageSegment> Segments; | |||
524 | SegmentBuilder Builder(Segments); | |||
525 | ||||
526 | sortNestedRegions(Regions); | |||
527 | ArrayRef<CountedRegion> CombinedRegions = combineRegions(Regions); | |||
528 | ||||
529 | LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("coverage-mapping")) { { dbgs() << "Combined regions:\n" ; for (const auto &CR : CombinedRegions) dbgs() << " " << CR.LineStart << ":" << CR.ColumnStart << " -> " << CR.LineEnd << ":" << CR.ColumnEnd << " (count=" << CR.ExecutionCount << ")\n" ; }; } } while (false) | |||
530 | dbgs() << "Combined regions:\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("coverage-mapping")) { { dbgs() << "Combined regions:\n" ; for (const auto &CR : CombinedRegions) dbgs() << " " << CR.LineStart << ":" << CR.ColumnStart << " -> " << CR.LineEnd << ":" << CR.ColumnEnd << " (count=" << CR.ExecutionCount << ")\n" ; }; } } while (false) | |||
531 | for (const auto &CR : CombinedRegions)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("coverage-mapping")) { { dbgs() << "Combined regions:\n" ; for (const auto &CR : CombinedRegions) dbgs() << " " << CR.LineStart << ":" << CR.ColumnStart << " -> " << CR.LineEnd << ":" << CR.ColumnEnd << " (count=" << CR.ExecutionCount << ")\n" ; }; } } while (false) | |||
532 | dbgs() << " " << CR.LineStart << ":" << CR.ColumnStart << " -> "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("coverage-mapping")) { { dbgs() << "Combined regions:\n" ; for (const auto &CR : CombinedRegions) dbgs() << " " << CR.LineStart << ":" << CR.ColumnStart << " -> " << CR.LineEnd << ":" << CR.ColumnEnd << " (count=" << CR.ExecutionCount << ")\n" ; }; } } while (false) | |||
533 | << CR.LineEnd << ":" << CR.ColumnEnddo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("coverage-mapping")) { { dbgs() << "Combined regions:\n" ; for (const auto &CR : CombinedRegions) dbgs() << " " << CR.LineStart << ":" << CR.ColumnStart << " -> " << CR.LineEnd << ":" << CR.ColumnEnd << " (count=" << CR.ExecutionCount << ")\n" ; }; } } while (false) | |||
534 | << " (count=" << CR.ExecutionCount << ")\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("coverage-mapping")) { { dbgs() << "Combined regions:\n" ; for (const auto &CR : CombinedRegions) dbgs() << " " << CR.LineStart << ":" << CR.ColumnStart << " -> " << CR.LineEnd << ":" << CR.ColumnEnd << " (count=" << CR.ExecutionCount << ")\n" ; }; } } while (false) | |||
535 | })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("coverage-mapping")) { { dbgs() << "Combined regions:\n" ; for (const auto &CR : CombinedRegions) dbgs() << " " << CR.LineStart << ":" << CR.ColumnStart << " -> " << CR.LineEnd << ":" << CR.ColumnEnd << " (count=" << CR.ExecutionCount << ")\n" ; }; } } while (false); | |||
536 | ||||
537 | Builder.buildSegmentsImpl(CombinedRegions); | |||
538 | ||||
539 | #ifndef NDEBUG | |||
540 | for (unsigned I = 1, E = Segments.size(); I < E; ++I) { | |||
541 | const auto &L = Segments[I - 1]; | |||
542 | const auto &R = Segments[I]; | |||
543 | if (!(L.Line < R.Line) && !(L.Line == R.Line && L.Col < R.Col)) { | |||
544 | LLVM_DEBUG(dbgs() << " ! Segment " << L.Line << ":" << L.Coldo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("coverage-mapping")) { dbgs() << " ! Segment " << L.Line << ":" << L.Col << " followed by " << R.Line << ":" << R.Col << "\n"; } } while ( false) | |||
545 | << " followed by " << R.Line << ":" << R.Col << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("coverage-mapping")) { dbgs() << " ! Segment " << L.Line << ":" << L.Col << " followed by " << R.Line << ":" << R.Col << "\n"; } } while ( false); | |||
546 | assert(false && "Coverage segments not unique or sorted")((false && "Coverage segments not unique or sorted") ? static_cast<void> (0) : __assert_fail ("false && \"Coverage segments not unique or sorted\"" , "/build/llvm-toolchain-snapshot-9~svn362543/lib/ProfileData/Coverage/CoverageMapping.cpp" , 546, __PRETTY_FUNCTION__)); | |||
547 | } | |||
548 | } | |||
549 | #endif | |||
550 | ||||
551 | return Segments; | |||
552 | } | |||
553 | }; | |||
554 | ||||
555 | } // end anonymous namespace | |||
556 | ||||
557 | std::vector<StringRef> CoverageMapping::getUniqueSourceFiles() const { | |||
558 | std::vector<StringRef> Filenames; | |||
559 | for (const auto &Function : getCoveredFunctions()) | |||
560 | Filenames.insert(Filenames.end(), Function.Filenames.begin(), | |||
561 | Function.Filenames.end()); | |||
562 | llvm::sort(Filenames); | |||
563 | auto Last = std::unique(Filenames.begin(), Filenames.end()); | |||
564 | Filenames.erase(Last, Filenames.end()); | |||
565 | return Filenames; | |||
566 | } | |||
567 | ||||
568 | static SmallBitVector gatherFileIDs(StringRef SourceFile, | |||
569 | const FunctionRecord &Function) { | |||
570 | SmallBitVector FilenameEquivalence(Function.Filenames.size(), false); | |||
571 | for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I) | |||
572 | if (SourceFile == Function.Filenames[I]) | |||
573 | FilenameEquivalence[I] = true; | |||
574 | return FilenameEquivalence; | |||
575 | } | |||
576 | ||||
577 | /// Return the ID of the file where the definition of the function is located. | |||
578 | static Optional<unsigned> findMainViewFileID(const FunctionRecord &Function) { | |||
579 | SmallBitVector IsNotExpandedFile(Function.Filenames.size(), true); | |||
580 | for (const auto &CR : Function.CountedRegions) | |||
581 | if (CR.Kind == CounterMappingRegion::ExpansionRegion) | |||
582 | IsNotExpandedFile[CR.ExpandedFileID] = false; | |||
583 | int I = IsNotExpandedFile.find_first(); | |||
584 | if (I == -1) | |||
585 | return None; | |||
586 | return I; | |||
587 | } | |||
588 | ||||
589 | /// Check if SourceFile is the file that contains the definition of | |||
590 | /// the Function. Return the ID of the file in that case or None otherwise. | |||
591 | static Optional<unsigned> findMainViewFileID(StringRef SourceFile, | |||
592 | const FunctionRecord &Function) { | |||
593 | Optional<unsigned> I = findMainViewFileID(Function); | |||
594 | if (I && SourceFile == Function.Filenames[*I]) | |||
595 | return I; | |||
596 | return None; | |||
597 | } | |||
598 | ||||
599 | static bool isExpansion(const CountedRegion &R, unsigned FileID) { | |||
600 | return R.Kind == CounterMappingRegion::ExpansionRegion && R.FileID == FileID; | |||
601 | } | |||
602 | ||||
603 | CoverageData CoverageMapping::getCoverageForFile(StringRef Filename) const { | |||
604 | CoverageData FileCoverage(Filename); | |||
605 | std::vector<CountedRegion> Regions; | |||
606 | ||||
607 | for (const auto &Function : Functions) { | |||
| ||||
608 | auto MainFileID = findMainViewFileID(Filename, Function); | |||
609 | auto FileIDs = gatherFileIDs(Filename, Function); | |||
| ||||
610 | for (const auto &CR : Function.CountedRegions) | |||
611 | if (FileIDs.test(CR.FileID)) { | |||
612 | Regions.push_back(CR); | |||
613 | if (MainFileID && isExpansion(CR, *MainFileID)) | |||
614 | FileCoverage.Expansions.emplace_back(CR, Function); | |||
615 | } | |||
616 | } | |||
617 | ||||
618 | LLVM_DEBUG(dbgs() << "Emitting segments for file: " << Filename << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("coverage-mapping")) { dbgs() << "Emitting segments for file: " << Filename << "\n"; } } while (false); | |||
619 | FileCoverage.Segments = SegmentBuilder::buildSegments(Regions); | |||
620 | ||||
621 | return FileCoverage; | |||
622 | } | |||
623 | ||||
624 | std::vector<InstantiationGroup> | |||
625 | CoverageMapping::getInstantiationGroups(StringRef Filename) const { | |||
626 | FunctionInstantiationSetCollector InstantiationSetCollector; | |||
627 | for (const auto &Function : Functions) { | |||
628 | auto MainFileID = findMainViewFileID(Filename, Function); | |||
629 | if (!MainFileID) | |||
630 | continue; | |||
631 | InstantiationSetCollector.insert(Function, *MainFileID); | |||
632 | } | |||
633 | ||||
634 | std::vector<InstantiationGroup> Result; | |||
635 | for (auto &InstantiationSet : InstantiationSetCollector) { | |||
636 | InstantiationGroup IG{InstantiationSet.first.first, | |||
637 | InstantiationSet.first.second, | |||
638 | std::move(InstantiationSet.second)}; | |||
639 | Result.emplace_back(std::move(IG)); | |||
640 | } | |||
641 | return Result; | |||
642 | } | |||
643 | ||||
644 | CoverageData | |||
645 | CoverageMapping::getCoverageForFunction(const FunctionRecord &Function) const { | |||
646 | auto MainFileID = findMainViewFileID(Function); | |||
647 | if (!MainFileID) | |||
648 | return CoverageData(); | |||
649 | ||||
650 | CoverageData FunctionCoverage(Function.Filenames[*MainFileID]); | |||
651 | std::vector<CountedRegion> Regions; | |||
652 | for (const auto &CR : Function.CountedRegions) | |||
653 | if (CR.FileID == *MainFileID) { | |||
654 | Regions.push_back(CR); | |||
655 | if (isExpansion(CR, *MainFileID)) | |||
656 | FunctionCoverage.Expansions.emplace_back(CR, Function); | |||
657 | } | |||
658 | ||||
659 | LLVM_DEBUG(dbgs() << "Emitting segments for function: " << Function.Namedo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("coverage-mapping")) { dbgs() << "Emitting segments for function: " << Function.Name << "\n"; } } while (false) | |||
660 | << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("coverage-mapping")) { dbgs() << "Emitting segments for function: " << Function.Name << "\n"; } } while (false); | |||
661 | FunctionCoverage.Segments = SegmentBuilder::buildSegments(Regions); | |||
662 | ||||
663 | return FunctionCoverage; | |||
664 | } | |||
665 | ||||
666 | CoverageData CoverageMapping::getCoverageForExpansion( | |||
667 | const ExpansionRecord &Expansion) const { | |||
668 | CoverageData ExpansionCoverage( | |||
669 | Expansion.Function.Filenames[Expansion.FileID]); | |||
670 | std::vector<CountedRegion> Regions; | |||
671 | for (const auto &CR : Expansion.Function.CountedRegions) | |||
672 | if (CR.FileID == Expansion.FileID) { | |||
673 | Regions.push_back(CR); | |||
674 | if (isExpansion(CR, Expansion.FileID)) | |||
675 | ExpansionCoverage.Expansions.emplace_back(CR, Expansion.Function); | |||
676 | } | |||
677 | ||||
678 | LLVM_DEBUG(dbgs() << "Emitting segments for expansion of file "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("coverage-mapping")) { dbgs() << "Emitting segments for expansion of file " << Expansion.FileID << "\n"; } } while (false) | |||
679 | << Expansion.FileID << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("coverage-mapping")) { dbgs() << "Emitting segments for expansion of file " << Expansion.FileID << "\n"; } } while (false); | |||
680 | ExpansionCoverage.Segments = SegmentBuilder::buildSegments(Regions); | |||
681 | ||||
682 | return ExpansionCoverage; | |||
683 | } | |||
684 | ||||
685 | LineCoverageStats::LineCoverageStats( | |||
686 | ArrayRef<const CoverageSegment *> LineSegments, | |||
687 | const CoverageSegment *WrappedSegment, unsigned Line) | |||
688 | : ExecutionCount(0), HasMultipleRegions(false), Mapped(false), Line(Line), | |||
689 | LineSegments(LineSegments), WrappedSegment(WrappedSegment) { | |||
690 | // Find the minimum number of regions which start in this line. | |||
691 | unsigned MinRegionCount = 0; | |||
692 | auto isStartOfRegion = [](const CoverageSegment *S) { | |||
693 | return !S->IsGapRegion && S->HasCount && S->IsRegionEntry; | |||
694 | }; | |||
695 | for (unsigned I = 0; I < LineSegments.size() && MinRegionCount < 2; ++I) | |||
696 | if (isStartOfRegion(LineSegments[I])) | |||
697 | ++MinRegionCount; | |||
698 | ||||
699 | bool StartOfSkippedRegion = !LineSegments.empty() && | |||
700 | !LineSegments.front()->HasCount && | |||
701 | LineSegments.front()->IsRegionEntry; | |||
702 | ||||
703 | HasMultipleRegions = MinRegionCount > 1; | |||
704 | Mapped = | |||
705 | !StartOfSkippedRegion && | |||
706 | ((WrappedSegment && WrappedSegment->HasCount) || (MinRegionCount > 0)); | |||
707 | ||||
708 | if (!Mapped) | |||
709 | return; | |||
710 | ||||
711 | // Pick the max count from the non-gap, region entry segments and the | |||
712 | // wrapped count. | |||
713 | if (WrappedSegment) | |||
714 | ExecutionCount = WrappedSegment->Count; | |||
715 | if (!MinRegionCount) | |||
716 | return; | |||
717 | for (const auto *LS : LineSegments) | |||
718 | if (isStartOfRegion(LS)) | |||
719 | ExecutionCount = std::max(ExecutionCount, LS->Count); | |||
720 | } | |||
721 | ||||
722 | LineCoverageIterator &LineCoverageIterator::operator++() { | |||
723 | if (Next == CD.end()) { | |||
724 | Stats = LineCoverageStats(); | |||
725 | Ended = true; | |||
726 | return *this; | |||
727 | } | |||
728 | if (Segments.size()) | |||
729 | WrappedSegment = Segments.back(); | |||
730 | Segments.clear(); | |||
731 | while (Next != CD.end() && Next->Line == Line) | |||
732 | Segments.push_back(&*Next++); | |||
733 | Stats = LineCoverageStats(Segments, WrappedSegment, Line); | |||
734 | ++Line; | |||
735 | return *this; | |||
736 | } | |||
737 | ||||
738 | static std::string getCoverageMapErrString(coveragemap_error Err) { | |||
739 | switch (Err) { | |||
740 | case coveragemap_error::success: | |||
741 | return "Success"; | |||
742 | case coveragemap_error::eof: | |||
743 | return "End of File"; | |||
744 | case coveragemap_error::no_data_found: | |||
745 | return "No coverage data found"; | |||
746 | case coveragemap_error::unsupported_version: | |||
747 | return "Unsupported coverage format version"; | |||
748 | case coveragemap_error::truncated: | |||
749 | return "Truncated coverage data"; | |||
750 | case coveragemap_error::malformed: | |||
751 | return "Malformed coverage data"; | |||
752 | } | |||
753 | llvm_unreachable("A value of coveragemap_error has no message.")::llvm::llvm_unreachable_internal("A value of coveragemap_error has no message." , "/build/llvm-toolchain-snapshot-9~svn362543/lib/ProfileData/Coverage/CoverageMapping.cpp" , 753); | |||
754 | } | |||
755 | ||||
756 | namespace { | |||
757 | ||||
758 | // FIXME: This class is only here to support the transition to llvm::Error. It | |||
759 | // will be removed once this transition is complete. Clients should prefer to | |||
760 | // deal with the Error value directly, rather than converting to error_code. | |||
761 | class CoverageMappingErrorCategoryType : public std::error_category { | |||
762 | const char *name() const noexcept override { return "llvm.coveragemap"; } | |||
763 | std::string message(int IE) const override { | |||
764 | return getCoverageMapErrString(static_cast<coveragemap_error>(IE)); | |||
765 | } | |||
766 | }; | |||
767 | ||||
768 | } // end anonymous namespace | |||
769 | ||||
770 | std::string CoverageMapError::message() const { | |||
771 | return getCoverageMapErrString(Err); | |||
772 | } | |||
773 | ||||
774 | static ManagedStatic<CoverageMappingErrorCategoryType> ErrorCategory; | |||
775 | ||||
776 | const std::error_category &llvm::coverage::coveragemap_category() { | |||
777 | return *ErrorCategory; | |||
778 | } | |||
779 | ||||
780 | char CoverageMapError::ID = 0; |
1 | //===- llvm/ADT/SmallBitVector.h - 'Normally small' bit vectors -*- C++ -*-===// |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | // |
9 | // This file implements the SmallBitVector class. |
10 | // |
11 | //===----------------------------------------------------------------------===// |
12 | |
13 | #ifndef LLVM_ADT_SMALLBITVECTOR_H |
14 | #define LLVM_ADT_SMALLBITVECTOR_H |
15 | |
16 | #include "llvm/ADT/BitVector.h" |
17 | #include "llvm/ADT/iterator_range.h" |
18 | #include "llvm/Support/MathExtras.h" |
19 | #include <algorithm> |
20 | #include <cassert> |
21 | #include <climits> |
22 | #include <cstddef> |
23 | #include <cstdint> |
24 | #include <limits> |
25 | #include <utility> |
26 | |
27 | namespace llvm { |
28 | |
29 | /// This is a 'bitvector' (really, a variable-sized bit array), optimized for |
30 | /// the case when the array is small. It contains one pointer-sized field, which |
31 | /// is directly used as a plain collection of bits when possible, or as a |
32 | /// pointer to a larger heap-allocated array when necessary. This allows normal |
33 | /// "small" cases to be fast without losing generality for large inputs. |
34 | class SmallBitVector { |
35 | // TODO: In "large" mode, a pointer to a BitVector is used, leading to an |
36 | // unnecessary level of indirection. It would be more efficient to use a |
37 | // pointer to memory containing size, allocation size, and the array of bits. |
38 | uintptr_t X = 1; |
39 | |
40 | enum { |
41 | // The number of bits in this class. |
42 | NumBaseBits = sizeof(uintptr_t) * CHAR_BIT8, |
43 | |
44 | // One bit is used to discriminate between small and large mode. The |
45 | // remaining bits are used for the small-mode representation. |
46 | SmallNumRawBits = NumBaseBits - 1, |
47 | |
48 | // A few more bits are used to store the size of the bit set in small mode. |
49 | // Theoretically this is a ceil-log2. These bits are encoded in the most |
50 | // significant bits of the raw bits. |
51 | SmallNumSizeBits = (NumBaseBits == 32 ? 5 : |
52 | NumBaseBits == 64 ? 6 : |
53 | SmallNumRawBits), |
54 | |
55 | // The remaining bits are used to store the actual set in small mode. |
56 | SmallNumDataBits = SmallNumRawBits - SmallNumSizeBits |
57 | }; |
58 | |
59 | static_assert(NumBaseBits == 64 || NumBaseBits == 32, |
60 | "Unsupported word size"); |
61 | |
62 | public: |
63 | using size_type = unsigned; |
64 | |
65 | // Encapsulation of a single bit. |
66 | class reference { |
67 | SmallBitVector &TheVector; |
68 | unsigned BitPos; |
69 | |
70 | public: |
71 | reference(SmallBitVector &b, unsigned Idx) : TheVector(b), BitPos(Idx) {} |
72 | |
73 | reference(const reference&) = default; |
74 | |
75 | reference& operator=(reference t) { |
76 | *this = bool(t); |
77 | return *this; |
78 | } |
79 | |
80 | reference& operator=(bool t) { |
81 | if (t) |
82 | TheVector.set(BitPos); |
83 | else |
84 | TheVector.reset(BitPos); |
85 | return *this; |
86 | } |
87 | |
88 | operator bool() const { |
89 | return const_cast<const SmallBitVector &>(TheVector).operator[](BitPos); |
90 | } |
91 | }; |
92 | |
93 | private: |
94 | BitVector *getPointer() const { |
95 | assert(!isSmall())((!isSmall()) ? static_cast<void> (0) : __assert_fail ( "!isSmall()", "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/ADT/SmallBitVector.h" , 95, __PRETTY_FUNCTION__)); |
96 | return reinterpret_cast<BitVector *>(X); |
97 | } |
98 | |
99 | void switchToSmall(uintptr_t NewSmallBits, size_t NewSize) { |
100 | X = 1; |
101 | setSmallSize(NewSize); |
102 | setSmallBits(NewSmallBits); |
103 | } |
104 | |
105 | void switchToLarge(BitVector *BV) { |
106 | X = reinterpret_cast<uintptr_t>(BV); |
107 | assert(!isSmall() && "Tried to use an unaligned pointer")((!isSmall() && "Tried to use an unaligned pointer") ? static_cast<void> (0) : __assert_fail ("!isSmall() && \"Tried to use an unaligned pointer\"" , "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/ADT/SmallBitVector.h" , 107, __PRETTY_FUNCTION__)); |
108 | } |
109 | |
110 | // Return all the bits used for the "small" representation; this includes |
111 | // bits for the size as well as the element bits. |
112 | uintptr_t getSmallRawBits() const { |
113 | assert(isSmall())((isSmall()) ? static_cast<void> (0) : __assert_fail ("isSmall()" , "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/ADT/SmallBitVector.h" , 113, __PRETTY_FUNCTION__)); |
114 | return X >> 1; |
115 | } |
116 | |
117 | void setSmallRawBits(uintptr_t NewRawBits) { |
118 | assert(isSmall())((isSmall()) ? static_cast<void> (0) : __assert_fail ("isSmall()" , "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/ADT/SmallBitVector.h" , 118, __PRETTY_FUNCTION__)); |
119 | X = (NewRawBits << 1) | uintptr_t(1); |
120 | } |
121 | |
122 | // Return the size. |
123 | size_t getSmallSize() const { return getSmallRawBits() >> SmallNumDataBits; } |
124 | |
125 | void setSmallSize(size_t Size) { |
126 | setSmallRawBits(getSmallBits() | (Size << SmallNumDataBits)); |
127 | } |
128 | |
129 | // Return the element bits. |
130 | uintptr_t getSmallBits() const { |
131 | return getSmallRawBits() & ~(~uintptr_t(0) << getSmallSize()); |
132 | } |
133 | |
134 | void setSmallBits(uintptr_t NewBits) { |
135 | setSmallRawBits((NewBits & ~(~uintptr_t(0) << getSmallSize())) | |
136 | (getSmallSize() << SmallNumDataBits)); |
137 | } |
138 | |
139 | public: |
140 | /// Creates an empty bitvector. |
141 | SmallBitVector() = default; |
142 | |
143 | /// Creates a bitvector of specified number of bits. All bits are initialized |
144 | /// to the specified value. |
145 | explicit SmallBitVector(unsigned s, bool t = false) { |
146 | if (s <= SmallNumDataBits) |
147 | switchToSmall(t ? ~uintptr_t(0) : 0, s); |
148 | else |
149 | switchToLarge(new BitVector(s, t)); |
150 | } |
151 | |
152 | /// SmallBitVector copy ctor. |
153 | SmallBitVector(const SmallBitVector &RHS) { |
154 | if (RHS.isSmall()) |
155 | X = RHS.X; |
156 | else |
157 | switchToLarge(new BitVector(*RHS.getPointer())); |
158 | } |
159 | |
160 | SmallBitVector(SmallBitVector &&RHS) : X(RHS.X) { |
161 | RHS.X = 1; |
162 | } |
163 | |
164 | ~SmallBitVector() { |
165 | if (!isSmall()) |
166 | delete getPointer(); |
167 | } |
168 | |
169 | using const_set_bits_iterator = const_set_bits_iterator_impl<SmallBitVector>; |
170 | using set_iterator = const_set_bits_iterator; |
171 | |
172 | const_set_bits_iterator set_bits_begin() const { |
173 | return const_set_bits_iterator(*this); |
174 | } |
175 | |
176 | const_set_bits_iterator set_bits_end() const { |
177 | return const_set_bits_iterator(*this, -1); |
178 | } |
179 | |
180 | iterator_range<const_set_bits_iterator> set_bits() const { |
181 | return make_range(set_bits_begin(), set_bits_end()); |
182 | } |
183 | |
184 | bool isSmall() const { return X & uintptr_t(1); } |
185 | |
186 | /// Tests whether there are no bits in this bitvector. |
187 | bool empty() const { |
188 | return isSmall() ? getSmallSize() == 0 : getPointer()->empty(); |
189 | } |
190 | |
191 | /// Returns the number of bits in this bitvector. |
192 | size_t size() const { |
193 | return isSmall() ? getSmallSize() : getPointer()->size(); |
194 | } |
195 | |
196 | /// Returns the number of bits which are set. |
197 | size_type count() const { |
198 | if (isSmall()) { |
199 | uintptr_t Bits = getSmallBits(); |
200 | return countPopulation(Bits); |
201 | } |
202 | return getPointer()->count(); |
203 | } |
204 | |
205 | /// Returns true if any bit is set. |
206 | bool any() const { |
207 | if (isSmall()) |
208 | return getSmallBits() != 0; |
209 | return getPointer()->any(); |
210 | } |
211 | |
212 | /// Returns true if all bits are set. |
213 | bool all() const { |
214 | if (isSmall()) |
215 | return getSmallBits() == (uintptr_t(1) << getSmallSize()) - 1; |
216 | return getPointer()->all(); |
217 | } |
218 | |
219 | /// Returns true if none of the bits are set. |
220 | bool none() const { |
221 | if (isSmall()) |
222 | return getSmallBits() == 0; |
223 | return getPointer()->none(); |
224 | } |
225 | |
226 | /// Returns the index of the first set bit, -1 if none of the bits are set. |
227 | int find_first() const { |
228 | if (isSmall()) { |
229 | uintptr_t Bits = getSmallBits(); |
230 | if (Bits == 0) |
231 | return -1; |
232 | return countTrailingZeros(Bits); |
233 | } |
234 | return getPointer()->find_first(); |
235 | } |
236 | |
237 | int find_last() const { |
238 | if (isSmall()) { |
239 | uintptr_t Bits = getSmallBits(); |
240 | if (Bits == 0) |
241 | return -1; |
242 | return NumBaseBits - countLeadingZeros(Bits) - 1; |
243 | } |
244 | return getPointer()->find_last(); |
245 | } |
246 | |
247 | /// Returns the index of the first unset bit, -1 if all of the bits are set. |
248 | int find_first_unset() const { |
249 | if (isSmall()) { |
250 | if (count() == getSmallSize()) |
251 | return -1; |
252 | |
253 | uintptr_t Bits = getSmallBits(); |
254 | return countTrailingOnes(Bits); |
255 | } |
256 | return getPointer()->find_first_unset(); |
257 | } |
258 | |
259 | int find_last_unset() const { |
260 | if (isSmall()) { |
261 | if (count() == getSmallSize()) |
262 | return -1; |
263 | |
264 | uintptr_t Bits = getSmallBits(); |
265 | // Set unused bits. |
266 | Bits |= ~uintptr_t(0) << getSmallSize(); |
267 | return NumBaseBits - countLeadingOnes(Bits) - 1; |
268 | } |
269 | return getPointer()->find_last_unset(); |
270 | } |
271 | |
272 | /// Returns the index of the next set bit following the "Prev" bit. |
273 | /// Returns -1 if the next set bit is not found. |
274 | int find_next(unsigned Prev) const { |
275 | if (isSmall()) { |
276 | uintptr_t Bits = getSmallBits(); |
277 | // Mask off previous bits. |
278 | Bits &= ~uintptr_t(0) << (Prev + 1); |
279 | if (Bits == 0 || Prev + 1 >= getSmallSize()) |
280 | return -1; |
281 | return countTrailingZeros(Bits); |
282 | } |
283 | return getPointer()->find_next(Prev); |
284 | } |
285 | |
286 | /// Returns the index of the next unset bit following the "Prev" bit. |
287 | /// Returns -1 if the next unset bit is not found. |
288 | int find_next_unset(unsigned Prev) const { |
289 | if (isSmall()) { |
290 | ++Prev; |
291 | uintptr_t Bits = getSmallBits(); |
292 | // Mask in previous bits. |
293 | uintptr_t Mask = (1 << Prev) - 1; |
294 | Bits |= Mask; |
295 | |
296 | if (Bits == ~uintptr_t(0) || Prev + 1 >= getSmallSize()) |
297 | return -1; |
298 | return countTrailingOnes(Bits); |
299 | } |
300 | return getPointer()->find_next_unset(Prev); |
301 | } |
302 | |
303 | /// find_prev - Returns the index of the first set bit that precedes the |
304 | /// the bit at \p PriorTo. Returns -1 if all previous bits are unset. |
305 | int find_prev(unsigned PriorTo) const { |
306 | if (isSmall()) { |
307 | if (PriorTo == 0) |
308 | return -1; |
309 | |
310 | --PriorTo; |
311 | uintptr_t Bits = getSmallBits(); |
312 | Bits &= maskTrailingOnes<uintptr_t>(PriorTo + 1); |
313 | if (Bits == 0) |
314 | return -1; |
315 | |
316 | return NumBaseBits - countLeadingZeros(Bits) - 1; |
317 | } |
318 | return getPointer()->find_prev(PriorTo); |
319 | } |
320 | |
321 | /// Clear all bits. |
322 | void clear() { |
323 | if (!isSmall()) |
324 | delete getPointer(); |
325 | switchToSmall(0, 0); |
326 | } |
327 | |
328 | /// Grow or shrink the bitvector. |
329 | void resize(unsigned N, bool t = false) { |
330 | if (!isSmall()) { |
331 | getPointer()->resize(N, t); |
332 | } else if (SmallNumDataBits >= N) { |
333 | uintptr_t NewBits = t ? ~uintptr_t(0) << getSmallSize() : 0; |
334 | setSmallSize(N); |
335 | setSmallBits(NewBits | getSmallBits()); |
336 | } else { |
337 | BitVector *BV = new BitVector(N, t); |
338 | uintptr_t OldBits = getSmallBits(); |
339 | for (size_t i = 0, e = getSmallSize(); i != e; ++i) |
340 | (*BV)[i] = (OldBits >> i) & 1; |
341 | switchToLarge(BV); |
342 | } |
343 | } |
344 | |
345 | void reserve(unsigned N) { |
346 | if (isSmall()) { |
347 | if (N > SmallNumDataBits) { |
348 | uintptr_t OldBits = getSmallRawBits(); |
349 | size_t SmallSize = getSmallSize(); |
350 | BitVector *BV = new BitVector(SmallSize); |
351 | for (size_t i = 0; i < SmallSize; ++i) |
352 | if ((OldBits >> i) & 1) |
353 | BV->set(i); |
354 | BV->reserve(N); |
355 | switchToLarge(BV); |
356 | } |
357 | } else { |
358 | getPointer()->reserve(N); |
359 | } |
360 | } |
361 | |
362 | // Set, reset, flip |
363 | SmallBitVector &set() { |
364 | if (isSmall()) |
365 | setSmallBits(~uintptr_t(0)); |
366 | else |
367 | getPointer()->set(); |
368 | return *this; |
369 | } |
370 | |
371 | SmallBitVector &set(unsigned Idx) { |
372 | if (isSmall()) { |
373 | assert(Idx <= static_cast<unsigned>(((Idx <= static_cast<unsigned>( std::numeric_limits< uintptr_t>::digits) && "undefined behavior") ? static_cast <void> (0) : __assert_fail ("Idx <= static_cast<unsigned>( std::numeric_limits<uintptr_t>::digits) && \"undefined behavior\"" , "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/ADT/SmallBitVector.h" , 375, __PRETTY_FUNCTION__)) |
374 | std::numeric_limits<uintptr_t>::digits) &&((Idx <= static_cast<unsigned>( std::numeric_limits< uintptr_t>::digits) && "undefined behavior") ? static_cast <void> (0) : __assert_fail ("Idx <= static_cast<unsigned>( std::numeric_limits<uintptr_t>::digits) && \"undefined behavior\"" , "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/ADT/SmallBitVector.h" , 375, __PRETTY_FUNCTION__)) |
375 | "undefined behavior")((Idx <= static_cast<unsigned>( std::numeric_limits< uintptr_t>::digits) && "undefined behavior") ? static_cast <void> (0) : __assert_fail ("Idx <= static_cast<unsigned>( std::numeric_limits<uintptr_t>::digits) && \"undefined behavior\"" , "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/ADT/SmallBitVector.h" , 375, __PRETTY_FUNCTION__)); |
376 | setSmallBits(getSmallBits() | (uintptr_t(1) << Idx)); |
377 | } |
378 | else |
379 | getPointer()->set(Idx); |
380 | return *this; |
381 | } |
382 | |
383 | /// Efficiently set a range of bits in [I, E) |
384 | SmallBitVector &set(unsigned I, unsigned E) { |
385 | assert(I <= E && "Attempted to set backwards range!")((I <= E && "Attempted to set backwards range!") ? static_cast<void> (0) : __assert_fail ("I <= E && \"Attempted to set backwards range!\"" , "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/ADT/SmallBitVector.h" , 385, __PRETTY_FUNCTION__)); |
386 | assert(E <= size() && "Attempted to set out-of-bounds range!")((E <= size() && "Attempted to set out-of-bounds range!" ) ? static_cast<void> (0) : __assert_fail ("E <= size() && \"Attempted to set out-of-bounds range!\"" , "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/ADT/SmallBitVector.h" , 386, __PRETTY_FUNCTION__)); |
387 | if (I == E) return *this; |
388 | if (isSmall()) { |
389 | uintptr_t EMask = ((uintptr_t)1) << E; |
390 | uintptr_t IMask = ((uintptr_t)1) << I; |
391 | uintptr_t Mask = EMask - IMask; |
392 | setSmallBits(getSmallBits() | Mask); |
393 | } else |
394 | getPointer()->set(I, E); |
395 | return *this; |
396 | } |
397 | |
398 | SmallBitVector &reset() { |
399 | if (isSmall()) |
400 | setSmallBits(0); |
401 | else |
402 | getPointer()->reset(); |
403 | return *this; |
404 | } |
405 | |
406 | SmallBitVector &reset(unsigned Idx) { |
407 | if (isSmall()) |
408 | setSmallBits(getSmallBits() & ~(uintptr_t(1) << Idx)); |
409 | else |
410 | getPointer()->reset(Idx); |
411 | return *this; |
412 | } |
413 | |
414 | /// Efficiently reset a range of bits in [I, E) |
415 | SmallBitVector &reset(unsigned I, unsigned E) { |
416 | assert(I <= E && "Attempted to reset backwards range!")((I <= E && "Attempted to reset backwards range!") ? static_cast<void> (0) : __assert_fail ("I <= E && \"Attempted to reset backwards range!\"" , "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/ADT/SmallBitVector.h" , 416, __PRETTY_FUNCTION__)); |
417 | assert(E <= size() && "Attempted to reset out-of-bounds range!")((E <= size() && "Attempted to reset out-of-bounds range!" ) ? static_cast<void> (0) : __assert_fail ("E <= size() && \"Attempted to reset out-of-bounds range!\"" , "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/ADT/SmallBitVector.h" , 417, __PRETTY_FUNCTION__)); |
418 | if (I == E) return *this; |
419 | if (isSmall()) { |
420 | uintptr_t EMask = ((uintptr_t)1) << E; |
421 | uintptr_t IMask = ((uintptr_t)1) << I; |
422 | uintptr_t Mask = EMask - IMask; |
423 | setSmallBits(getSmallBits() & ~Mask); |
424 | } else |
425 | getPointer()->reset(I, E); |
426 | return *this; |
427 | } |
428 | |
429 | SmallBitVector &flip() { |
430 | if (isSmall()) |
431 | setSmallBits(~getSmallBits()); |
432 | else |
433 | getPointer()->flip(); |
434 | return *this; |
435 | } |
436 | |
437 | SmallBitVector &flip(unsigned Idx) { |
438 | if (isSmall()) |
439 | setSmallBits(getSmallBits() ^ (uintptr_t(1) << Idx)); |
440 | else |
441 | getPointer()->flip(Idx); |
442 | return *this; |
443 | } |
444 | |
445 | // No argument flip. |
446 | SmallBitVector operator~() const { |
447 | return SmallBitVector(*this).flip(); |
448 | } |
449 | |
450 | // Indexing. |
451 | reference operator[](unsigned Idx) { |
452 | assert(Idx < size() && "Out-of-bounds Bit access.")((Idx < size() && "Out-of-bounds Bit access.") ? static_cast <void> (0) : __assert_fail ("Idx < size() && \"Out-of-bounds Bit access.\"" , "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/ADT/SmallBitVector.h" , 452, __PRETTY_FUNCTION__)); |
453 | return reference(*this, Idx); |
454 | } |
455 | |
456 | bool operator[](unsigned Idx) const { |
457 | assert(Idx < size() && "Out-of-bounds Bit access.")((Idx < size() && "Out-of-bounds Bit access.") ? static_cast <void> (0) : __assert_fail ("Idx < size() && \"Out-of-bounds Bit access.\"" , "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/ADT/SmallBitVector.h" , 457, __PRETTY_FUNCTION__)); |
458 | if (isSmall()) |
459 | return ((getSmallBits() >> Idx) & 1) != 0; |
460 | return getPointer()->operator[](Idx); |
461 | } |
462 | |
463 | bool test(unsigned Idx) const { |
464 | return (*this)[Idx]; |
465 | } |
466 | |
467 | // Push single bit to end of vector. |
468 | void push_back(bool Val) { |
469 | resize(size() + 1, Val); |
470 | } |
471 | |
472 | /// Test if any common bits are set. |
473 | bool anyCommon(const SmallBitVector &RHS) const { |
474 | if (isSmall() && RHS.isSmall()) |
475 | return (getSmallBits() & RHS.getSmallBits()) != 0; |
476 | if (!isSmall() && !RHS.isSmall()) |
477 | return getPointer()->anyCommon(*RHS.getPointer()); |
478 | |
479 | for (unsigned i = 0, e = std::min(size(), RHS.size()); i != e; ++i) |
480 | if (test(i) && RHS.test(i)) |
481 | return true; |
482 | return false; |
483 | } |
484 | |
485 | // Comparison operators. |
486 | bool operator==(const SmallBitVector &RHS) const { |
487 | if (size() != RHS.size()) |
488 | return false; |
489 | if (isSmall() && RHS.isSmall()) |
490 | return getSmallBits() == RHS.getSmallBits(); |
491 | else if (!isSmall() && !RHS.isSmall()) |
492 | return *getPointer() == *RHS.getPointer(); |
493 | else { |
494 | for (size_t i = 0, e = size(); i != e; ++i) { |
495 | if ((*this)[i] != RHS[i]) |
496 | return false; |
497 | } |
498 | return true; |
499 | } |
500 | } |
501 | |
502 | bool operator!=(const SmallBitVector &RHS) const { |
503 | return !(*this == RHS); |
504 | } |
505 | |
506 | // Intersection, union, disjoint union. |
507 | // FIXME BitVector::operator&= does not resize the LHS but this does |
508 | SmallBitVector &operator&=(const SmallBitVector &RHS) { |
509 | resize(std::max(size(), RHS.size())); |
510 | if (isSmall() && RHS.isSmall()) |
511 | setSmallBits(getSmallBits() & RHS.getSmallBits()); |
512 | else if (!isSmall() && !RHS.isSmall()) |
513 | getPointer()->operator&=(*RHS.getPointer()); |
514 | else { |
515 | size_t i, e; |
516 | for (i = 0, e = std::min(size(), RHS.size()); i != e; ++i) |
517 | (*this)[i] = test(i) && RHS.test(i); |
518 | for (e = size(); i != e; ++i) |
519 | reset(i); |
520 | } |
521 | return *this; |
522 | } |
523 | |
524 | /// Reset bits that are set in RHS. Same as *this &= ~RHS. |
525 | SmallBitVector &reset(const SmallBitVector &RHS) { |
526 | if (isSmall() && RHS.isSmall()) |
527 | setSmallBits(getSmallBits() & ~RHS.getSmallBits()); |
528 | else if (!isSmall() && !RHS.isSmall()) |
529 | getPointer()->reset(*RHS.getPointer()); |
530 | else |
531 | for (unsigned i = 0, e = std::min(size(), RHS.size()); i != e; ++i) |
532 | if (RHS.test(i)) |
533 | reset(i); |
534 | |
535 | return *this; |
536 | } |
537 | |
538 | /// Check if (This - RHS) is zero. This is the same as reset(RHS) and any(). |
539 | bool test(const SmallBitVector &RHS) const { |
540 | if (isSmall() && RHS.isSmall()) |
541 | return (getSmallBits() & ~RHS.getSmallBits()) != 0; |
542 | if (!isSmall() && !RHS.isSmall()) |
543 | return getPointer()->test(*RHS.getPointer()); |
544 | |
545 | unsigned i, e; |
546 | for (i = 0, e = std::min(size(), RHS.size()); i != e; ++i) |
547 | if (test(i) && !RHS.test(i)) |
548 | return true; |
549 | |
550 | for (e = size(); i != e; ++i) |
551 | if (test(i)) |
552 | return true; |
553 | |
554 | return false; |
555 | } |
556 | |
557 | SmallBitVector &operator|=(const SmallBitVector &RHS) { |
558 | resize(std::max(size(), RHS.size())); |
559 | if (isSmall() && RHS.isSmall()) |
560 | setSmallBits(getSmallBits() | RHS.getSmallBits()); |
561 | else if (!isSmall() && !RHS.isSmall()) |
562 | getPointer()->operator|=(*RHS.getPointer()); |
563 | else { |
564 | for (size_t i = 0, e = RHS.size(); i != e; ++i) |
565 | (*this)[i] = test(i) || RHS.test(i); |
566 | } |
567 | return *this; |
568 | } |
569 | |
570 | SmallBitVector &operator^=(const SmallBitVector &RHS) { |
571 | resize(std::max(size(), RHS.size())); |
572 | if (isSmall() && RHS.isSmall()) |
573 | setSmallBits(getSmallBits() ^ RHS.getSmallBits()); |
574 | else if (!isSmall() && !RHS.isSmall()) |
575 | getPointer()->operator^=(*RHS.getPointer()); |
576 | else { |
577 | for (size_t i = 0, e = RHS.size(); i != e; ++i) |
578 | (*this)[i] = test(i) != RHS.test(i); |
579 | } |
580 | return *this; |
581 | } |
582 | |
583 | SmallBitVector &operator<<=(unsigned N) { |
584 | if (isSmall()) |
585 | setSmallBits(getSmallBits() << N); |
586 | else |
587 | getPointer()->operator<<=(N); |
588 | return *this; |
589 | } |
590 | |
591 | SmallBitVector &operator>>=(unsigned N) { |
592 | if (isSmall()) |
593 | setSmallBits(getSmallBits() >> N); |
594 | else |
595 | getPointer()->operator>>=(N); |
596 | return *this; |
597 | } |
598 | |
599 | // Assignment operator. |
600 | const SmallBitVector &operator=(const SmallBitVector &RHS) { |
601 | if (isSmall()) { |
602 | if (RHS.isSmall()) |
603 | X = RHS.X; |
604 | else |
605 | switchToLarge(new BitVector(*RHS.getPointer())); |
606 | } else { |
607 | if (!RHS.isSmall()) |
608 | *getPointer() = *RHS.getPointer(); |
609 | else { |
610 | delete getPointer(); |
611 | X = RHS.X; |
612 | } |
613 | } |
614 | return *this; |
615 | } |
616 | |
617 | const SmallBitVector &operator=(SmallBitVector &&RHS) { |
618 | if (this != &RHS) { |
619 | clear(); |
620 | swap(RHS); |
621 | } |
622 | return *this; |
623 | } |
624 | |
625 | void swap(SmallBitVector &RHS) { |
626 | std::swap(X, RHS.X); |
627 | } |
628 | |
629 | /// Add '1' bits from Mask to this vector. Don't resize. |
630 | /// This computes "*this |= Mask". |
631 | void setBitsInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) { |
632 | if (isSmall()) |
633 | applyMask<true, false>(Mask, MaskWords); |
634 | else |
635 | getPointer()->setBitsInMask(Mask, MaskWords); |
636 | } |
637 | |
638 | /// Clear any bits in this vector that are set in Mask. Don't resize. |
639 | /// This computes "*this &= ~Mask". |
640 | void clearBitsInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) { |
641 | if (isSmall()) |
642 | applyMask<false, false>(Mask, MaskWords); |
643 | else |
644 | getPointer()->clearBitsInMask(Mask, MaskWords); |
645 | } |
646 | |
647 | /// Add a bit to this vector for every '0' bit in Mask. Don't resize. |
648 | /// This computes "*this |= ~Mask". |
649 | void setBitsNotInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) { |
650 | if (isSmall()) |
651 | applyMask<true, true>(Mask, MaskWords); |
652 | else |
653 | getPointer()->setBitsNotInMask(Mask, MaskWords); |
654 | } |
655 | |
656 | /// Clear a bit in this vector for every '0' bit in Mask. Don't resize. |
657 | /// This computes "*this &= Mask". |
658 | void clearBitsNotInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) { |
659 | if (isSmall()) |
660 | applyMask<false, true>(Mask, MaskWords); |
661 | else |
662 | getPointer()->clearBitsNotInMask(Mask, MaskWords); |
663 | } |
664 | |
665 | private: |
666 | template <bool AddBits, bool InvertMask> |
667 | void applyMask(const uint32_t *Mask, unsigned MaskWords) { |
668 | assert(MaskWords <= sizeof(uintptr_t) && "Mask is larger than base!")((MaskWords <= sizeof(uintptr_t) && "Mask is larger than base!" ) ? static_cast<void> (0) : __assert_fail ("MaskWords <= sizeof(uintptr_t) && \"Mask is larger than base!\"" , "/build/llvm-toolchain-snapshot-9~svn362543/include/llvm/ADT/SmallBitVector.h" , 668, __PRETTY_FUNCTION__)); |
669 | uintptr_t M = Mask[0]; |
670 | if (NumBaseBits == 64) |
671 | M |= uint64_t(Mask[1]) << 32; |
672 | if (InvertMask) |
673 | M = ~M; |
674 | if (AddBits) |
675 | setSmallBits(getSmallBits() | M); |
676 | else |
677 | setSmallBits(getSmallBits() & ~M); |
678 | } |
679 | }; |
680 | |
681 | inline SmallBitVector |
682 | operator&(const SmallBitVector &LHS, const SmallBitVector &RHS) { |
683 | SmallBitVector Result(LHS); |
684 | Result &= RHS; |
685 | return Result; |
686 | } |
687 | |
688 | inline SmallBitVector |
689 | operator|(const SmallBitVector &LHS, const SmallBitVector &RHS) { |
690 | SmallBitVector Result(LHS); |
691 | Result |= RHS; |
692 | return Result; |
693 | } |
694 | |
695 | inline SmallBitVector |
696 | operator^(const SmallBitVector &LHS, const SmallBitVector &RHS) { |
697 | SmallBitVector Result(LHS); |
698 | Result ^= RHS; |
699 | return Result; |
700 | } |
701 | |
702 | } // end namespace llvm |
703 | |
704 | namespace std { |
705 | |
706 | /// Implement std::swap in terms of BitVector swap. |
707 | inline void |
708 | swap(llvm::SmallBitVector &LHS, llvm::SmallBitVector &RHS) { |
709 | LHS.swap(RHS); |
710 | } |
711 | |
712 | } // end namespace std |
713 | |
714 | #endif // LLVM_ADT_SMALLBITVECTOR_H |