Coverage Report

Created: 2017-11-23 03:11

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/polly/lib/Support/ISLTools.cpp
Line
Count
Source (jump to first uncovered line)
1
//===------ ISLTools.cpp ----------------------------------------*- C++ -*-===//
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
// Tools, utilities, helpers and extensions useful in conjunction with the
11
// Integer Set Library (isl).
12
//
13
//===----------------------------------------------------------------------===//
14
15
#include "polly/Support/ISLTools.h"
16
#include "llvm/ADT/StringRef.h"
17
18
using namespace polly;
19
20
namespace {
21
/// Create a map that shifts one dimension by an offset.
22
///
23
/// Example:
24
/// makeShiftDimAff({ [i0, i1] -> [o0, o1] }, 1, -2)
25
///   = { [i0, i1] -> [i0, i1 - 1] }
26
///
27
/// @param Space  The map space of the result. Must have equal number of in- and
28
///               out-dimensions.
29
/// @param Pos    Position to shift.
30
/// @param Amount Value added to the shifted dimension.
31
///
32
/// @return An isl_multi_aff for the map with this shifted dimension.
33
931
isl::multi_aff makeShiftDimAff(isl::space Space, int Pos, int Amount) {
34
931
  auto Identity = give(isl_multi_aff_identity(Space.take()));
35
931
  if (Amount == 0)
36
0
    return Identity;
37
931
  auto ShiftAff = give(isl_multi_aff_get_aff(Identity.keep(), Pos));
38
931
  ShiftAff = give(isl_aff_set_constant_si(ShiftAff.take(), Amount));
39
931
  return give(isl_multi_aff_set_aff(Identity.take(), Pos, ShiftAff.take()));
40
931
}
41
42
/// Construct a map that swaps two nested tuples.
43
///
44
/// @param FromSpace1 { Space1[] }
45
/// @param FromSpace2 { Space2[] }
46
///
47
/// @return { [Space1[] -> Space2[]] -> [Space2[] -> Space1[]] }
48
isl::basic_map makeTupleSwapBasicMap(isl::space FromSpace1,
49
124
                                     isl::space FromSpace2) {
50
124
  assert(isl_space_is_set(FromSpace1.keep()) != isl_bool_false);
51
124
  assert(isl_space_is_set(FromSpace2.keep()) != isl_bool_false);
52
124
53
124
  auto Dims1 = isl_space_dim(FromSpace1.keep(), isl_dim_set);
54
124
  auto Dims2 = isl_space_dim(FromSpace2.keep(), isl_dim_set);
55
124
  auto FromSpace = give(isl_space_wrap(isl_space_map_from_domain_and_range(
56
124
      FromSpace1.copy(), FromSpace2.copy())));
57
124
  auto ToSpace = give(isl_space_wrap(isl_space_map_from_domain_and_range(
58
124
      FromSpace2.take(), FromSpace1.take())));
59
124
  auto MapSpace = give(
60
124
      isl_space_map_from_domain_and_range(FromSpace.take(), ToSpace.take()));
61
124
62
124
  auto Result = give(isl_basic_map_universe(MapSpace.take()));
63
186
  for (auto i = Dims1 - Dims1; i < Dims1; 
i += 162
) {
64
62
    Result = give(isl_basic_map_equate(Result.take(), isl_dim_in, i,
65
62
                                       isl_dim_out, Dims2 + i));
66
62
  }
67
333
  for (auto i = Dims2 - Dims2; i < Dims2; 
i += 1209
) {
68
209
    Result = give(isl_basic_map_equate(Result.take(), isl_dim_in, Dims1 + i,
69
209
                                       isl_dim_out, i));
70
209
  }
71
124
72
124
  return Result;
73
124
}
74
75
/// Like makeTupleSwapBasicMap(isl::space,isl::space), but returns
76
/// an isl_map.
77
124
isl::map makeTupleSwapMap(isl::space FromSpace1, isl::space FromSpace2) {
78
124
  auto BMapResult =
79
124
      makeTupleSwapBasicMap(std::move(FromSpace1), std::move(FromSpace2));
80
124
  return give(isl_map_from_basic_map(BMapResult.take()));
81
124
}
82
} // anonymous namespace
83
84
241
isl::map polly::beforeScatter(isl::map Map, bool Strict) {
85
241
  auto RangeSpace = give(isl_space_range(isl_map_get_space(Map.keep())));
86
241
  auto ScatterRel = give(Strict ? 
isl_map_lex_gt(RangeSpace.take())57
87
241
                                : 
isl_map_lex_ge(RangeSpace.take())184
);
88
241
  return give(isl_map_apply_range(Map.take(), ScatterRel.take()));
89
241
}
90
91
95
isl::union_map polly::beforeScatter(isl::union_map UMap, bool Strict) {
92
95
  auto Result = give(isl_union_map_empty(isl_union_map_get_space(UMap.keep())));
93
108
  UMap.foreach_map([=, &Result](isl::map Map) -> isl::stat {
94
108
    auto After = beforeScatter(Map, Strict);
95
108
    Result = give(isl_union_map_add_map(Result.take(), After.take()));
96
108
    return isl::stat::ok;
97
108
  });
98
95
  return Result;
99
95
}
100
101
148
isl::map polly::afterScatter(isl::map Map, bool Strict) {
102
148
  auto RangeSpace = give(isl_space_range(isl_map_get_space(Map.keep())));
103
148
  auto ScatterRel = give(Strict ? 
isl_map_lex_lt(RangeSpace.take())130
104
148
                                : 
isl_map_lex_le(RangeSpace.take())18
);
105
148
  return give(isl_map_apply_range(Map.take(), ScatterRel.take()));
106
148
}
107
108
95
isl::union_map polly::afterScatter(const isl::union_map &UMap, bool Strict) {
109
95
  auto Result = give(isl_union_map_empty(isl_union_map_get_space(UMap.keep())));
110
95
  UMap.foreach_map([=, &Result](isl::map Map) -> isl::stat {
111
54
    auto After = afterScatter(Map, Strict);
112
54
    Result = give(isl_union_map_add_map(Result.take(), After.take()));
113
54
    return isl::stat::ok;
114
54
  });
115
95
  return Result;
116
95
}
117
118
isl::map polly::betweenScatter(isl::map From, isl::map To, bool InclFrom,
119
92
                               bool InclTo) {
120
92
  auto AfterFrom = afterScatter(From, !InclFrom);
121
92
  auto BeforeTo = beforeScatter(To, !InclTo);
122
92
123
92
  return give(isl_map_intersect(AfterFrom.take(), BeforeTo.take()));
124
92
}
125
126
isl::union_map polly::betweenScatter(isl::union_map From, isl::union_map To,
127
83
                                     bool InclFrom, bool InclTo) {
128
83
  auto AfterFrom = afterScatter(From, !InclFrom);
129
83
  auto BeforeTo = beforeScatter(To, !InclTo);
130
83
131
83
  return give(isl_union_map_intersect(AfterFrom.take(), BeforeTo.take()));
132
83
}
133
134
444
isl::map polly::singleton(isl::union_map UMap, isl::space ExpectedSpace) {
135
444
  if (!UMap)
136
0
    return nullptr;
137
444
138
444
  if (isl_union_map_n_map(UMap.keep()) == 0)
139
3
    return isl::map::empty(ExpectedSpace);
140
441
141
441
  isl::map Result = isl::map::from_union_map(UMap);
142
441
  assert(!Result || Result.get_space().has_equal_tuples(ExpectedSpace));
143
441
144
441
  return Result;
145
441
}
146
147
43
isl::set polly::singleton(isl::union_set USet, isl::space ExpectedSpace) {
148
43
  if (!USet)
149
0
    return nullptr;
150
43
151
43
  if (isl_union_set_n_set(USet.keep()) == 0)
152
1
    return isl::set::empty(ExpectedSpace);
153
42
154
42
  isl::set Result(USet);
155
42
  assert(!Result || Result.get_space().has_equal_tuples(ExpectedSpace));
156
42
157
42
  return Result;
158
42
}
159
160
627
unsigned polly::getNumScatterDims(const isl::union_map &Schedule) {
161
627
  unsigned Dims = 0;
162
2.38k
  Schedule.foreach_map([&Dims](isl::map Map) -> isl::stat {
163
2.38k
    Dims = std::max(Dims, isl_map_dim(Map.keep(), isl_dim_out));
164
2.38k
    return isl::stat::ok;
165
2.38k
  });
166
627
  return Dims;
167
627
}
168
169
619
isl::space polly::getScatterSpace(const isl::union_map &Schedule) {
170
619
  if (!Schedule)
171
0
    return nullptr;
172
619
  auto Dims = getNumScatterDims(Schedule);
173
619
  auto ScatterSpace =
174
619
      give(isl_space_set_from_params(isl_union_map_get_space(Schedule.keep())));
175
619
  return give(isl_space_add_dims(ScatterSpace.take(), isl_dim_set, Dims));
176
619
}
177
178
isl::union_map polly::makeIdentityMap(const isl::union_set &USet,
179
94
                                      bool RestrictDomain) {
180
94
  auto Result = give(isl_union_map_empty(isl_union_set_get_space(USet.keep())));
181
110
  USet.foreach_set([=, &Result](isl::set Set) -> isl::stat {
182
110
    auto IdentityMap = give(isl_map_identity(
183
110
        isl_space_map_from_set(isl_set_get_space(Set.keep()))));
184
110
    if (RestrictDomain)
185
56
      IdentityMap =
186
56
          give(isl_map_intersect_domain(IdentityMap.take(), Set.take()));
187
110
    Result = give(isl_union_map_add_map(Result.take(), IdentityMap.take()));
188
110
    return isl::stat::ok;
189
110
  });
190
94
  return Result;
191
94
}
192
193
124
isl::map polly::reverseDomain(isl::map Map) {
194
124
  auto DomSpace =
195
124
      give(isl_space_unwrap(isl_space_domain(isl_map_get_space(Map.keep()))));
196
124
  auto Space1 = give(isl_space_domain(DomSpace.copy()));
197
124
  auto Space2 = give(isl_space_range(DomSpace.take()));
198
124
  auto Swap = makeTupleSwapMap(std::move(Space1), std::move(Space2));
199
124
  return give(isl_map_apply_domain(Map.take(), Swap.take()));
200
124
}
201
202
159
isl::union_map polly::reverseDomain(const isl::union_map &UMap) {
203
159
  auto Result = give(isl_union_map_empty(isl_union_map_get_space(UMap.keep())));
204
159
  UMap.foreach_map([=, &Result](isl::map Map) -> isl::stat {
205
123
    auto Reversed = reverseDomain(std::move(Map));
206
123
    Result = give(isl_union_map_add_map(Result.take(), Reversed.take()));
207
123
    return isl::stat::ok;
208
123
  });
209
159
  return Result;
210
159
}
211
212
562
isl::set polly::shiftDim(isl::set Set, int Pos, int Amount) {
213
562
  int NumDims = isl_set_dim(Set.keep(), isl_dim_set);
214
562
  if (Pos < 0)
215
559
    Pos = NumDims + Pos;
216
562
  assert(Pos < NumDims && "Dimension index must be in range");
217
562
  auto Space = give(isl_set_get_space(Set.keep()));
218
562
  Space = give(isl_space_map_from_domain_and_range(Space.copy(), Space.copy()));
219
562
  auto Translator = makeShiftDimAff(std::move(Space), Pos, Amount);
220
562
  auto TranslatorMap = give(isl_map_from_multi_aff(Translator.take()));
221
562
  return give(isl_set_apply(Set.take(), TranslatorMap.take()));
222
562
}
223
224
546
isl::union_set polly::shiftDim(isl::union_set USet, int Pos, int Amount) {
225
546
  auto Result = give(isl_union_set_empty(isl_union_set_get_space(USet.keep())));
226
561
  USet.foreach_set([=, &Result](isl::set Set) -> isl::stat {
227
561
    auto Shifted = shiftDim(Set, Pos, Amount);
228
561
    Result = give(isl_union_set_add_set(Result.take(), Shifted.take()));
229
561
    return isl::stat::ok;
230
561
  });
231
546
  return Result;
232
546
}
233
234
369
isl::map polly::shiftDim(isl::map Map, isl::dim Dim, int Pos, int Amount) {
235
369
  int NumDims = Map.dim(Dim);
236
369
  if (Pos < 0)
237
365
    Pos = NumDims + Pos;
238
369
  assert(Pos < NumDims && "Dimension index must be in range");
239
369
  auto Space = give(isl_map_get_space(Map.keep()));
240
369
  switch (Dim) {
241
369
  case isl::dim::in:
242
364
    Space = std::move(Space).domain();
243
364
    break;
244
369
  case isl::dim::out:
245
5
    Space = give(isl_space_range(Space.take()));
246
5
    break;
247
369
  default:
248
0
    llvm_unreachable("Unsupported value for 'dim'");
249
369
  }
250
369
  Space = give(isl_space_map_from_domain_and_range(Space.copy(), Space.copy()));
251
369
  auto Translator = makeShiftDimAff(std::move(Space), Pos, Amount);
252
369
  auto TranslatorMap = give(isl_map_from_multi_aff(Translator.take()));
253
369
  switch (Dim) {
254
369
  case isl::dim::in:
255
364
    return Map.apply_domain(TranslatorMap);
256
369
  case isl::dim::out:
257
5
    return Map.apply_range(TranslatorMap);
258
369
  default:
259
0
    llvm_unreachable("Unsupported value for 'dim'");
260
0
  }
261
0
}
262
263
isl::union_map polly::shiftDim(isl::union_map UMap, isl::dim Dim, int Pos,
264
534
                               int Amount) {
265
534
  auto Result = isl::union_map::empty(UMap.get_space());
266
534
267
534
  UMap.foreach_map([=, &Result](isl::map Map) -> isl::stat {
268
367
    auto Shifted = shiftDim(Map, Dim, Pos, Amount);
269
367
    Result = std::move(Result).add_map(Shifted);
270
367
    return isl::stat::ok;
271
367
  });
272
534
  return Result;
273
534
}
274
275
55
void polly::simplify(isl::set &Set) {
276
55
  Set = give(isl_set_compute_divs(Set.take()));
277
55
  Set = give(isl_set_detect_equalities(Set.take()));
278
55
  Set = give(isl_set_coalesce(Set.take()));
279
55
}
280
281
81
void polly::simplify(isl::union_set &USet) {
282
81
  USet = give(isl_union_set_compute_divs(USet.take()));
283
81
  USet = give(isl_union_set_detect_equalities(USet.take()));
284
81
  USet = give(isl_union_set_coalesce(USet.take()));
285
81
}
286
287
748
void polly::simplify(isl::map &Map) {
288
748
  Map = give(isl_map_compute_divs(Map.take()));
289
748
  Map = give(isl_map_detect_equalities(Map.take()));
290
748
  Map = give(isl_map_coalesce(Map.take()));
291
748
}
292
293
514
void polly::simplify(isl::union_map &UMap) {
294
514
  UMap = give(isl_union_map_compute_divs(UMap.take()));
295
514
  UMap = give(isl_union_map_detect_equalities(UMap.take()));
296
514
  UMap = give(isl_union_map_coalesce(UMap.take()));
297
514
}
298
299
isl::union_map polly::computeReachingWrite(isl::union_map Schedule,
300
                                           isl::union_map Writes, bool Reverse,
301
394
                                           bool InclPrevDef, bool InclNextDef) {
302
394
303
394
  // { Scatter[] }
304
394
  isl::space ScatterSpace = getScatterSpace(Schedule);
305
394
306
394
  // { ScatterRead[] -> ScatterWrite[] }
307
394
  isl::map Relation;
308
394
  if (Reverse)
309
205
    Relation = InclPrevDef ? 
isl::map::lex_lt(ScatterSpace)25
310
205
                           : 
isl::map::lex_le(ScatterSpace)180
;
311
189
  else
312
189
    Relation = InclNextDef ? 
isl::map::lex_gt(ScatterSpace)183
313
189
                           : 
isl::map::lex_ge(ScatterSpace)6
;
314
394
315
394
  // { ScatterWrite[] -> [ScatterRead[] -> ScatterWrite[]] }
316
394
  isl::map RelationMap = Relation.range_map().reverse();
317
394
318
394
  // { Element[] -> ScatterWrite[] }
319
394
  isl::union_map WriteAction = Schedule.apply_domain(Writes);
320
394
321
394
  // { ScatterWrite[] -> Element[] }
322
394
  isl::union_map WriteActionRev = WriteAction.reverse();
323
394
324
394
  // { Element[] -> [ScatterUse[] -> ScatterWrite[]] }
325
394
  isl::union_map DefSchedRelation =
326
394
      isl::union_map(RelationMap).apply_domain(WriteActionRev);
327
394
328
394
  // For each element, at every point in time, map to the times of previous
329
394
  // definitions. { [Element[] -> ScatterRead[]] -> ScatterWrite[] }
330
394
  isl::union_map ReachableWrites = DefSchedRelation.uncurry();
331
394
  if (Reverse)
332
205
    ReachableWrites = ReachableWrites.lexmin();
333
189
  else
334
189
    ReachableWrites = ReachableWrites.lexmax();
335
394
336
394
  // { [Element[] -> ScatterWrite[]] -> ScatterWrite[] }
337
394
  isl::union_map SelfUse = WriteAction.range_map();
338
394
339
394
  if (InclPrevDef && 
InclNextDef29
) {
340
6
    // Add the Def itself to the solution.
341
6
    ReachableWrites = ReachableWrites.unite(SelfUse).coalesce();
342
388
  } else if (!InclPrevDef && 
!InclNextDef365
) {
343
10
    // Remove Def itself from the solution.
344
10
    ReachableWrites = ReachableWrites.subtract(SelfUse);
345
10
  }
346
394
347
394
  // { [Element[] -> ScatterRead[]] -> Domain[] }
348
394
  return ReachableWrites.apply_range(Schedule.reverse());
349
394
}
350
351
isl::union_map
352
polly::computeArrayUnused(isl::union_map Schedule, isl::union_map Writes,
353
                          isl::union_map Reads, bool ReadEltInSameInst,
354
79
                          bool IncludeLastRead, bool IncludeWrite) {
355
79
  // { Element[] -> Scatter[] }
356
79
  auto ReadActions =
357
79
      give(isl_union_map_apply_domain(Schedule.copy(), Reads.take()));
358
79
  auto WriteActions =
359
79
      give(isl_union_map_apply_domain(Schedule.copy(), Writes.copy()));
360
79
361
79
  // { [Element[] -> DomainWrite[]] -> Scatter[] }
362
79
  auto EltDomWrites = give(isl_union_map_apply_range(
363
79
      isl_union_map_range_map(isl_union_map_reverse(Writes.copy())),
364
79
      Schedule.copy()));
365
79
366
79
  // { [Element[] -> Scatter[]] -> DomainWrite[] }
367
79
  auto ReachingOverwrite = computeReachingWrite(
368
79
      Schedule, Writes, true, ReadEltInSameInst, !ReadEltInSameInst);
369
79
370
79
  // { [Element[] -> Scatter[]] -> DomainWrite[] }
371
79
  auto ReadsOverwritten = give(isl_union_map_intersect_domain(
372
79
      ReachingOverwrite.take(), isl_union_map_wrap(ReadActions.take())));
373
79
374
79
  // { [Element[] -> DomainWrite[]] -> Scatter[] }
375
79
  auto ReadsOverwrittenRotated = give(isl_union_map_reverse(
376
79
      isl_union_map_curry(reverseDomain(ReadsOverwritten).take())));
377
79
  auto LastOverwrittenRead =
378
79
      give(isl_union_map_lexmax(ReadsOverwrittenRotated.copy()));
379
79
380
79
  // { [Element[] -> DomainWrite[]] -> Scatter[] }
381
79
  auto BetweenLastReadOverwrite = betweenScatter(
382
79
      LastOverwrittenRead, EltDomWrites, IncludeLastRead, IncludeWrite);
383
79
384
79
  // { [Element[] -> Scatter[]] -> DomainWrite[] }
385
79
  isl::union_map ReachingOverwriteZone = computeReachingWrite(
386
79
      Schedule, Writes, true, IncludeLastRead, IncludeWrite);
387
79
388
79
  // { [Element[] -> DomainWrite[]] -> Scatter[] }
389
79
  isl::union_map ReachingOverwriteRotated =
390
79
      reverseDomain(ReachingOverwriteZone).curry().reverse();
391
79
392
79
  // { [Element[] -> DomainWrite[]] -> Scatter[] }
393
79
  isl::union_map WritesWithoutReads = ReachingOverwriteRotated.subtract_domain(
394
79
      ReadsOverwrittenRotated.domain());
395
79
396
79
  return BetweenLastReadOverwrite.unite(WritesWithoutReads)
397
79
      .domain_factor_domain();
398
79
}
399
400
isl::union_set polly::convertZoneToTimepoints(isl::union_set Zone,
401
546
                                              bool InclStart, bool InclEnd) {
402
546
  if (!InclStart && 
InclEnd10
)
403
5
    return Zone;
404
541
405
541
  auto ShiftedZone = shiftDim(Zone, -1, -1);
406
541
  if (InclStart && 
!InclEnd536
)
407
531
    return ShiftedZone;
408
10
  else if (!InclStart && 
!InclEnd5
)
409
5
    return give(isl_union_set_intersect(Zone.take(), ShiftedZone.take()));
410
5
411
5
  assert(InclStart && InclEnd);
412
5
  return give(isl_union_set_union(Zone.take(), ShiftedZone.take()));
413
5
}
414
415
isl::union_map polly::convertZoneToTimepoints(isl::union_map Zone, isl::dim Dim,
416
600
                                              bool InclStart, bool InclEnd) {
417
600
  if (!InclStart && 
InclEnd70
)
418
68
    return Zone;
419
532
420
532
  auto ShiftedZone = shiftDim(Zone, Dim, -1, -1);
421
532
  if (InclStart && 
!InclEnd530
)
422
528
    return ShiftedZone;
423
4
  else if (!InclStart && 
!InclEnd2
)
424
2
    return give(isl_union_map_intersect(Zone.take(), ShiftedZone.take()));
425
2
426
2
  assert(InclStart && InclEnd);
427
2
  return give(isl_union_map_union(Zone.take(), ShiftedZone.take()));
428
2
}
429
430
isl::map polly::convertZoneToTimepoints(isl::map Zone, isl::dim Dim,
431
72
                                        bool InclStart, bool InclEnd) {
432
72
  if (!InclStart && InclEnd)
433
72
    return Zone;
434
0
435
0
  auto ShiftedZone = shiftDim(Zone, Dim, -1, -1);
436
0
  if (InclStart && !InclEnd)
437
0
    return ShiftedZone;
438
0
  else if (!InclStart && !InclEnd)
439
0
    return give(isl_map_intersect(Zone.take(), ShiftedZone.take()));
440
0
441
0
  assert(InclStart && InclEnd);
442
0
  return give(isl_map_union(Zone.take(), ShiftedZone.take()));
443
0
}
444
445
205
isl::map polly::distributeDomain(isl::map Map) {
446
205
  // Note that we cannot take Map apart into { Domain[] -> Range1[] } and {
447
205
  // Domain[] -> Range2[] } and combine again. We would loose any relation
448
205
  // between Range1[] and Range2[] that is not also a constraint to Domain[].
449
205
450
205
  auto Space = give(isl_map_get_space(Map.keep()));
451
205
  auto DomainSpace = give(isl_space_domain(Space.copy()));
452
205
  auto DomainDims = isl_space_dim(DomainSpace.keep(), isl_dim_set);
453
205
  auto RangeSpace = give(isl_space_unwrap(isl_space_range(Space.copy())));
454
205
  auto Range1Space = give(isl_space_domain(RangeSpace.copy()));
455
205
  auto Range1Dims = isl_space_dim(Range1Space.keep(), isl_dim_set);
456
205
  auto Range2Space = give(isl_space_range(RangeSpace.copy()));
457
205
  auto Range2Dims = isl_space_dim(Range2Space.keep(), isl_dim_set);
458
205
459
205
  auto OutputSpace = give(isl_space_map_from_domain_and_range(
460
205
      isl_space_wrap(isl_space_map_from_domain_and_range(DomainSpace.copy(),
461
205
                                                         Range1Space.copy())),
462
205
      isl_space_wrap(isl_space_map_from_domain_and_range(DomainSpace.copy(),
463
205
                                                         Range2Space.copy()))));
464
205
465
205
  auto Translator =
466
205
      give(isl_basic_map_universe(isl_space_map_from_domain_and_range(
467
205
          isl_space_wrap(Space.copy()), isl_space_wrap(OutputSpace.copy()))));
468
205
469
413
  for (unsigned i = 0; i < DomainDims; 
i += 1208
) {
470
208
    Translator = give(
471
208
        isl_basic_map_equate(Translator.take(), isl_dim_in, i, isl_dim_out, i));
472
208
    Translator =
473
208
        give(isl_basic_map_equate(Translator.take(), isl_dim_in, i, isl_dim_out,
474
208
                                  DomainDims + Range1Dims + i));
475
208
  }
476
675
  for (unsigned i = 0; i < Range1Dims; 
i += 1470
) {
477
470
    Translator =
478
470
        give(isl_basic_map_equate(Translator.take(), isl_dim_in, DomainDims + i,
479
470
                                  isl_dim_out, DomainDims + i));
480
470
  }
481
367
  for (unsigned i = 0; i < Range2Dims; 
i += 1162
) {
482
162
    Translator = give(isl_basic_map_equate(
483
162
        Translator.take(), isl_dim_in, DomainDims + Range1Dims + i, isl_dim_out,
484
162
        DomainDims + Range1Dims + DomainDims + i));
485
162
  }
486
205
487
205
  return give(isl_set_unwrap(isl_set_apply(
488
205
      isl_map_wrap(Map.copy()), isl_map_from_basic_map(Translator.copy()))));
489
205
}
490
491
117
isl::union_map polly::distributeDomain(isl::union_map UMap) {
492
117
  auto Result = give(isl_union_map_empty(isl_union_map_get_space(UMap.keep())));
493
203
  isl::stat Success = UMap.foreach_map([=, &Result](isl::map Map) {
494
203
    auto Distributed = distributeDomain(Map);
495
203
    Result = give(isl_union_map_add_map(Result.take(), Distributed.copy()));
496
203
    return isl::stat::ok;
497
203
  });
498
117
  if (Success != isl::stat::ok)
499
1
    return {};
500
116
  return Result;
501
116
}
502
503
54
isl::union_map polly::liftDomains(isl::union_map UMap, isl::union_set Factor) {
504
54
505
54
  // { Factor[] -> Factor[] }
506
54
  auto Factors = makeIdentityMap(std::move(Factor), true);
507
54
508
54
  return std::move(Factors).product(std::move(UMap));
509
54
}
510
511
isl::union_map polly::applyDomainRange(isl::union_map UMap,
512
51
                                       isl::union_map Func) {
513
51
  // This implementation creates unnecessary cross products of the
514
51
  // DomainDomain[] and Func. An alternative implementation could reverse
515
51
  // domain+uncurry,apply Func to what now is the domain, then undo the
516
51
  // preparing transformation. Another alternative implementation could create a
517
51
  // translator map for each piece.
518
51
519
51
  // { DomainDomain[] }
520
51
  auto DomainDomain = UMap.domain().unwrap().domain();
521
51
522
51
  // { [DomainDomain[] -> DomainRange[]] -> [DomainDomain[] -> NewDomainRange[]]
523
51
  // }
524
51
  auto LifetedFunc = liftDomains(std::move(Func), DomainDomain);
525
51
526
51
  return std::move(UMap).apply_domain(std::move(LifetedFunc));
527
51
}
528
529
156
isl::map polly::intersectRange(isl::map Map, isl::union_set Range) {
530
156
  isl::set RangeSet = Range.extract_set(Map.get_space().range());
531
156
  return Map.intersect_range(RangeSet);
532
156
}
533
534
78
isl::val polly::getConstant(isl::pw_aff PwAff, bool Max, bool Min) {
535
78
  assert(!Max || !Min); // Cannot return min and max at the same time.
536
78
  isl::val Result;
537
78
  PwAff.foreach_piece([=, &Result](isl::set Set, isl::aff Aff) -> isl::stat {
538
78
    if (Result && 
Result.is_nan()0
)
539
0
      return isl::stat::ok;
540
78
541
78
    // TODO: If Min/Max, we can also determine a minimum/maximum value if
542
78
    // Set is constant-bounded.
543
78
    if (!Aff.is_cst()) {
544
0
      Result = isl::val::nan(Aff.get_ctx());
545
0
      return isl::stat::error;
546
0
    }
547
78
548
78
    isl::val ThisVal = Aff.get_constant_val();
549
78
    if (!Result) {
550
78
      Result = ThisVal;
551
78
      return isl::stat::ok;
552
78
    }
553
0
554
0
    if (Result.eq(ThisVal))
555
0
      return isl::stat::ok;
556
0
557
0
    if (Max && ThisVal.gt(Result)) {
558
0
      Result = ThisVal;
559
0
      return isl::stat::ok;
560
0
    }
561
0
562
0
    if (Min && ThisVal.lt(Result)) {
563
0
      Result = ThisVal;
564
0
      return isl::stat::ok;
565
0
    }
566
0
567
0
    // Not compatible
568
0
    Result = isl::val::nan(Aff.get_ctx());
569
0
    return isl::stat::error;
570
0
  });
571
78
  return Result;
572
78
}
573
574
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
575
static void foreachPoint(const isl::set &Set,
576
                         const std::function<void(isl::point P)> &F) {
577
  isl_set_foreach_point(
578
      Set.keep(),
579
      [](__isl_take isl_point *p, void *User) -> isl_stat {
580
        auto &F = *static_cast<const std::function<void(isl::point)> *>(User);
581
        F(give(p));
582
        return isl_stat_ok;
583
      },
584
      const_cast<void *>(static_cast<const void *>(&F)));
585
}
586
587
static void foreachPoint(isl::basic_set BSet,
588
                         const std::function<void(isl::point P)> &F) {
589
  foreachPoint(give(isl_set_from_basic_set(BSet.take())), F);
590
}
591
592
/// Determine the sorting order of the sets @p A and @p B without considering
593
/// the space structure.
594
///
595
/// Ordering is based on the lower bounds of the set's dimensions. First
596
/// dimensions are considered first.
597
static int flatCompare(const isl::basic_set &A, const isl::basic_set &B) {
598
  int ALen = A.dim(isl::dim::set);
599
  int BLen = B.dim(isl::dim::set);
600
  int Len = std::min(ALen, BLen);
601
602
  for (int i = 0; i < Len; i += 1) {
603
    isl::basic_set ADim =
604
        A.project_out(isl::dim::param, 0, A.dim(isl::dim::param))
605
            .project_out(isl::dim::set, i + 1, ALen - i - 1)
606
            .project_out(isl::dim::set, 0, i);
607
    isl::basic_set BDim =
608
        B.project_out(isl::dim::param, 0, B.dim(isl::dim::param))
609
            .project_out(isl::dim::set, i + 1, BLen - i - 1)
610
            .project_out(isl::dim::set, 0, i);
611
612
    isl::basic_set AHull = isl::set(ADim).convex_hull();
613
    isl::basic_set BHull = isl::set(BDim).convex_hull();
614
615
    bool ALowerBounded =
616
        bool(isl::set(AHull).dim_has_any_lower_bound(isl::dim::set, 0));
617
    bool BLowerBounded =
618
        bool(isl::set(BHull).dim_has_any_lower_bound(isl::dim::set, 0));
619
620
    int BoundedCompare = BLowerBounded - ALowerBounded;
621
    if (BoundedCompare != 0)
622
      return BoundedCompare;
623
624
    if (!ALowerBounded || !BLowerBounded)
625
      continue;
626
627
    isl::pw_aff AMin = isl::set(ADim).dim_min(0);
628
    isl::pw_aff BMin = isl::set(BDim).dim_min(0);
629
630
    isl::val AMinVal = polly::getConstant(AMin, false, true);
631
    isl::val BMinVal = polly::getConstant(BMin, false, true);
632
633
    int MinCompare = AMinVal.sub(BMinVal).sgn();
634
    if (MinCompare != 0)
635
      return MinCompare;
636
  }
637
638
  // If all the dimensions' lower bounds are equal or incomparable, sort based
639
  // on the number of dimensions.
640
  return ALen - BLen;
641
}
642
643
/// Compare the sets @p A and @p B according to their nested space structure. If
644
/// the structure is the same, sort using the dimension lower bounds.
645
static int recursiveCompare(const isl::basic_set &A, const isl::basic_set &B) {
646
  isl::space ASpace = A.get_space();
647
  isl::space BSpace = B.get_space();
648
649
  int WrappingCompare = bool(ASpace.is_wrapping()) - bool(BSpace.is_wrapping());
650
  if (WrappingCompare != 0)
651
    return WrappingCompare;
652
653
  if (ASpace.is_wrapping() && B.is_wrapping()) {
654
    isl::basic_map AMap = A.unwrap();
655
    isl::basic_map BMap = B.unwrap();
656
657
    int FirstResult = recursiveCompare(AMap.domain(), BMap.domain());
658
    if (FirstResult != 0)
659
      return FirstResult;
660
661
    return recursiveCompare(AMap.range(), BMap.range());
662
  }
663
664
  std::string AName = ASpace.has_tuple_name(isl::dim::set)
665
                          ? ASpace.get_tuple_name(isl::dim::set)
666
                          : std::string();
667
  std::string BName = BSpace.has_tuple_name(isl::dim::set)
668
                          ? BSpace.get_tuple_name(isl::dim::set)
669
                          : std::string();
670
671
  int NameCompare = AName.compare(BName);
672
  if (NameCompare != 0)
673
    return NameCompare;
674
675
  return flatCompare(A, B);
676
}
677
678
/// Wrapper for recursiveCompare, convert a {-1,0,1} compare result to what
679
/// std::sort expects.
680
static bool orderComparer(const isl::basic_set &A, const isl::basic_set &B) {
681
  return recursiveCompare(A, B) < 0;
682
}
683
684
/// Print a string representation of @p USet to @p OS.
685
///
686
/// The pieces of @p USet are printed in a sorted order. Spaces with equal or
687
/// similar nesting structure are printed together. Compared to isl's own
688
/// printing function the uses the structure itself as base of the sorting, not
689
/// a hash of it. It ensures that e.g. maps spaces with same domain structure
690
/// are printed together. Set pieces with same structure are printed in order of
691
/// their lower bounds.
692
///
693
/// @param USet     Polyhedra to print.
694
/// @param OS       Target stream.
695
/// @param Simplify Whether to simplify the polyhedron before printing.
696
/// @param IsMap    Whether @p USet is a wrapped map. If true, sets are
697
///                 unwrapped before printing to again appear as a map.
698
static void printSortedPolyhedra(isl::union_set USet, llvm::raw_ostream &OS,
699
                                 bool Simplify, bool IsMap) {
700
  if (!USet) {
701
    OS << "<null>\n";
702
    return;
703
  }
704
705
  if (Simplify)
706
    simplify(USet);
707
708
  // Get all the polyhedra.
709
  std::vector<isl::basic_set> BSets;
710
  USet.foreach_set([&BSets](isl::set Set) -> isl::stat {
711
    Set.foreach_basic_set([&BSets](isl::basic_set BSet) -> isl::stat {
712
      BSets.push_back(BSet);
713
      return isl::stat::ok;
714
    });
715
    return isl::stat::ok;
716
  });
717
718
  if (BSets.empty()) {
719
    OS << "{\n}\n";
720
    return;
721
  }
722
723
  // Sort the polyhedra.
724
  std::sort(BSets.begin(), BSets.end(), orderComparer);
725
726
  // Print the polyhedra.
727
  bool First = true;
728
  for (const isl::basic_set &BSet : BSets) {
729
    std::string Str;
730
    if (IsMap)
731
      Str = isl::map(BSet.unwrap()).to_str();
732
    else
733
      Str = isl::set(BSet).to_str();
734
    size_t OpenPos = Str.find_first_of('{');
735
    assert(OpenPos != std::string::npos);
736
    size_t ClosePos = Str.find_last_of('}');
737
    assert(ClosePos != std::string::npos);
738
739
    if (First)
740
      OS << llvm::StringRef(Str).substr(0, OpenPos + 1) << "\n ";
741
    else
742
      OS << ";\n ";
743
744
    OS << llvm::StringRef(Str).substr(OpenPos + 1, ClosePos - OpenPos - 2);
745
    First = false;
746
  }
747
  assert(!First);
748
  OS << "\n}\n";
749
}
750
751
static void recursiveExpand(isl::basic_set BSet, int Dim, isl::set &Expanded) {
752
  int Dims = BSet.dim(isl::dim::set);
753
  if (Dim >= Dims) {
754
    Expanded = Expanded.unite(BSet);
755
    return;
756
  }
757
758
  isl::basic_set DimOnly =
759
      BSet.project_out(isl::dim::param, 0, BSet.dim(isl::dim::param))
760
          .project_out(isl::dim::set, Dim + 1, Dims - Dim - 1)
761
          .project_out(isl::dim::set, 0, Dim);
762
  if (!DimOnly.is_bounded()) {
763
    recursiveExpand(BSet, Dim + 1, Expanded);
764
    return;
765
  }
766
767
  foreachPoint(DimOnly, [&, Dim](isl::point P) {
768
    isl::val Val = P.get_coordinate_val(isl::dim::set, 0);
769
    isl::basic_set FixBSet = BSet.fix_val(isl::dim::set, Dim, Val);
770
    recursiveExpand(FixBSet, Dim + 1, Expanded);
771
  });
772
}
773
774
/// Make each point of a set explicit.
775
///
776
/// "Expanding" makes each point a set contains explicit. That is, the result is
777
/// a set of singleton polyhedra. Unbounded dimensions are not expanded.
778
///
779
/// Example:
780
///   { [i] : 0 <= i < 2 }
781
/// is expanded to:
782
///   { [0]; [1] }
783
static isl::set expand(const isl::set &Set) {
784
  isl::set Expanded = isl::set::empty(Set.get_space());
785
  Set.foreach_basic_set([&](isl::basic_set BSet) -> isl::stat {
786
    recursiveExpand(BSet, 0, Expanded);
787
    return isl::stat::ok;
788
  });
789
  return Expanded;
790
}
791
792
/// Expand all points of a union set explicit.
793
///
794
/// @see expand(const isl::set)
795
static isl::union_set expand(const isl::union_set &USet) {
796
  isl::union_set Expanded =
797
      give(isl_union_set_empty(isl_union_set_get_space(USet.keep())));
798
  USet.foreach_set([&](isl::set Set) -> isl::stat {
799
    isl::set SetExpanded = expand(Set);
800
    Expanded = Expanded.add_set(SetExpanded);
801
    return isl::stat::ok;
802
  });
803
  return Expanded;
804
}
805
806
LLVM_DUMP_METHOD void polly::dumpPw(const isl::set &Set) {
807
  printSortedPolyhedra(Set, llvm::errs(), true, false);
808
}
809
810
LLVM_DUMP_METHOD void polly::dumpPw(const isl::map &Map) {
811
  printSortedPolyhedra(Map.wrap(), llvm::errs(), true, true);
812
}
813
814
LLVM_DUMP_METHOD void polly::dumpPw(const isl::union_set &USet) {
815
  printSortedPolyhedra(USet, llvm::errs(), true, false);
816
}
817
818
LLVM_DUMP_METHOD void polly::dumpPw(const isl::union_map &UMap) {
819
  printSortedPolyhedra(UMap.wrap(), llvm::errs(), true, true);
820
}
821
822
LLVM_DUMP_METHOD void polly::dumpPw(__isl_keep isl_set *Set) {
823
  dumpPw(isl::manage(isl_set_copy(Set)));
824
}
825
826
LLVM_DUMP_METHOD void polly::dumpPw(__isl_keep isl_map *Map) {
827
  dumpPw(isl::manage(isl_map_copy(Map)));
828
}
829
830
LLVM_DUMP_METHOD void polly::dumpPw(__isl_keep isl_union_set *USet) {
831
  dumpPw(isl::manage(isl_union_set_copy(USet)));
832
}
833
834
LLVM_DUMP_METHOD void polly::dumpPw(__isl_keep isl_union_map *UMap) {
835
  dumpPw(isl::manage(isl_union_map_copy(UMap)));
836
}
837
838
LLVM_DUMP_METHOD void polly::dumpExpanded(const isl::set &Set) {
839
  printSortedPolyhedra(expand(Set), llvm::errs(), false, false);
840
}
841
842
LLVM_DUMP_METHOD void polly::dumpExpanded(const isl::map &Map) {
843
  printSortedPolyhedra(expand(Map.wrap()), llvm::errs(), false, true);
844
}
845
846
LLVM_DUMP_METHOD void polly::dumpExpanded(const isl::union_set &USet) {
847
  printSortedPolyhedra(expand(USet), llvm::errs(), false, false);
848
}
849
850
LLVM_DUMP_METHOD void polly::dumpExpanded(const isl::union_map &UMap) {
851
  printSortedPolyhedra(expand(UMap.wrap()), llvm::errs(), false, true);
852
}
853
854
LLVM_DUMP_METHOD void polly::dumpExpanded(__isl_keep isl_set *Set) {
855
  dumpExpanded(isl::manage(isl_set_copy(Set)));
856
}
857
858
LLVM_DUMP_METHOD void polly::dumpExpanded(__isl_keep isl_map *Map) {
859
  dumpExpanded(isl::manage(isl_map_copy(Map)));
860
}
861
862
LLVM_DUMP_METHOD void polly::dumpExpanded(__isl_keep isl_union_set *USet) {
863
  dumpExpanded(isl::manage(isl_union_set_copy(USet)));
864
}
865
866
LLVM_DUMP_METHOD void polly::dumpExpanded(__isl_keep isl_union_map *UMap) {
867
  dumpExpanded(isl::manage(isl_union_map_copy(UMap)));
868
}
869
#endif