llvm.org GIT mirror llvm / 6a4e43b
[ADT] Add BitVector::find_prev. This almost completes the matrix of all possible find functions. *EXISTING* ---------- find_first find_first_unset find_next find_next_unset find_last find_last_unset *NEW* ---- find_prev *STILL MISSING* --------------- find_prev_unset Differential Revision: https://reviews.llvm.org/D32885 git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@302254 91177308-0d34-0410-b5e6-96231b3b80d8 Zachary Turner 2 years ago
3 changed file(s) with 55 addition(s) and 0 deletion(s). Raw diff Collapse all Expand all
249249 for (unsigned i = WordPos + 1; i < NumBitWords(size()); ++i)
250250 if (Bits[i] != ~0UL)
251251 return next_unset_in_word(i, Bits[i]);
252 return -1;
253 }
254
255 /// find_prev - Returns the index of the first set bit that precedes the
256 /// the bit at \p PriorTo. Returns -1 if all previous bits are unset.
257 int find_prev(unsigned PriorTo) {
258 if (PriorTo == 0)
259 return -1;
260
261 --PriorTo;
262
263 unsigned WordPos = PriorTo / BITWORD_SIZE;
264 unsigned BitPos = PriorTo % BITWORD_SIZE;
265 BitWord Copy = Bits[WordPos];
266 // Mask off next bits.
267 Copy &= maskTrailingOnes(BitPos + 1);
268
269 if (Copy != 0)
270 return (WordPos + 1) * BITWORD_SIZE - countLeadingZeros(Copy) - 1;
271
272 // Check previous words.
273 for (unsigned i = 1; i <= WordPos; ++i) {
274 unsigned Index = WordPos - i;
275 if (Bits[Index] == 0)
276 continue;
277 return (Index + 1) * BITWORD_SIZE - countLeadingZeros(Bits[Index]) - 1;
278 }
252279 return -1;
253280 }
254281
275275 return countTrailingOnes(Bits);
276276 }
277277 return getPointer()->find_next_unset(Prev);
278 }
279
280 /// find_prev - Returns the index of the first set bit that precedes the
281 /// the bit at \p PriorTo. Returns -1 if all previous bits are unset.
282 int find_prev(unsigned PriorTo) const {
283 if (isSmall()) {
284 if (PriorTo == 0)
285 return -1;
286
287 --PriorTo;
288 uintptr_t Bits = getSmallBits();
289 Bits &= maskTrailingOnes(PriorTo + 1);
290 if (Bits == 0)
291 return -1;
292
293 return NumBaseBits - countLeadingZeros(Bits) - 1;
294 }
295 return getPointer()->find_prev(PriorTo);
278296 }
279297
280298 /// Clear all bits.
203203 EXPECT_EQ(75, A.find_next(13));
204204 EXPECT_EQ(-1, A.find_next(75));
205205
206 EXPECT_EQ(-1, A.find_prev(12));
207 EXPECT_EQ(12, A.find_prev(13));
208 EXPECT_EQ(13, A.find_prev(75));
209 EXPECT_EQ(75, A.find_prev(90));
210
206211 EXPECT_EQ(0, A.find_first_unset());
207212 EXPECT_EQ(99, A.find_last_unset());
208213 EXPECT_EQ(14, A.find_next_unset(11));
238243 EXPECT_EQ(4, A.find_next(3));
239244 EXPECT_EQ(16, A.find_next(4));
240245 EXPECT_EQ(-1, A.find_next(16));
246
247 EXPECT_EQ(-1, A.find_prev(3));
248 EXPECT_EQ(3, A.find_prev(4));
249 EXPECT_EQ(4, A.find_prev(16));
250 EXPECT_EQ(16, A.find_prev(18));
241251
242252 EXPECT_EQ(0, A.find_first_unset());
243253 EXPECT_EQ(19, A.find_last_unset());