blob: d6873141fe4c7830101988b870bdcb3ee15985b0 [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
George Burgess IVe1919962016-07-06 00:47:21 +000013#include "AliasAnalysisSummary.h"
Hal Finkel7529c552014-09-02 21:43:13 +000014#include "llvm/ADT/DenseMap.h"
15#include "llvm/ADT/Optional.h"
Hal Finkel7529c552014-09-02 21:43:13 +000016#include "llvm/ADT/SmallSet.h"
17#include "llvm/ADT/SmallVector.h"
18#include <bitset>
19#include <cassert>
20#include <cmath>
Hal Finkel7529c552014-09-02 21:43:13 +000021#include <type_traits>
Hal Finkel8d1590d2014-09-02 22:52:30 +000022#include <utility>
Hal Finkel7529c552014-09-02 21:43:13 +000023#include <vector>
24
25namespace llvm {
George Burgess IV1ca8aff2016-07-06 00:36:12 +000026namespace cflaa {
George Burgess IVcae581d2016-04-13 23:27:37 +000027/// An index into Stratified Sets.
Hal Finkel7529c552014-09-02 21:43:13 +000028typedef unsigned StratifiedIndex;
George Burgess IVcae581d2016-04-13 23:27:37 +000029/// NOTE: ^ This can't be a short -- bootstrapping clang has a case where
30/// ~1M sets exist.
Hal Finkel7529c552014-09-02 21:43:13 +000031
32// \brief Container of information related to a value in a StratifiedSet.
33struct StratifiedInfo {
34 StratifiedIndex Index;
George Burgess IVcae581d2016-04-13 23:27:37 +000035 /// For field sensitivity, etc. we can tack fields on here.
Hal Finkel7529c552014-09-02 21:43:13 +000036};
37
George Burgess IVcae581d2016-04-13 23:27:37 +000038/// A "link" between two StratifiedSets.
Hal Finkel7529c552014-09-02 21:43:13 +000039struct StratifiedLink {
George Burgess IVcae581d2016-04-13 23:27:37 +000040 /// \brief This is a value used to signify "does not exist" where the
41 /// StratifiedIndex type is used.
42 ///
43 /// This is used instead of Optional<StratifiedIndex> because
44 /// Optional<StratifiedIndex> would eat up a considerable amount of extra
45 /// memory, after struct padding/alignment is taken into account.
Hal Finkel1ae325f2014-09-02 23:50:01 +000046 static const StratifiedIndex SetSentinel;
Hal Finkel7529c552014-09-02 21:43:13 +000047
George Burgess IVcae581d2016-04-13 23:27:37 +000048 /// The index for the set "above" current
Hal Finkel7529c552014-09-02 21:43:13 +000049 StratifiedIndex Above;
50
George Burgess IVcae581d2016-04-13 23:27:37 +000051 /// The link for the set "below" current
Hal Finkel7529c552014-09-02 21:43:13 +000052 StratifiedIndex Below;
53
George Burgess IVcae581d2016-04-13 23:27:37 +000054 /// Attributes for these StratifiedSets.
George Burgess IVe1919962016-07-06 00:47:21 +000055 AliasAttrs Attrs;
Hal Finkel7529c552014-09-02 21:43:13 +000056
57 StratifiedLink() : Above(SetSentinel), Below(SetSentinel) {}
58
59 bool hasBelow() const { return Below != SetSentinel; }
60 bool hasAbove() const { return Above != SetSentinel; }
61
62 void clearBelow() { Below = SetSentinel; }
63 void clearAbove() { Above = SetSentinel; }
64};
65
George Burgess IVcae581d2016-04-13 23:27:37 +000066/// \brief These are stratified sets, as described in "Fast algorithms for
67/// Dyck-CFL-reachability with applications to Alias Analysis" by Zhang Q, Lyu M
68/// R, Yuan H, and Su Z. -- in short, this is meant to represent different sets
69/// of Value*s. If two Value*s are in the same set, or if both sets have
70/// overlapping attributes, then the Value*s are said to alias.
71///
72/// Sets may be related by position, meaning that one set may be considered as
73/// above or below another. In CFL Alias Analysis, this gives us an indication
74/// of how two variables are related; if the set of variable A is below a set
75/// containing variable B, then at some point, a variable that has interacted
76/// with B (or B itself) was either used in order to extract the variable A, or
77/// was used as storage of variable A.
78///
79/// Sets may also have attributes (as noted above). These attributes are
80/// generally used for noting whether a variable in the set has interacted with
81/// a variable whose origins we don't quite know (i.e. globals/arguments), or if
82/// the variable may have had operations performed on it (modified in a function
83/// call). All attributes that exist in a set A must exist in all sets marked as
84/// below set A.
Hal Finkel7529c552014-09-02 21:43:13 +000085template <typename T> class StratifiedSets {
86public:
George Burgess IV60af2262016-06-07 21:41:18 +000087 StratifiedSets() = default;
George Burgess IVfd4e2f72016-06-08 17:56:35 +000088
89 // TODO: Figure out how to make MSVC not call the copy ctor here, and delete
90 // it.
George Burgess IV785f3912016-06-08 17:27:14 +000091
92 // Can't default these due to compile errors in MSVC2013
93 StratifiedSets(StratifiedSets &&Other) { *this = std::move(Other); }
94 StratifiedSets &operator=(StratifiedSets &&Other) {
95 Values = std::move(Other.Values);
96 Links = std::move(Other.Links);
97 return *this;
98 }
Hal Finkel7529c552014-09-02 21:43:13 +000099
100 StratifiedSets(DenseMap<T, StratifiedInfo> Map,
101 std::vector<StratifiedLink> Links)
102 : Values(std::move(Map)), Links(std::move(Links)) {}
103
Hal Finkel7529c552014-09-02 21:43:13 +0000104 Optional<StratifiedInfo> find(const T &Elem) const {
105 auto Iter = Values.find(Elem);
George Burgess IVcae581d2016-04-13 23:27:37 +0000106 if (Iter == Values.end())
107 return None;
Hal Finkel7529c552014-09-02 21:43:13 +0000108 return Iter->second;
109 }
110
111 const StratifiedLink &getLink(StratifiedIndex Index) const {
112 assert(inbounds(Index));
113 return Links[Index];
114 }
115
116private:
117 DenseMap<T, StratifiedInfo> Values;
118 std::vector<StratifiedLink> Links;
119
120 bool inbounds(StratifiedIndex Idx) const { return Idx < Links.size(); }
121};
122
George Burgess IVcae581d2016-04-13 23:27:37 +0000123/// Generic Builder class that produces StratifiedSets instances.
124///
125/// The goal of this builder is to efficiently produce correct StratifiedSets
126/// instances. To this end, we use a few tricks:
127/// > Set chains (A method for linking sets together)
128/// > Set remaps (A method for marking a set as an alias [irony?] of another)
129///
130/// ==== Set chains ====
131/// This builder has a notion of some value A being above, below, or with some
132/// other value B:
133/// > The `A above B` relationship implies that there is a reference edge
134/// going from A to B. Namely, it notes that A can store anything in B's set.
135/// > The `A below B` relationship is the opposite of `A above B`. It implies
136/// that there's a dereference edge going from A to B.
137/// > The `A with B` relationship states that there's an assignment edge going
138/// from A to B, and that A and B should be treated as equals.
139///
140/// As an example, take the following code snippet:
141///
142/// %a = alloca i32, align 4
143/// %ap = alloca i32*, align 8
144/// %app = alloca i32**, align 8
145/// store %a, %ap
146/// store %ap, %app
George Burgess IV60af2262016-06-07 21:41:18 +0000147/// %aw = getelementptr %ap, i32 0
George Burgess IVcae581d2016-04-13 23:27:37 +0000148///
George Burgess IV60af2262016-06-07 21:41:18 +0000149/// Given this, the following relations exist:
George Burgess IVcae581d2016-04-13 23:27:37 +0000150/// - %a below %ap & %ap above %a
151/// - %ap below %app & %app above %ap
152/// - %aw with %ap & %ap with %aw
153///
154/// These relations produce the following sets:
155/// [{%a}, {%ap, %aw}, {%app}]
156///
George Burgess IV60af2262016-06-07 21:41:18 +0000157/// ...Which state that the only MayAlias relationship in the above program is
George Burgess IVcae581d2016-04-13 23:27:37 +0000158/// between %ap and %aw.
159///
George Burgess IV60af2262016-06-07 21:41:18 +0000160/// Because LLVM allows arbitrary casts, code like the following needs to be
161/// supported:
162/// %ip = alloca i64, align 8
163/// %ipp = alloca i64*, align 8
164/// %i = bitcast i64** ipp to i64
165/// store i64* %ip, i64** %ipp
166/// store i64 %i, i64* %ip
George Burgess IVcae581d2016-04-13 23:27:37 +0000167///
George Burgess IV60af2262016-06-07 21:41:18 +0000168/// Which, because %ipp ends up *both* above and below %ip, is fun.
George Burgess IVcae581d2016-04-13 23:27:37 +0000169///
George Burgess IV60af2262016-06-07 21:41:18 +0000170/// This is solved by merging %i and %ipp into a single set (...which is the
171/// only way to solve this, since their bit patterns are equivalent). Any sets
172/// that ended up in between %i and %ipp at the time of merging (in this case,
173/// the set containing %ip) also get conservatively merged into the set of %i
174/// and %ipp. In short, the resulting StratifiedSet from the above code would be
175/// {%ip, %ipp, %i}.
George Burgess IVcae581d2016-04-13 23:27:37 +0000176///
177/// ==== Set remaps ====
178/// More of an implementation detail than anything -- when merging sets, we need
179/// to update the numbers of all of the elements mapped to those sets. Rather
180/// than doing this at each merge, we note in the BuilderLink structure that a
181/// remap has occurred, and use this information so we can defer renumbering set
182/// elements until build time.
Hal Finkel7529c552014-09-02 21:43:13 +0000183template <typename T> class StratifiedSetsBuilder {
George Burgess IVcae581d2016-04-13 23:27:37 +0000184 /// \brief Represents a Stratified Set, with information about the Stratified
185 /// Set above it, the set below it, and whether the current set has been
186 /// remapped to another.
Hal Finkel7529c552014-09-02 21:43:13 +0000187 struct BuilderLink {
188 const StratifiedIndex Number;
189
190 BuilderLink(StratifiedIndex N) : Number(N) {
191 Remap = StratifiedLink::SetSentinel;
192 }
193
194 bool hasAbove() const {
195 assert(!isRemapped());
196 return Link.hasAbove();
197 }
198
199 bool hasBelow() const {
200 assert(!isRemapped());
201 return Link.hasBelow();
202 }
203
204 void setBelow(StratifiedIndex I) {
205 assert(!isRemapped());
206 Link.Below = I;
207 }
208
209 void setAbove(StratifiedIndex I) {
210 assert(!isRemapped());
211 Link.Above = I;
212 }
213
214 void clearBelow() {
215 assert(!isRemapped());
216 Link.clearBelow();
217 }
218
219 void clearAbove() {
220 assert(!isRemapped());
221 Link.clearAbove();
222 }
223
224 StratifiedIndex getBelow() const {
225 assert(!isRemapped());
226 assert(hasBelow());
227 return Link.Below;
228 }
229
230 StratifiedIndex getAbove() const {
231 assert(!isRemapped());
232 assert(hasAbove());
233 return Link.Above;
234 }
235
George Burgess IVe1919962016-07-06 00:47:21 +0000236 AliasAttrs getAttrs() {
Hal Finkel7529c552014-09-02 21:43:13 +0000237 assert(!isRemapped());
238 return Link.Attrs;
239 }
240
George Burgess IVe1919962016-07-06 00:47:21 +0000241 void setAttrs(AliasAttrs Other) {
Hal Finkel7529c552014-09-02 21:43:13 +0000242 assert(!isRemapped());
George Burgess IVe1919962016-07-06 00:47:21 +0000243 Link.Attrs |= Other;
Hal Finkel7529c552014-09-02 21:43:13 +0000244 }
245
246 bool isRemapped() const { return Remap != StratifiedLink::SetSentinel; }
247
George Burgess IVcae581d2016-04-13 23:27:37 +0000248 /// For initial remapping to another set
Hal Finkel7529c552014-09-02 21:43:13 +0000249 void remapTo(StratifiedIndex Other) {
250 assert(!isRemapped());
251 Remap = Other;
252 }
253
254 StratifiedIndex getRemapIndex() const {
255 assert(isRemapped());
256 return Remap;
257 }
258
George Burgess IVcae581d2016-04-13 23:27:37 +0000259 /// Should only be called when we're already remapped.
Hal Finkel7529c552014-09-02 21:43:13 +0000260 void updateRemap(StratifiedIndex Other) {
261 assert(isRemapped());
262 Remap = Other;
263 }
264
George Burgess IVcae581d2016-04-13 23:27:37 +0000265 /// Prefer the above functions to calling things directly on what's returned
266 /// from this -- they guard against unexpected calls when the current
267 /// BuilderLink is remapped.
Hal Finkel7529c552014-09-02 21:43:13 +0000268 const StratifiedLink &getLink() const { return Link; }
269
270 private:
271 StratifiedLink Link;
272 StratifiedIndex Remap;
273 };
274
George Burgess IVcae581d2016-04-13 23:27:37 +0000275 /// \brief This function performs all of the set unioning/value renumbering
276 /// that we've been putting off, and generates a vector<StratifiedLink> that
277 /// may be placed in a StratifiedSets instance.
Hal Finkel7529c552014-09-02 21:43:13 +0000278 void finalizeSets(std::vector<StratifiedLink> &StratLinks) {
279 DenseMap<StratifiedIndex, StratifiedIndex> Remaps;
280 for (auto &Link : Links) {
George Burgess IVcae581d2016-04-13 23:27:37 +0000281 if (Link.isRemapped())
Hal Finkel7529c552014-09-02 21:43:13 +0000282 continue;
Hal Finkel7529c552014-09-02 21:43:13 +0000283
284 StratifiedIndex Number = StratLinks.size();
Hal Finkel8d1590d2014-09-02 22:52:30 +0000285 Remaps.insert(std::make_pair(Link.Number, Number));
Hal Finkel7529c552014-09-02 21:43:13 +0000286 StratLinks.push_back(Link.getLink());
287 }
288
289 for (auto &Link : StratLinks) {
290 if (Link.hasAbove()) {
291 auto &Above = linksAt(Link.Above);
292 auto Iter = Remaps.find(Above.Number);
293 assert(Iter != Remaps.end());
294 Link.Above = Iter->second;
295 }
296
297 if (Link.hasBelow()) {
298 auto &Below = linksAt(Link.Below);
299 auto Iter = Remaps.find(Below.Number);
300 assert(Iter != Remaps.end());
301 Link.Below = Iter->second;
302 }
303 }
304
305 for (auto &Pair : Values) {
306 auto &Info = Pair.second;
307 auto &Link = linksAt(Info.Index);
308 auto Iter = Remaps.find(Link.Number);
309 assert(Iter != Remaps.end());
310 Info.Index = Iter->second;
311 }
312 }
313
George Burgess IVcae581d2016-04-13 23:27:37 +0000314 /// \brief There's a guarantee in StratifiedLink where all bits set in a
315 /// Link.externals will be set in all Link.externals "below" it.
Hal Finkel7529c552014-09-02 21:43:13 +0000316 static void propagateAttrs(std::vector<StratifiedLink> &Links) {
317 const auto getHighestParentAbove = [&Links](StratifiedIndex Idx) {
318 const auto *Link = &Links[Idx];
319 while (Link->hasAbove()) {
320 Idx = Link->Above;
321 Link = &Links[Idx];
322 }
323 return Idx;
324 };
325
326 SmallSet<StratifiedIndex, 16> Visited;
327 for (unsigned I = 0, E = Links.size(); I < E; ++I) {
328 auto CurrentIndex = getHighestParentAbove(I);
George Burgess IVcae581d2016-04-13 23:27:37 +0000329 if (!Visited.insert(CurrentIndex).second)
Hal Finkel7529c552014-09-02 21:43:13 +0000330 continue;
Hal Finkel7529c552014-09-02 21:43:13 +0000331
332 while (Links[CurrentIndex].hasBelow()) {
333 auto &CurrentBits = Links[CurrentIndex].Attrs;
334 auto NextIndex = Links[CurrentIndex].Below;
335 auto &NextBits = Links[NextIndex].Attrs;
336 NextBits |= CurrentBits;
337 CurrentIndex = NextIndex;
338 }
339 }
340 }
341
342public:
George Burgess IVcae581d2016-04-13 23:27:37 +0000343 /// Builds a StratifiedSet from the information we've been given since either
344 /// construction or the prior build() call.
Hal Finkel7529c552014-09-02 21:43:13 +0000345 StratifiedSets<T> build() {
346 std::vector<StratifiedLink> StratLinks;
347 finalizeSets(StratLinks);
348 propagateAttrs(StratLinks);
349 Links.clear();
350 return StratifiedSets<T>(std::move(Values), std::move(StratLinks));
351 }
352
Hal Finkel7529c552014-09-02 21:43:13 +0000353 bool has(const T &Elem) const { return get(Elem).hasValue(); }
354
355 bool add(const T &Main) {
356 if (get(Main).hasValue())
357 return false;
358
359 auto NewIndex = getNewUnlinkedIndex();
360 return addAtMerging(Main, NewIndex);
361 }
362
George Burgess IVcae581d2016-04-13 23:27:37 +0000363 /// \brief Restructures the stratified sets as necessary to make "ToAdd" in a
364 /// set above "Main". There are some cases where this is not possible (see
365 /// above), so we merge them such that ToAdd and Main are in the same set.
Hal Finkel7529c552014-09-02 21:43:13 +0000366 bool addAbove(const T &Main, const T &ToAdd) {
367 assert(has(Main));
368 auto Index = *indexOf(Main);
369 if (!linksAt(Index).hasAbove())
370 addLinkAbove(Index);
371
372 auto Above = linksAt(Index).getAbove();
373 return addAtMerging(ToAdd, Above);
374 }
375
George Burgess IVcae581d2016-04-13 23:27:37 +0000376 /// \brief Restructures the stratified sets as necessary to make "ToAdd" in a
377 /// set below "Main". There are some cases where this is not possible (see
378 /// above), so we merge them such that ToAdd and Main are in the same set.
Hal Finkel7529c552014-09-02 21:43:13 +0000379 bool addBelow(const T &Main, const T &ToAdd) {
380 assert(has(Main));
381 auto Index = *indexOf(Main);
382 if (!linksAt(Index).hasBelow())
383 addLinkBelow(Index);
384
385 auto Below = linksAt(Index).getBelow();
386 return addAtMerging(ToAdd, Below);
387 }
388
George Burgess IVe1919962016-07-06 00:47:21 +0000389 /// \brief Set the AliasAttrs of the set "Level"-levels below "Main". If
George Burgess IVa3d62be2016-06-24 01:00:03 +0000390 /// there is no set below "Main", create one for it.
George Burgess IVe1919962016-07-06 00:47:21 +0000391 void addAttributesBelow(const T &Main, unsigned Level, AliasAttrs Attr) {
George Burgess IV652ec4f2016-06-09 23:15:04 +0000392 assert(has(Main));
393 auto Index = *indexOf(Main);
George Burgess IVa3d62be2016-06-24 01:00:03 +0000394 auto *Link = &linksAt(Index);
George Burgess IV652ec4f2016-06-09 23:15:04 +0000395
George Burgess IVa3d62be2016-06-24 01:00:03 +0000396 for (unsigned I = 0; I < Level; ++I) {
397 Index = Link->hasBelow() ? Link->getBelow() : addLinkBelow(Index);
398 Link = &linksAt(Index);
399 }
400 Link->setAttrs(Attr);
George Burgess IV652ec4f2016-06-09 23:15:04 +0000401 }
402
Hal Finkel7529c552014-09-02 21:43:13 +0000403 bool addWith(const T &Main, const T &ToAdd) {
404 assert(has(Main));
405 auto MainIndex = *indexOf(Main);
406 return addAtMerging(ToAdd, MainIndex);
407 }
408
George Burgess IV1f99da52016-06-23 18:55:23 +0000409 /// \brief Merge the set "MainBelow"-levels below "Main" and the set
410 /// "ToAddBelow"-levels below "ToAdd".
411 void addBelowWith(const T &Main, unsigned MainBelow, const T &ToAdd,
412 unsigned ToAddBelow) {
413 assert(has(Main));
414 assert(has(ToAdd));
415
George Burgess IVd14d05a2016-06-23 20:59:13 +0000416 auto GetIndexBelow = [&](StratifiedIndex Index, unsigned NumLevel) {
George Burgess IV1f99da52016-06-23 18:55:23 +0000417 for (unsigned I = 0; I < NumLevel; ++I) {
418 auto Link = linksAt(Index);
419 Index = Link.hasBelow() ? Link.getBelow() : addLinkBelow(Index);
420 }
421 return Index;
422 };
423 auto MainIndex = GetIndexBelow(*indexOf(Main), MainBelow);
424 auto ToAddIndex = GetIndexBelow(*indexOf(ToAdd), ToAddBelow);
425 if (&linksAt(MainIndex) != &linksAt(ToAddIndex))
426 merge(MainIndex, ToAddIndex);
427 }
428
George Burgess IVe1919962016-07-06 00:47:21 +0000429 void noteAttributes(const T &Main, AliasAttrs NewAttrs) {
Hal Finkel7529c552014-09-02 21:43:13 +0000430 assert(has(Main));
431 auto *Info = *get(Main);
432 auto &Link = linksAt(Info->Index);
433 Link.setAttrs(NewAttrs);
434 }
435
Hal Finkel7529c552014-09-02 21:43:13 +0000436private:
437 DenseMap<T, StratifiedInfo> Values;
438 std::vector<BuilderLink> Links;
439
George Burgess IVcae581d2016-04-13 23:27:37 +0000440 /// Adds the given element at the given index, merging sets if necessary.
Hal Finkel7529c552014-09-02 21:43:13 +0000441 bool addAtMerging(const T &ToAdd, StratifiedIndex Index) {
442 StratifiedInfo Info = {Index};
Hal Finkel8d1590d2014-09-02 22:52:30 +0000443 auto Pair = Values.insert(std::make_pair(ToAdd, Info));
Hal Finkel7529c552014-09-02 21:43:13 +0000444 if (Pair.second)
445 return true;
446
447 auto &Iter = Pair.first;
448 auto &IterSet = linksAt(Iter->second.Index);
449 auto &ReqSet = linksAt(Index);
450
451 // Failed to add where we wanted to. Merge the sets.
452 if (&IterSet != &ReqSet)
453 merge(IterSet.Number, ReqSet.Number);
454
455 return false;
456 }
457
George Burgess IVcae581d2016-04-13 23:27:37 +0000458 /// Gets the BuilderLink at the given index, taking set remapping into
459 /// account.
Hal Finkel7529c552014-09-02 21:43:13 +0000460 BuilderLink &linksAt(StratifiedIndex Index) {
461 auto *Start = &Links[Index];
462 if (!Start->isRemapped())
463 return *Start;
464
465 auto *Current = Start;
466 while (Current->isRemapped())
467 Current = &Links[Current->getRemapIndex()];
468
469 auto NewRemap = Current->Number;
470
471 // Run through everything that has yet to be updated, and update them to
472 // remap to NewRemap
473 Current = Start;
474 while (Current->isRemapped()) {
475 auto *Next = &Links[Current->getRemapIndex()];
476 Current->updateRemap(NewRemap);
477 Current = Next;
478 }
479
480 return *Current;
481 }
482
George Burgess IVcae581d2016-04-13 23:27:37 +0000483 /// \brief Merges two sets into one another. Assumes that these sets are not
484 /// already one in the same.
Hal Finkel7529c552014-09-02 21:43:13 +0000485 void merge(StratifiedIndex Idx1, StratifiedIndex Idx2) {
486 assert(inbounds(Idx1) && inbounds(Idx2));
487 assert(&linksAt(Idx1) != &linksAt(Idx2) &&
488 "Merging a set into itself is not allowed");
489
490 // CASE 1: If the set at `Idx1` is above or below `Idx2`, we need to merge
491 // both the
492 // given sets, and all sets between them, into one.
493 if (tryMergeUpwards(Idx1, Idx2))
494 return;
495
496 if (tryMergeUpwards(Idx2, Idx1))
497 return;
498
499 // CASE 2: The set at `Idx1` is not in the same chain as the set at `Idx2`.
500 // We therefore need to merge the two chains together.
501 mergeDirect(Idx1, Idx2);
502 }
503
George Burgess IVcae581d2016-04-13 23:27:37 +0000504 /// \brief Merges two sets assuming that the set at `Idx1` is unreachable from
505 /// traversing above or below the set at `Idx2`.
Hal Finkel7529c552014-09-02 21:43:13 +0000506 void mergeDirect(StratifiedIndex Idx1, StratifiedIndex Idx2) {
507 assert(inbounds(Idx1) && inbounds(Idx2));
508
509 auto *LinksInto = &linksAt(Idx1);
510 auto *LinksFrom = &linksAt(Idx2);
511 // Merging everything above LinksInto then proceeding to merge everything
512 // below LinksInto becomes problematic, so we go as far "up" as possible!
513 while (LinksInto->hasAbove() && LinksFrom->hasAbove()) {
514 LinksInto = &linksAt(LinksInto->getAbove());
515 LinksFrom = &linksAt(LinksFrom->getAbove());
516 }
517
518 if (LinksFrom->hasAbove()) {
519 LinksInto->setAbove(LinksFrom->getAbove());
520 auto &NewAbove = linksAt(LinksInto->getAbove());
521 NewAbove.setBelow(LinksInto->Number);
522 }
523
524 // Merging strategy:
525 // > If neither has links below, stop.
526 // > If only `LinksInto` has links below, stop.
527 // > If only `LinksFrom` has links below, reset `LinksInto.Below` to
528 // match `LinksFrom.Below`
529 // > If both have links above, deal with those next.
530 while (LinksInto->hasBelow() && LinksFrom->hasBelow()) {
George Burgess IVe1919962016-07-06 00:47:21 +0000531 auto FromAttrs = LinksFrom->getAttrs();
Hal Finkel7529c552014-09-02 21:43:13 +0000532 LinksInto->setAttrs(FromAttrs);
533
534 // Remap needs to happen after getBelow(), but before
535 // assignment of LinksFrom
536 auto *NewLinksFrom = &linksAt(LinksFrom->getBelow());
537 LinksFrom->remapTo(LinksInto->Number);
538 LinksFrom = NewLinksFrom;
539 LinksInto = &linksAt(LinksInto->getBelow());
540 }
541
542 if (LinksFrom->hasBelow()) {
543 LinksInto->setBelow(LinksFrom->getBelow());
544 auto &NewBelow = linksAt(LinksInto->getBelow());
545 NewBelow.setAbove(LinksInto->Number);
546 }
547
548 LinksFrom->remapTo(LinksInto->Number);
549 }
550
George Burgess IVcae581d2016-04-13 23:27:37 +0000551 /// Checks to see if lowerIndex is at a level lower than upperIndex. If so, it
552 /// will merge lowerIndex with upperIndex (and all of the sets between) and
553 /// return true. Otherwise, it will return false.
Hal Finkel7529c552014-09-02 21:43:13 +0000554 bool tryMergeUpwards(StratifiedIndex LowerIndex, StratifiedIndex UpperIndex) {
555 assert(inbounds(LowerIndex) && inbounds(UpperIndex));
556 auto *Lower = &linksAt(LowerIndex);
557 auto *Upper = &linksAt(UpperIndex);
558 if (Lower == Upper)
559 return true;
560
561 SmallVector<BuilderLink *, 8> Found;
562 auto *Current = Lower;
563 auto Attrs = Current->getAttrs();
564 while (Current->hasAbove() && Current != Upper) {
565 Found.push_back(Current);
566 Attrs |= Current->getAttrs();
567 Current = &linksAt(Current->getAbove());
568 }
569
570 if (Current != Upper)
571 return false;
572
573 Upper->setAttrs(Attrs);
574
575 if (Lower->hasBelow()) {
576 auto NewBelowIndex = Lower->getBelow();
577 Upper->setBelow(NewBelowIndex);
578 auto &NewBelow = linksAt(NewBelowIndex);
579 NewBelow.setAbove(UpperIndex);
580 } else {
581 Upper->clearBelow();
582 }
583
584 for (const auto &Ptr : Found)
585 Ptr->remapTo(Upper->Number);
586
587 return true;
588 }
589
590 Optional<const StratifiedInfo *> get(const T &Val) const {
591 auto Result = Values.find(Val);
592 if (Result == Values.end())
George Burgess IVcae581d2016-04-13 23:27:37 +0000593 return None;
Hal Finkel7529c552014-09-02 21:43:13 +0000594 return &Result->second;
595 }
596
597 Optional<StratifiedInfo *> get(const T &Val) {
598 auto Result = Values.find(Val);
599 if (Result == Values.end())
George Burgess IVcae581d2016-04-13 23:27:37 +0000600 return None;
Hal Finkel7529c552014-09-02 21:43:13 +0000601 return &Result->second;
602 }
603
604 Optional<StratifiedIndex> indexOf(const T &Val) {
605 auto MaybeVal = get(Val);
606 if (!MaybeVal.hasValue())
George Burgess IVcae581d2016-04-13 23:27:37 +0000607 return None;
Hal Finkel7529c552014-09-02 21:43:13 +0000608 auto *Info = *MaybeVal;
609 auto &Link = linksAt(Info->Index);
610 return Link.Number;
611 }
612
613 StratifiedIndex addLinkBelow(StratifiedIndex Set) {
614 auto At = addLinks();
615 Links[Set].setBelow(At);
616 Links[At].setAbove(Set);
617 return At;
618 }
619
620 StratifiedIndex addLinkAbove(StratifiedIndex Set) {
621 auto At = addLinks();
622 Links[At].setBelow(Set);
623 Links[Set].setAbove(At);
624 return At;
625 }
626
627 StratifiedIndex getNewUnlinkedIndex() { return addLinks(); }
628
629 StratifiedIndex addLinks() {
630 auto Link = Links.size();
631 Links.push_back(BuilderLink(Link));
632 return Link;
633 }
634
Hal Finkel42b7e012014-09-02 22:36:58 +0000635 bool inbounds(StratifiedIndex N) const { return N < Links.size(); }
Hal Finkel7529c552014-09-02 21:43:13 +0000636};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000637}
George Burgess IV1ca8aff2016-07-06 00:36:12 +0000638}
George Burgess IVd14d05a2016-06-23 20:59:13 +0000639#endif // LLVM_ADT_STRATIFIEDSETS_H