blob: 85503131ad8d6e18fcc9f5ca0db9749e92c2f9a6 [file] [log] [blame]
Hal Finkel7529c552014-09-02 21:43:13 +00001//===- StratifiedSets.h - Abstract stratified sets implementation. --------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#ifndef LLVM_ADT_STRATIFIEDSETS_H
11#define LLVM_ADT_STRATIFIEDSETS_H
12
13#include "llvm/ADT/DenseMap.h"
14#include "llvm/ADT/Optional.h"
Hal Finkel7529c552014-09-02 21:43:13 +000015#include "llvm/ADT/SmallSet.h"
16#include "llvm/ADT/SmallVector.h"
17#include <bitset>
18#include <cassert>
19#include <cmath>
Hal Finkel7529c552014-09-02 21:43:13 +000020#include <type_traits>
Hal Finkel8d1590d2014-09-02 22:52:30 +000021#include <utility>
Hal Finkel7529c552014-09-02 21:43:13 +000022#include <vector>
23
24namespace llvm {
George Burgess IVcae581d2016-04-13 23:27:37 +000025/// An index into Stratified Sets.
Hal Finkel7529c552014-09-02 21:43:13 +000026typedef unsigned StratifiedIndex;
George Burgess IVcae581d2016-04-13 23:27:37 +000027/// NOTE: ^ This can't be a short -- bootstrapping clang has a case where
28/// ~1M sets exist.
Hal Finkel7529c552014-09-02 21:43:13 +000029
30// \brief Container of information related to a value in a StratifiedSet.
31struct StratifiedInfo {
32 StratifiedIndex Index;
George Burgess IVcae581d2016-04-13 23:27:37 +000033 /// For field sensitivity, etc. we can tack fields on here.
Hal Finkel7529c552014-09-02 21:43:13 +000034};
35
George Burgess IVcae581d2016-04-13 23:27:37 +000036/// The number of attributes that StratifiedAttrs should contain. Attributes are
37/// described below, and 32 was an arbitrary choice because it fits nicely in 32
38/// bits (because we use a bitset for StratifiedAttrs).
Hal Finkel981602a2014-09-02 22:26:06 +000039static const unsigned NumStratifiedAttrs = 32;
Hal Finkel7529c552014-09-02 21:43:13 +000040
George Burgess IVcae581d2016-04-13 23:27:37 +000041/// These are attributes that the users of StratifiedSets/StratifiedSetBuilders
42/// may use for various purposes. These also have the special property of that
43/// they are merged down. So, if set A is above set B, and one decides to set an
44/// attribute in set A, then the attribute will automatically be set in set B.
Hal Finkel7529c552014-09-02 21:43:13 +000045typedef std::bitset<NumStratifiedAttrs> StratifiedAttrs;
46
George Burgess IVcae581d2016-04-13 23:27:37 +000047/// A "link" between two StratifiedSets.
Hal Finkel7529c552014-09-02 21:43:13 +000048struct StratifiedLink {
George Burgess IVcae581d2016-04-13 23:27:37 +000049 /// \brief This is a value used to signify "does not exist" where the
50 /// StratifiedIndex type is used.
51 ///
52 /// This is used instead of Optional<StratifiedIndex> because
53 /// Optional<StratifiedIndex> would eat up a considerable amount of extra
54 /// memory, after struct padding/alignment is taken into account.
Hal Finkel1ae325f2014-09-02 23:50:01 +000055 static const StratifiedIndex SetSentinel;
Hal Finkel7529c552014-09-02 21:43:13 +000056
George Burgess IVcae581d2016-04-13 23:27:37 +000057 /// The index for the set "above" current
Hal Finkel7529c552014-09-02 21:43:13 +000058 StratifiedIndex Above;
59
George Burgess IVcae581d2016-04-13 23:27:37 +000060 /// The link for the set "below" current
Hal Finkel7529c552014-09-02 21:43:13 +000061 StratifiedIndex Below;
62
George Burgess IVcae581d2016-04-13 23:27:37 +000063 /// Attributes for these StratifiedSets.
Hal Finkel7529c552014-09-02 21:43:13 +000064 StratifiedAttrs Attrs;
65
66 StratifiedLink() : Above(SetSentinel), Below(SetSentinel) {}
67
68 bool hasBelow() const { return Below != SetSentinel; }
69 bool hasAbove() const { return Above != SetSentinel; }
70
71 void clearBelow() { Below = SetSentinel; }
72 void clearAbove() { Above = SetSentinel; }
73};
74
George Burgess IVcae581d2016-04-13 23:27:37 +000075/// \brief These are stratified sets, as described in "Fast algorithms for
76/// Dyck-CFL-reachability with applications to Alias Analysis" by Zhang Q, Lyu M
77/// R, Yuan H, and Su Z. -- in short, this is meant to represent different sets
78/// of Value*s. If two Value*s are in the same set, or if both sets have
79/// overlapping attributes, then the Value*s are said to alias.
80///
81/// Sets may be related by position, meaning that one set may be considered as
82/// above or below another. In CFL Alias Analysis, this gives us an indication
83/// of how two variables are related; if the set of variable A is below a set
84/// containing variable B, then at some point, a variable that has interacted
85/// with B (or B itself) was either used in order to extract the variable A, or
86/// was used as storage of variable A.
87///
88/// Sets may also have attributes (as noted above). These attributes are
89/// generally used for noting whether a variable in the set has interacted with
90/// a variable whose origins we don't quite know (i.e. globals/arguments), or if
91/// the variable may have had operations performed on it (modified in a function
92/// call). All attributes that exist in a set A must exist in all sets marked as
93/// below set A.
Hal Finkel7529c552014-09-02 21:43:13 +000094template <typename T> class StratifiedSets {
95public:
George Burgess IV60af2262016-06-07 21:41:18 +000096 StratifiedSets() = default;
97 // If we have a need to copy these at some point, it's fine to default this.
98 // At the time of writing, copying StratifiedSets is always a perf bug.
99 StratifiedSets(const StratifiedSets &) = delete;
100 StratifiedSets(StratifiedSets &&Other) = default;
Hal Finkel7529c552014-09-02 21:43:13 +0000101
102 StratifiedSets(DenseMap<T, StratifiedInfo> Map,
103 std::vector<StratifiedLink> Links)
104 : Values(std::move(Map)), Links(std::move(Links)) {}
105
George Burgess IV60af2262016-06-07 21:41:18 +0000106 StratifiedSets &operator=(StratifiedSets<T> &&Other) = default;
Hal Finkel7529c552014-09-02 21:43:13 +0000107
108 Optional<StratifiedInfo> find(const T &Elem) const {
109 auto Iter = Values.find(Elem);
George Burgess IVcae581d2016-04-13 23:27:37 +0000110 if (Iter == Values.end())
111 return None;
Hal Finkel7529c552014-09-02 21:43:13 +0000112 return Iter->second;
113 }
114
115 const StratifiedLink &getLink(StratifiedIndex Index) const {
116 assert(inbounds(Index));
117 return Links[Index];
118 }
119
120private:
121 DenseMap<T, StratifiedInfo> Values;
122 std::vector<StratifiedLink> Links;
123
124 bool inbounds(StratifiedIndex Idx) const { return Idx < Links.size(); }
125};
126
George Burgess IVcae581d2016-04-13 23:27:37 +0000127/// Generic Builder class that produces StratifiedSets instances.
128///
129/// The goal of this builder is to efficiently produce correct StratifiedSets
130/// instances. To this end, we use a few tricks:
131/// > Set chains (A method for linking sets together)
132/// > Set remaps (A method for marking a set as an alias [irony?] of another)
133///
134/// ==== Set chains ====
135/// This builder has a notion of some value A being above, below, or with some
136/// other value B:
137/// > The `A above B` relationship implies that there is a reference edge
138/// going from A to B. Namely, it notes that A can store anything in B's set.
139/// > The `A below B` relationship is the opposite of `A above B`. It implies
140/// that there's a dereference edge going from A to B.
141/// > The `A with B` relationship states that there's an assignment edge going
142/// from A to B, and that A and B should be treated as equals.
143///
144/// As an example, take the following code snippet:
145///
146/// %a = alloca i32, align 4
147/// %ap = alloca i32*, align 8
148/// %app = alloca i32**, align 8
149/// store %a, %ap
150/// store %ap, %app
George Burgess IV60af2262016-06-07 21:41:18 +0000151/// %aw = getelementptr %ap, i32 0
George Burgess IVcae581d2016-04-13 23:27:37 +0000152///
George Burgess IV60af2262016-06-07 21:41:18 +0000153/// Given this, the following relations exist:
George Burgess IVcae581d2016-04-13 23:27:37 +0000154/// - %a below %ap & %ap above %a
155/// - %ap below %app & %app above %ap
156/// - %aw with %ap & %ap with %aw
157///
158/// These relations produce the following sets:
159/// [{%a}, {%ap, %aw}, {%app}]
160///
George Burgess IV60af2262016-06-07 21:41:18 +0000161/// ...Which state that the only MayAlias relationship in the above program is
George Burgess IVcae581d2016-04-13 23:27:37 +0000162/// between %ap and %aw.
163///
George Burgess IV60af2262016-06-07 21:41:18 +0000164/// Because LLVM allows arbitrary casts, code like the following needs to be
165/// supported:
166/// %ip = alloca i64, align 8
167/// %ipp = alloca i64*, align 8
168/// %i = bitcast i64** ipp to i64
169/// store i64* %ip, i64** %ipp
170/// store i64 %i, i64* %ip
George Burgess IVcae581d2016-04-13 23:27:37 +0000171///
George Burgess IV60af2262016-06-07 21:41:18 +0000172/// Which, because %ipp ends up *both* above and below %ip, is fun.
George Burgess IVcae581d2016-04-13 23:27:37 +0000173///
George Burgess IV60af2262016-06-07 21:41:18 +0000174/// This is solved by merging %i and %ipp into a single set (...which is the
175/// only way to solve this, since their bit patterns are equivalent). Any sets
176/// that ended up in between %i and %ipp at the time of merging (in this case,
177/// the set containing %ip) also get conservatively merged into the set of %i
178/// and %ipp. In short, the resulting StratifiedSet from the above code would be
179/// {%ip, %ipp, %i}.
George Burgess IVcae581d2016-04-13 23:27:37 +0000180///
181/// ==== Set remaps ====
182/// More of an implementation detail than anything -- when merging sets, we need
183/// to update the numbers of all of the elements mapped to those sets. Rather
184/// than doing this at each merge, we note in the BuilderLink structure that a
185/// remap has occurred, and use this information so we can defer renumbering set
186/// elements until build time.
Hal Finkel7529c552014-09-02 21:43:13 +0000187template <typename T> class StratifiedSetsBuilder {
George Burgess IVcae581d2016-04-13 23:27:37 +0000188 /// \brief Represents a Stratified Set, with information about the Stratified
189 /// Set above it, the set below it, and whether the current set has been
190 /// remapped to another.
Hal Finkel7529c552014-09-02 21:43:13 +0000191 struct BuilderLink {
192 const StratifiedIndex Number;
193
194 BuilderLink(StratifiedIndex N) : Number(N) {
195 Remap = StratifiedLink::SetSentinel;
196 }
197
198 bool hasAbove() const {
199 assert(!isRemapped());
200 return Link.hasAbove();
201 }
202
203 bool hasBelow() const {
204 assert(!isRemapped());
205 return Link.hasBelow();
206 }
207
208 void setBelow(StratifiedIndex I) {
209 assert(!isRemapped());
210 Link.Below = I;
211 }
212
213 void setAbove(StratifiedIndex I) {
214 assert(!isRemapped());
215 Link.Above = I;
216 }
217
218 void clearBelow() {
219 assert(!isRemapped());
220 Link.clearBelow();
221 }
222
223 void clearAbove() {
224 assert(!isRemapped());
225 Link.clearAbove();
226 }
227
228 StratifiedIndex getBelow() const {
229 assert(!isRemapped());
230 assert(hasBelow());
231 return Link.Below;
232 }
233
234 StratifiedIndex getAbove() const {
235 assert(!isRemapped());
236 assert(hasAbove());
237 return Link.Above;
238 }
239
240 StratifiedAttrs &getAttrs() {
241 assert(!isRemapped());
242 return Link.Attrs;
243 }
244
Hal Finkel7529c552014-09-02 21:43:13 +0000245 void setAttrs(const StratifiedAttrs &other) {
246 assert(!isRemapped());
247 Link.Attrs |= other;
248 }
249
250 bool isRemapped() const { return Remap != StratifiedLink::SetSentinel; }
251
George Burgess IVcae581d2016-04-13 23:27:37 +0000252 /// For initial remapping to another set
Hal Finkel7529c552014-09-02 21:43:13 +0000253 void remapTo(StratifiedIndex Other) {
254 assert(!isRemapped());
255 Remap = Other;
256 }
257
258 StratifiedIndex getRemapIndex() const {
259 assert(isRemapped());
260 return Remap;
261 }
262
George Burgess IVcae581d2016-04-13 23:27:37 +0000263 /// Should only be called when we're already remapped.
Hal Finkel7529c552014-09-02 21:43:13 +0000264 void updateRemap(StratifiedIndex Other) {
265 assert(isRemapped());
266 Remap = Other;
267 }
268
George Burgess IVcae581d2016-04-13 23:27:37 +0000269 /// Prefer the above functions to calling things directly on what's returned
270 /// from this -- they guard against unexpected calls when the current
271 /// BuilderLink is remapped.
Hal Finkel7529c552014-09-02 21:43:13 +0000272 const StratifiedLink &getLink() const { return Link; }
273
274 private:
275 StratifiedLink Link;
276 StratifiedIndex Remap;
277 };
278
George Burgess IVcae581d2016-04-13 23:27:37 +0000279 /// \brief This function performs all of the set unioning/value renumbering
280 /// that we've been putting off, and generates a vector<StratifiedLink> that
281 /// may be placed in a StratifiedSets instance.
Hal Finkel7529c552014-09-02 21:43:13 +0000282 void finalizeSets(std::vector<StratifiedLink> &StratLinks) {
283 DenseMap<StratifiedIndex, StratifiedIndex> Remaps;
284 for (auto &Link : Links) {
George Burgess IVcae581d2016-04-13 23:27:37 +0000285 if (Link.isRemapped())
Hal Finkel7529c552014-09-02 21:43:13 +0000286 continue;
Hal Finkel7529c552014-09-02 21:43:13 +0000287
288 StratifiedIndex Number = StratLinks.size();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000289 Remaps.insert(std::make_pair(Link.Number, Number));
Hal Finkel7529c552014-09-02 21:43:13 +0000290 StratLinks.push_back(Link.getLink());
291 }
292
293 for (auto &Link : StratLinks) {
294 if (Link.hasAbove()) {
295 auto &Above = linksAt(Link.Above);
296 auto Iter = Remaps.find(Above.Number);
297 assert(Iter != Remaps.end());
298 Link.Above = Iter->second;
299 }
300
301 if (Link.hasBelow()) {
302 auto &Below = linksAt(Link.Below);
303 auto Iter = Remaps.find(Below.Number);
304 assert(Iter != Remaps.end());
305 Link.Below = Iter->second;
306 }
307 }
308
309 for (auto &Pair : Values) {
310 auto &Info = Pair.second;
311 auto &Link = linksAt(Info.Index);
312 auto Iter = Remaps.find(Link.Number);
313 assert(Iter != Remaps.end());
314 Info.Index = Iter->second;
315 }
316 }
317
George Burgess IVcae581d2016-04-13 23:27:37 +0000318 /// \brief There's a guarantee in StratifiedLink where all bits set in a
319 /// Link.externals will be set in all Link.externals "below" it.
Hal Finkel7529c552014-09-02 21:43:13 +0000320 static void propagateAttrs(std::vector<StratifiedLink> &Links) {
321 const auto getHighestParentAbove = [&Links](StratifiedIndex Idx) {
322 const auto *Link = &Links[Idx];
323 while (Link->hasAbove()) {
324 Idx = Link->Above;
325 Link = &Links[Idx];
326 }
327 return Idx;
328 };
329
330 SmallSet<StratifiedIndex, 16> Visited;
331 for (unsigned I = 0, E = Links.size(); I < E; ++I) {
332 auto CurrentIndex = getHighestParentAbove(I);
George Burgess IVcae581d2016-04-13 23:27:37 +0000333 if (!Visited.insert(CurrentIndex).second)
Hal Finkel7529c552014-09-02 21:43:13 +0000334 continue;
Hal Finkel7529c552014-09-02 21:43:13 +0000335
336 while (Links[CurrentIndex].hasBelow()) {
337 auto &CurrentBits = Links[CurrentIndex].Attrs;
338 auto NextIndex = Links[CurrentIndex].Below;
339 auto &NextBits = Links[NextIndex].Attrs;
340 NextBits |= CurrentBits;
341 CurrentIndex = NextIndex;
342 }
343 }
344 }
345
346public:
George Burgess IVcae581d2016-04-13 23:27:37 +0000347 /// Builds a StratifiedSet from the information we've been given since either
348 /// construction or the prior build() call.
Hal Finkel7529c552014-09-02 21:43:13 +0000349 StratifiedSets<T> build() {
350 std::vector<StratifiedLink> StratLinks;
351 finalizeSets(StratLinks);
352 propagateAttrs(StratLinks);
353 Links.clear();
354 return StratifiedSets<T>(std::move(Values), std::move(StratLinks));
355 }
356
Hal Finkel7529c552014-09-02 21:43:13 +0000357 bool has(const T &Elem) const { return get(Elem).hasValue(); }
358
359 bool add(const T &Main) {
360 if (get(Main).hasValue())
361 return false;
362
363 auto NewIndex = getNewUnlinkedIndex();
364 return addAtMerging(Main, NewIndex);
365 }
366
George Burgess IVcae581d2016-04-13 23:27:37 +0000367 /// \brief Restructures the stratified sets as necessary to make "ToAdd" in a
368 /// set above "Main". There are some cases where this is not possible (see
369 /// above), so we merge them such that ToAdd and Main are in the same set.
Hal Finkel7529c552014-09-02 21:43:13 +0000370 bool addAbove(const T &Main, const T &ToAdd) {
371 assert(has(Main));
372 auto Index = *indexOf(Main);
373 if (!linksAt(Index).hasAbove())
374 addLinkAbove(Index);
375
376 auto Above = linksAt(Index).getAbove();
377 return addAtMerging(ToAdd, Above);
378 }
379
George Burgess IVcae581d2016-04-13 23:27:37 +0000380 /// \brief Restructures the stratified sets as necessary to make "ToAdd" in a
381 /// set below "Main". There are some cases where this is not possible (see
382 /// above), so we merge them such that ToAdd and Main are in the same set.
Hal Finkel7529c552014-09-02 21:43:13 +0000383 bool addBelow(const T &Main, const T &ToAdd) {
384 assert(has(Main));
385 auto Index = *indexOf(Main);
386 if (!linksAt(Index).hasBelow())
387 addLinkBelow(Index);
388
389 auto Below = linksAt(Index).getBelow();
390 return addAtMerging(ToAdd, Below);
391 }
392
393 bool addWith(const T &Main, const T &ToAdd) {
394 assert(has(Main));
395 auto MainIndex = *indexOf(Main);
396 return addAtMerging(ToAdd, MainIndex);
397 }
398
Hal Finkel7529c552014-09-02 21:43:13 +0000399 void noteAttributes(const T &Main, const StratifiedAttrs &NewAttrs) {
400 assert(has(Main));
401 auto *Info = *get(Main);
402 auto &Link = linksAt(Info->Index);
403 Link.setAttrs(NewAttrs);
404 }
405
Hal Finkel7529c552014-09-02 21:43:13 +0000406private:
407 DenseMap<T, StratifiedInfo> Values;
408 std::vector<BuilderLink> Links;
409
George Burgess IVcae581d2016-04-13 23:27:37 +0000410 /// Adds the given element at the given index, merging sets if necessary.
Hal Finkel7529c552014-09-02 21:43:13 +0000411 bool addAtMerging(const T &ToAdd, StratifiedIndex Index) {
412 StratifiedInfo Info = {Index};
Hal Finkel8d1590d2014-09-02 22:52:30 +0000413 auto Pair = Values.insert(std::make_pair(ToAdd, Info));
Hal Finkel7529c552014-09-02 21:43:13 +0000414 if (Pair.second)
415 return true;
416
417 auto &Iter = Pair.first;
418 auto &IterSet = linksAt(Iter->second.Index);
419 auto &ReqSet = linksAt(Index);
420
421 // Failed to add where we wanted to. Merge the sets.
422 if (&IterSet != &ReqSet)
423 merge(IterSet.Number, ReqSet.Number);
424
425 return false;
426 }
427
George Burgess IVcae581d2016-04-13 23:27:37 +0000428 /// Gets the BuilderLink at the given index, taking set remapping into
429 /// account.
Hal Finkel7529c552014-09-02 21:43:13 +0000430 BuilderLink &linksAt(StratifiedIndex Index) {
431 auto *Start = &Links[Index];
432 if (!Start->isRemapped())
433 return *Start;
434
435 auto *Current = Start;
436 while (Current->isRemapped())
437 Current = &Links[Current->getRemapIndex()];
438
439 auto NewRemap = Current->Number;
440
441 // Run through everything that has yet to be updated, and update them to
442 // remap to NewRemap
443 Current = Start;
444 while (Current->isRemapped()) {
445 auto *Next = &Links[Current->getRemapIndex()];
446 Current->updateRemap(NewRemap);
447 Current = Next;
448 }
449
450 return *Current;
451 }
452
George Burgess IVcae581d2016-04-13 23:27:37 +0000453 /// \brief Merges two sets into one another. Assumes that these sets are not
454 /// already one in the same.
Hal Finkel7529c552014-09-02 21:43:13 +0000455 void merge(StratifiedIndex Idx1, StratifiedIndex Idx2) {
456 assert(inbounds(Idx1) && inbounds(Idx2));
457 assert(&linksAt(Idx1) != &linksAt(Idx2) &&
458 "Merging a set into itself is not allowed");
459
460 // CASE 1: If the set at `Idx1` is above or below `Idx2`, we need to merge
461 // both the
462 // given sets, and all sets between them, into one.
463 if (tryMergeUpwards(Idx1, Idx2))
464 return;
465
466 if (tryMergeUpwards(Idx2, Idx1))
467 return;
468
469 // CASE 2: The set at `Idx1` is not in the same chain as the set at `Idx2`.
470 // We therefore need to merge the two chains together.
471 mergeDirect(Idx1, Idx2);
472 }
473
George Burgess IVcae581d2016-04-13 23:27:37 +0000474 /// \brief Merges two sets assuming that the set at `Idx1` is unreachable from
475 /// traversing above or below the set at `Idx2`.
Hal Finkel7529c552014-09-02 21:43:13 +0000476 void mergeDirect(StratifiedIndex Idx1, StratifiedIndex Idx2) {
477 assert(inbounds(Idx1) && inbounds(Idx2));
478
479 auto *LinksInto = &linksAt(Idx1);
480 auto *LinksFrom = &linksAt(Idx2);
481 // Merging everything above LinksInto then proceeding to merge everything
482 // below LinksInto becomes problematic, so we go as far "up" as possible!
483 while (LinksInto->hasAbove() && LinksFrom->hasAbove()) {
484 LinksInto = &linksAt(LinksInto->getAbove());
485 LinksFrom = &linksAt(LinksFrom->getAbove());
486 }
487
488 if (LinksFrom->hasAbove()) {
489 LinksInto->setAbove(LinksFrom->getAbove());
490 auto &NewAbove = linksAt(LinksInto->getAbove());
491 NewAbove.setBelow(LinksInto->Number);
492 }
493
494 // Merging strategy:
495 // > If neither has links below, stop.
496 // > If only `LinksInto` has links below, stop.
497 // > If only `LinksFrom` has links below, reset `LinksInto.Below` to
498 // match `LinksFrom.Below`
499 // > If both have links above, deal with those next.
500 while (LinksInto->hasBelow() && LinksFrom->hasBelow()) {
501 auto &FromAttrs = LinksFrom->getAttrs();
502 LinksInto->setAttrs(FromAttrs);
503
504 // Remap needs to happen after getBelow(), but before
505 // assignment of LinksFrom
506 auto *NewLinksFrom = &linksAt(LinksFrom->getBelow());
507 LinksFrom->remapTo(LinksInto->Number);
508 LinksFrom = NewLinksFrom;
509 LinksInto = &linksAt(LinksInto->getBelow());
510 }
511
512 if (LinksFrom->hasBelow()) {
513 LinksInto->setBelow(LinksFrom->getBelow());
514 auto &NewBelow = linksAt(LinksInto->getBelow());
515 NewBelow.setAbove(LinksInto->Number);
516 }
517
518 LinksFrom->remapTo(LinksInto->Number);
519 }
520
George Burgess IVcae581d2016-04-13 23:27:37 +0000521 /// Checks to see if lowerIndex is at a level lower than upperIndex. If so, it
522 /// will merge lowerIndex with upperIndex (and all of the sets between) and
523 /// return true. Otherwise, it will return false.
Hal Finkel7529c552014-09-02 21:43:13 +0000524 bool tryMergeUpwards(StratifiedIndex LowerIndex, StratifiedIndex UpperIndex) {
525 assert(inbounds(LowerIndex) && inbounds(UpperIndex));
526 auto *Lower = &linksAt(LowerIndex);
527 auto *Upper = &linksAt(UpperIndex);
528 if (Lower == Upper)
529 return true;
530
531 SmallVector<BuilderLink *, 8> Found;
532 auto *Current = Lower;
533 auto Attrs = Current->getAttrs();
534 while (Current->hasAbove() && Current != Upper) {
535 Found.push_back(Current);
536 Attrs |= Current->getAttrs();
537 Current = &linksAt(Current->getAbove());
538 }
539
540 if (Current != Upper)
541 return false;
542
543 Upper->setAttrs(Attrs);
544
545 if (Lower->hasBelow()) {
546 auto NewBelowIndex = Lower->getBelow();
547 Upper->setBelow(NewBelowIndex);
548 auto &NewBelow = linksAt(NewBelowIndex);
549 NewBelow.setAbove(UpperIndex);
550 } else {
551 Upper->clearBelow();
552 }
553
554 for (const auto &Ptr : Found)
555 Ptr->remapTo(Upper->Number);
556
557 return true;
558 }
559
560 Optional<const StratifiedInfo *> get(const T &Val) const {
561 auto Result = Values.find(Val);
562 if (Result == Values.end())
George Burgess IVcae581d2016-04-13 23:27:37 +0000563 return None;
Hal Finkel7529c552014-09-02 21:43:13 +0000564 return &Result->second;
565 }
566
567 Optional<StratifiedInfo *> get(const T &Val) {
568 auto Result = Values.find(Val);
569 if (Result == Values.end())
George Burgess IVcae581d2016-04-13 23:27:37 +0000570 return None;
Hal Finkel7529c552014-09-02 21:43:13 +0000571 return &Result->second;
572 }
573
574 Optional<StratifiedIndex> indexOf(const T &Val) {
575 auto MaybeVal = get(Val);
576 if (!MaybeVal.hasValue())
George Burgess IVcae581d2016-04-13 23:27:37 +0000577 return None;
Hal Finkel7529c552014-09-02 21:43:13 +0000578 auto *Info = *MaybeVal;
579 auto &Link = linksAt(Info->Index);
580 return Link.Number;
581 }
582
583 StratifiedIndex addLinkBelow(StratifiedIndex Set) {
584 auto At = addLinks();
585 Links[Set].setBelow(At);
586 Links[At].setAbove(Set);
587 return At;
588 }
589
590 StratifiedIndex addLinkAbove(StratifiedIndex Set) {
591 auto At = addLinks();
592 Links[At].setBelow(Set);
593 Links[Set].setAbove(At);
594 return At;
595 }
596
597 StratifiedIndex getNewUnlinkedIndex() { return addLinks(); }
598
599 StratifiedIndex addLinks() {
600 auto Link = Links.size();
601 Links.push_back(BuilderLink(Link));
602 return Link;
603 }
604
Hal Finkel42b7e012014-09-02 22:36:58 +0000605 bool inbounds(StratifiedIndex N) const { return N < Links.size(); }
Hal Finkel7529c552014-09-02 21:43:13 +0000606};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000607}
Hal Finkel7529c552014-09-02 21:43:13 +0000608#endif // LLVM_ADT_STRATIFIEDSETS_H