1 //===- polly/ScheduleTreeTransform.cpp --------------------------*- 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 // Make changes to isl's schedule tree data structure.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "polly/ScheduleTreeTransform.h"
14 #include "polly/Support/ISLTools.h"
15 #include "polly/Support/ScopHelper.h"
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/Sequence.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/Metadata.h"
21 #include "llvm/Transforms/Utils/UnrollLoop.h"
22 
23 using namespace polly;
24 using namespace llvm;
25 
26 namespace {
27 /// Recursively visit all nodes of a schedule tree while allowing changes.
28 ///
29 /// The visit methods return an isl::schedule_node that is used to continue
30 /// visiting the tree. Structural changes such as returning a different node
31 /// will confuse the visitor.
32 template <typename Derived, typename... Args>
33 struct ScheduleNodeRewriter
34     : public RecursiveScheduleTreeVisitor<Derived, isl::schedule_node,
35                                           Args...> {
36   Derived &getDerived() { return *static_cast<Derived *>(this); }
37   const Derived &getDerived() const {
38     return *static_cast<const Derived *>(this);
39   }
40 
41   isl::schedule_node visitNode(const isl::schedule_node &Node, Args... args) {
42     if (!Node.has_children())
43       return Node;
44 
45     isl::schedule_node It = Node.first_child();
46     while (true) {
47       It = getDerived().visit(It, std::forward<Args>(args)...);
48       if (!It.has_next_sibling())
49         break;
50       It = It.next_sibling();
51     }
52     return It.parent();
53   }
54 };
55 
56 /// Rewrite a schedule tree by reconstructing it bottom-up.
57 ///
58 /// By default, the original schedule tree is reconstructed. To build a
59 /// different tree, redefine visitor methods in a derived class (CRTP).
60 ///
61 /// Note that AST build options are not applied; Setting the isolate[] option
62 /// makes the schedule tree 'anchored' and cannot be modified afterwards. Hence,
63 /// AST build options must be set after the tree has been constructed.
64 template <typename Derived, typename... Args>
65 struct ScheduleTreeRewriter
66     : public RecursiveScheduleTreeVisitor<Derived, isl::schedule, Args...> {
67   Derived &getDerived() { return *static_cast<Derived *>(this); }
68   const Derived &getDerived() const {
69     return *static_cast<const Derived *>(this);
70   }
71 
72   isl::schedule visitDomain(const isl::schedule_node &Node, Args... args) {
73     // Every schedule_tree already has a domain node, no need to add one.
74     return getDerived().visit(Node.first_child(), std::forward<Args>(args)...);
75   }
76 
77   isl::schedule visitBand(const isl::schedule_node &Band, Args... args) {
78     isl::multi_union_pw_aff PartialSched =
79         isl::manage(isl_schedule_node_band_get_partial_schedule(Band.get()));
80     isl::schedule NewChild =
81         getDerived().visit(Band.child(0), std::forward<Args>(args)...);
82     isl::schedule_node NewNode =
83         NewChild.insert_partial_schedule(PartialSched).get_root().child(0);
84 
85     // Reapply permutability and coincidence attributes.
86     NewNode = isl::manage(isl_schedule_node_band_set_permutable(
87         NewNode.release(), isl_schedule_node_band_get_permutable(Band.get())));
88     unsigned BandDims = isl_schedule_node_band_n_member(Band.get());
89     for (unsigned i = 0; i < BandDims; i += 1)
90       NewNode = isl::manage(isl_schedule_node_band_member_set_coincident(
91           NewNode.release(), i,
92           isl_schedule_node_band_member_get_coincident(Band.get(), i)));
93 
94     return NewNode.get_schedule();
95   }
96 
97   isl::schedule visitSequence(const isl::schedule_node &Sequence,
98                               Args... args) {
99     int NumChildren = isl_schedule_node_n_children(Sequence.get());
100     isl::schedule Result =
101         getDerived().visit(Sequence.child(0), std::forward<Args>(args)...);
102     for (int i = 1; i < NumChildren; i += 1)
103       Result = Result.sequence(
104           getDerived().visit(Sequence.child(i), std::forward<Args>(args)...));
105     return Result;
106   }
107 
108   isl::schedule visitSet(const isl::schedule_node &Set, Args... args) {
109     int NumChildren = isl_schedule_node_n_children(Set.get());
110     isl::schedule Result =
111         getDerived().visit(Set.child(0), std::forward<Args>(args)...);
112     for (int i = 1; i < NumChildren; i += 1)
113       Result = isl::manage(
114           isl_schedule_set(Result.release(),
115                            getDerived()
116                                .visit(Set.child(i), std::forward<Args>(args)...)
117                                .release()));
118     return Result;
119   }
120 
121   isl::schedule visitLeaf(const isl::schedule_node &Leaf, Args... args) {
122     return isl::schedule::from_domain(Leaf.get_domain());
123   }
124 
125   isl::schedule visitMark(const isl::schedule_node &Mark, Args... args) {
126 
127     isl::id TheMark = Mark.as<isl::schedule_node_mark>().get_id();
128     isl::schedule_node NewChild =
129         getDerived()
130             .visit(Mark.first_child(), std::forward<Args>(args)...)
131             .get_root()
132             .first_child();
133     return NewChild.insert_mark(TheMark).get_schedule();
134   }
135 
136   isl::schedule visitExtension(const isl::schedule_node &Extension,
137                                Args... args) {
138     isl::union_map TheExtension =
139         Extension.as<isl::schedule_node_extension>().get_extension();
140     isl::schedule_node NewChild = getDerived()
141                                       .visit(Extension.child(0), args...)
142                                       .get_root()
143                                       .first_child();
144     isl::schedule_node NewExtension =
145         isl::schedule_node::from_extension(TheExtension);
146     return NewChild.graft_before(NewExtension).get_schedule();
147   }
148 
149   isl::schedule visitFilter(const isl::schedule_node &Filter, Args... args) {
150     isl::union_set FilterDomain =
151         Filter.as<isl::schedule_node_filter>().get_filter();
152     isl::schedule NewSchedule =
153         getDerived().visit(Filter.child(0), std::forward<Args>(args)...);
154     return NewSchedule.intersect_domain(FilterDomain);
155   }
156 
157   isl::schedule visitNode(const isl::schedule_node &Node, Args... args) {
158     llvm_unreachable("Not implemented");
159   }
160 };
161 
162 /// Rewrite a schedule tree to an equivalent one without extension nodes.
163 ///
164 /// Each visit method takes two additional arguments:
165 ///
166 ///  * The new domain the node, which is the inherited domain plus any domains
167 ///    added by extension nodes.
168 ///
169 ///  * A map of extension domains of all children is returned; it is required by
170 ///    band nodes to schedule the additional domains at the same position as the
171 ///    extension node would.
172 ///
173 struct ExtensionNodeRewriter
174     : public ScheduleTreeRewriter<ExtensionNodeRewriter, const isl::union_set &,
175                                   isl::union_map &> {
176   using BaseTy = ScheduleTreeRewriter<ExtensionNodeRewriter,
177                                       const isl::union_set &, isl::union_map &>;
178   BaseTy &getBase() { return *this; }
179   const BaseTy &getBase() const { return *this; }
180 
181   isl::schedule visitSchedule(const isl::schedule &Schedule) {
182     isl::union_map Extensions;
183     isl::schedule Result =
184         visit(Schedule.get_root(), Schedule.get_domain(), Extensions);
185     assert(!Extensions.is_null() && Extensions.is_empty());
186     return Result;
187   }
188 
189   isl::schedule visitSequence(const isl::schedule_node &Sequence,
190                               const isl::union_set &Domain,
191                               isl::union_map &Extensions) {
192     int NumChildren = isl_schedule_node_n_children(Sequence.get());
193     isl::schedule NewNode = visit(Sequence.first_child(), Domain, Extensions);
194     for (int i = 1; i < NumChildren; i += 1) {
195       isl::schedule_node OldChild = Sequence.child(i);
196       isl::union_map NewChildExtensions;
197       isl::schedule NewChildNode = visit(OldChild, Domain, NewChildExtensions);
198       NewNode = NewNode.sequence(NewChildNode);
199       Extensions = Extensions.unite(NewChildExtensions);
200     }
201     return NewNode;
202   }
203 
204   isl::schedule visitSet(const isl::schedule_node &Set,
205                          const isl::union_set &Domain,
206                          isl::union_map &Extensions) {
207     int NumChildren = isl_schedule_node_n_children(Set.get());
208     isl::schedule NewNode = visit(Set.first_child(), Domain, Extensions);
209     for (int i = 1; i < NumChildren; i += 1) {
210       isl::schedule_node OldChild = Set.child(i);
211       isl::union_map NewChildExtensions;
212       isl::schedule NewChildNode = visit(OldChild, Domain, NewChildExtensions);
213       NewNode = isl::manage(
214           isl_schedule_set(NewNode.release(), NewChildNode.release()));
215       Extensions = Extensions.unite(NewChildExtensions);
216     }
217     return NewNode;
218   }
219 
220   isl::schedule visitLeaf(const isl::schedule_node &Leaf,
221                           const isl::union_set &Domain,
222                           isl::union_map &Extensions) {
223     Extensions = isl::union_map::empty(Leaf.ctx());
224     return isl::schedule::from_domain(Domain);
225   }
226 
227   isl::schedule visitBand(const isl::schedule_node &OldNode,
228                           const isl::union_set &Domain,
229                           isl::union_map &OuterExtensions) {
230     isl::schedule_node OldChild = OldNode.first_child();
231     isl::multi_union_pw_aff PartialSched =
232         isl::manage(isl_schedule_node_band_get_partial_schedule(OldNode.get()));
233 
234     isl::union_map NewChildExtensions;
235     isl::schedule NewChild = visit(OldChild, Domain, NewChildExtensions);
236 
237     // Add the extensions to the partial schedule.
238     OuterExtensions = isl::union_map::empty(NewChildExtensions.ctx());
239     isl::union_map NewPartialSchedMap = isl::union_map::from(PartialSched);
240     unsigned BandDims = isl_schedule_node_band_n_member(OldNode.get());
241     for (isl::map Ext : NewChildExtensions.get_map_list()) {
242       unsigned ExtDims = Ext.domain_tuple_dim().release();
243       assert(ExtDims >= BandDims);
244       unsigned OuterDims = ExtDims - BandDims;
245 
246       isl::map BandSched =
247           Ext.project_out(isl::dim::in, 0, OuterDims).reverse();
248       NewPartialSchedMap = NewPartialSchedMap.unite(BandSched);
249 
250       // There might be more outer bands that have to schedule the extensions.
251       if (OuterDims > 0) {
252         isl::map OuterSched =
253             Ext.project_out(isl::dim::in, OuterDims, BandDims);
254         OuterExtensions = OuterExtensions.unite(OuterSched);
255       }
256     }
257     isl::multi_union_pw_aff NewPartialSchedAsAsMultiUnionPwAff =
258         isl::multi_union_pw_aff::from_union_map(NewPartialSchedMap);
259     isl::schedule_node NewNode =
260         NewChild.insert_partial_schedule(NewPartialSchedAsAsMultiUnionPwAff)
261             .get_root()
262             .child(0);
263 
264     // Reapply permutability and coincidence attributes.
265     NewNode = isl::manage(isl_schedule_node_band_set_permutable(
266         NewNode.release(),
267         isl_schedule_node_band_get_permutable(OldNode.get())));
268     for (unsigned i = 0; i < BandDims; i += 1) {
269       NewNode = isl::manage(isl_schedule_node_band_member_set_coincident(
270           NewNode.release(), i,
271           isl_schedule_node_band_member_get_coincident(OldNode.get(), i)));
272     }
273 
274     return NewNode.get_schedule();
275   }
276 
277   isl::schedule visitFilter(const isl::schedule_node &Filter,
278                             const isl::union_set &Domain,
279                             isl::union_map &Extensions) {
280     isl::union_set FilterDomain =
281         Filter.as<isl::schedule_node_filter>().get_filter();
282     isl::union_set NewDomain = Domain.intersect(FilterDomain);
283 
284     // A filter is added implicitly if necessary when joining schedule trees.
285     return visit(Filter.first_child(), NewDomain, Extensions);
286   }
287 
288   isl::schedule visitExtension(const isl::schedule_node &Extension,
289                                const isl::union_set &Domain,
290                                isl::union_map &Extensions) {
291     isl::union_map ExtDomain =
292         Extension.as<isl::schedule_node_extension>().get_extension();
293     isl::union_set NewDomain = Domain.unite(ExtDomain.range());
294     isl::union_map ChildExtensions;
295     isl::schedule NewChild =
296         visit(Extension.first_child(), NewDomain, ChildExtensions);
297     Extensions = ChildExtensions.unite(ExtDomain);
298     return NewChild;
299   }
300 };
301 
302 /// Collect all AST build options in any schedule tree band.
303 ///
304 /// ScheduleTreeRewriter cannot apply the schedule tree options. This class
305 /// collects these options to apply them later.
306 struct CollectASTBuildOptions
307     : public RecursiveScheduleTreeVisitor<CollectASTBuildOptions> {
308   using BaseTy = RecursiveScheduleTreeVisitor<CollectASTBuildOptions>;
309   BaseTy &getBase() { return *this; }
310   const BaseTy &getBase() const { return *this; }
311 
312   llvm::SmallVector<isl::union_set, 8> ASTBuildOptions;
313 
314   void visitBand(const isl::schedule_node &Band) {
315     ASTBuildOptions.push_back(
316         isl::manage(isl_schedule_node_band_get_ast_build_options(Band.get())));
317     return getBase().visitBand(Band);
318   }
319 };
320 
321 /// Apply AST build options to the bands in a schedule tree.
322 ///
323 /// This rewrites a schedule tree with the AST build options applied. We assume
324 /// that the band nodes are visited in the same order as they were when the
325 /// build options were collected, typically by CollectASTBuildOptions.
326 struct ApplyASTBuildOptions
327     : public ScheduleNodeRewriter<ApplyASTBuildOptions> {
328   using BaseTy = ScheduleNodeRewriter<ApplyASTBuildOptions>;
329   BaseTy &getBase() { return *this; }
330   const BaseTy &getBase() const { return *this; }
331 
332   size_t Pos;
333   llvm::ArrayRef<isl::union_set> ASTBuildOptions;
334 
335   ApplyASTBuildOptions(llvm::ArrayRef<isl::union_set> ASTBuildOptions)
336       : ASTBuildOptions(ASTBuildOptions) {}
337 
338   isl::schedule visitSchedule(const isl::schedule &Schedule) {
339     Pos = 0;
340     isl::schedule Result = visit(Schedule).get_schedule();
341     assert(Pos == ASTBuildOptions.size() &&
342            "AST build options must match to band nodes");
343     return Result;
344   }
345 
346   isl::schedule_node visitBand(const isl::schedule_node &Band) {
347     isl::schedule_node Result =
348         Band.as<isl::schedule_node_band>().set_ast_build_options(
349             ASTBuildOptions[Pos]);
350     Pos += 1;
351     return getBase().visitBand(Result);
352   }
353 };
354 
355 /// Return whether the schedule contains an extension node.
356 static bool containsExtensionNode(isl::schedule Schedule) {
357   assert(!Schedule.is_null());
358 
359   auto Callback = [](__isl_keep isl_schedule_node *Node,
360                      void *User) -> isl_bool {
361     if (isl_schedule_node_get_type(Node) == isl_schedule_node_extension) {
362       // Stop walking the schedule tree.
363       return isl_bool_error;
364     }
365 
366     // Continue searching the subtree.
367     return isl_bool_true;
368   };
369   isl_stat RetVal = isl_schedule_foreach_schedule_node_top_down(
370       Schedule.get(), Callback, nullptr);
371 
372   // We assume that the traversal itself does not fail, i.e. the only reason to
373   // return isl_stat_error is that an extension node was found.
374   return RetVal == isl_stat_error;
375 }
376 
377 /// Find a named MDNode property in a LoopID.
378 static MDNode *findOptionalNodeOperand(MDNode *LoopMD, StringRef Name) {
379   return dyn_cast_or_null<MDNode>(
380       findMetadataOperand(LoopMD, Name).getValueOr(nullptr));
381 }
382 
383 /// Is this node of type mark?
384 static bool isMark(const isl::schedule_node &Node) {
385   return isl_schedule_node_get_type(Node.get()) == isl_schedule_node_mark;
386 }
387 
388 #ifndef NDEBUG
389 /// Is this node of type band?
390 static bool isBand(const isl::schedule_node &Node) {
391   return isl_schedule_node_get_type(Node.get()) == isl_schedule_node_band;
392 }
393 
394 /// Is this node a band of a single dimension (i.e. could represent a loop)?
395 static bool isBandWithSingleLoop(const isl::schedule_node &Node) {
396 
397   return isBand(Node) && isl_schedule_node_band_n_member(Node.get()) == 1;
398 }
399 #endif
400 
401 /// Create an isl::id representing the output loop after a transformation.
402 static isl::id createGeneratedLoopAttr(isl::ctx Ctx, MDNode *FollowupLoopMD) {
403   // Don't need to id the followup.
404   // TODO: Append llvm.loop.disable_heustistics metadata unless overridden by
405   //       user followup-MD
406   if (!FollowupLoopMD)
407     return {};
408 
409   BandAttr *Attr = new BandAttr();
410   Attr->Metadata = FollowupLoopMD;
411   return getIslLoopAttr(Ctx, Attr);
412 }
413 
414 /// A loop consists of a band and an optional marker that wraps it. Return the
415 /// outermost of the two.
416 
417 /// That is, either the mark or, if there is not mark, the loop itself. Can
418 /// start with either the mark or the band.
419 static isl::schedule_node moveToBandMark(isl::schedule_node BandOrMark) {
420   if (isBandMark(BandOrMark)) {
421     assert(isBandWithSingleLoop(BandOrMark.child(0)));
422     return BandOrMark;
423   }
424   assert(isBandWithSingleLoop(BandOrMark));
425 
426   isl::schedule_node Mark = BandOrMark.parent();
427   if (isBandMark(Mark))
428     return Mark;
429 
430   // Band has no loop marker.
431   return BandOrMark;
432 }
433 
434 static isl::schedule_node removeMark(isl::schedule_node MarkOrBand,
435                                      BandAttr *&Attr) {
436   MarkOrBand = moveToBandMark(MarkOrBand);
437 
438   isl::schedule_node Band;
439   if (isMark(MarkOrBand)) {
440     Attr = getLoopAttr(MarkOrBand.as<isl::schedule_node_mark>().get_id());
441     Band = isl::manage(isl_schedule_node_delete(MarkOrBand.release()));
442   } else {
443     Attr = nullptr;
444     Band = MarkOrBand;
445   }
446 
447   assert(isBandWithSingleLoop(Band));
448   return Band;
449 }
450 
451 /// Remove the mark that wraps a loop. Return the band representing the loop.
452 static isl::schedule_node removeMark(isl::schedule_node MarkOrBand) {
453   BandAttr *Attr;
454   return removeMark(MarkOrBand, Attr);
455 }
456 
457 static isl::schedule_node insertMark(isl::schedule_node Band, isl::id Mark) {
458   assert(isBand(Band));
459   assert(moveToBandMark(Band).is_equal(Band) &&
460          "Don't add a two marks for a band");
461 
462   return Band.insert_mark(Mark).child(0);
463 }
464 
465 /// Return the (one-dimensional) set of numbers that are divisible by @p Factor
466 /// with remainder @p Offset.
467 ///
468 ///  isDivisibleBySet(Ctx, 4, 0) = { [i] : floord(i,4) = 0 }
469 ///  isDivisibleBySet(Ctx, 4, 1) = { [i] : floord(i,4) = 1 }
470 ///
471 static isl::basic_set isDivisibleBySet(isl::ctx &Ctx, long Factor,
472                                        long Offset) {
473   isl::val ValFactor{Ctx, Factor};
474   isl::val ValOffset{Ctx, Offset};
475 
476   isl::space Unispace{Ctx, 0, 1};
477   isl::local_space LUnispace{Unispace};
478   isl::aff AffFactor{LUnispace, ValFactor};
479   isl::aff AffOffset{LUnispace, ValOffset};
480 
481   isl::aff Id = isl::aff::var_on_domain(LUnispace, isl::dim::out, 0);
482   isl::aff DivMul = Id.mod(ValFactor);
483   isl::basic_map Divisible = isl::basic_map::from_aff(DivMul);
484   isl::basic_map Modulo = Divisible.fix_val(isl::dim::out, 0, ValOffset);
485   return Modulo.domain();
486 }
487 
488 /// Make the last dimension of Set to take values from 0 to VectorWidth - 1.
489 ///
490 /// @param Set         A set, which should be modified.
491 /// @param VectorWidth A parameter, which determines the constraint.
492 static isl::set addExtentConstraints(isl::set Set, int VectorWidth) {
493   unsigned Dims = Set.tuple_dim().release();
494   isl::space Space = Set.get_space();
495   isl::local_space LocalSpace = isl::local_space(Space);
496   isl::constraint ExtConstr = isl::constraint::alloc_inequality(LocalSpace);
497   ExtConstr = ExtConstr.set_constant_si(0);
498   ExtConstr = ExtConstr.set_coefficient_si(isl::dim::set, Dims - 1, 1);
499   Set = Set.add_constraint(ExtConstr);
500   ExtConstr = isl::constraint::alloc_inequality(LocalSpace);
501   ExtConstr = ExtConstr.set_constant_si(VectorWidth - 1);
502   ExtConstr = ExtConstr.set_coefficient_si(isl::dim::set, Dims - 1, -1);
503   return Set.add_constraint(ExtConstr);
504 }
505 } // namespace
506 
507 bool polly::isBandMark(const isl::schedule_node &Node) {
508   return isMark(Node) &&
509          isLoopAttr(Node.as<isl::schedule_node_mark>().get_id());
510 }
511 
512 BandAttr *polly::getBandAttr(isl::schedule_node MarkOrBand) {
513   MarkOrBand = moveToBandMark(MarkOrBand);
514   if (!isMark(MarkOrBand))
515     return nullptr;
516 
517   return getLoopAttr(MarkOrBand.as<isl::schedule_node_mark>().get_id());
518 }
519 
520 isl::schedule polly::hoistExtensionNodes(isl::schedule Sched) {
521   // If there is no extension node in the first place, return the original
522   // schedule tree.
523   if (!containsExtensionNode(Sched))
524     return Sched;
525 
526   // Build options can anchor schedule nodes, such that the schedule tree cannot
527   // be modified anymore. Therefore, apply build options after the tree has been
528   // created.
529   CollectASTBuildOptions Collector;
530   Collector.visit(Sched);
531 
532   // Rewrite the schedule tree without extension nodes.
533   ExtensionNodeRewriter Rewriter;
534   isl::schedule NewSched = Rewriter.visitSchedule(Sched);
535 
536   // Reapply the AST build options. The rewriter must not change the iteration
537   // order of bands. Any other node type is ignored.
538   ApplyASTBuildOptions Applicator(Collector.ASTBuildOptions);
539   NewSched = Applicator.visitSchedule(NewSched);
540 
541   return NewSched;
542 }
543 
544 isl::schedule polly::applyFullUnroll(isl::schedule_node BandToUnroll) {
545   isl::ctx Ctx = BandToUnroll.ctx();
546 
547   // Remove the loop's mark, the loop will disappear anyway.
548   BandToUnroll = removeMark(BandToUnroll);
549   assert(isBandWithSingleLoop(BandToUnroll));
550 
551   isl::multi_union_pw_aff PartialSched = isl::manage(
552       isl_schedule_node_band_get_partial_schedule(BandToUnroll.get()));
553   assert(PartialSched.dim(isl::dim::out).release() == 1 &&
554          "Can only unroll a single dimension");
555   isl::union_pw_aff PartialSchedUAff = PartialSched.at(0);
556 
557   isl::union_set Domain = BandToUnroll.get_domain();
558   PartialSchedUAff = PartialSchedUAff.intersect_domain(Domain);
559   isl::union_map PartialSchedUMap =
560       isl::union_map::from(isl::union_pw_multi_aff(PartialSchedUAff));
561 
562   // Enumerator only the scatter elements.
563   isl::union_set ScatterList = PartialSchedUMap.range();
564 
565   // Enumerate all loop iterations.
566   // TODO: Diagnose if not enumerable or depends on a parameter.
567   SmallVector<isl::point, 16> Elts;
568   ScatterList.foreach_point([&Elts](isl::point P) -> isl::stat {
569     Elts.push_back(P);
570     return isl::stat::ok();
571   });
572 
573   // Don't assume that foreach_point returns in execution order.
574   llvm::sort(Elts, [](isl::point P1, isl::point P2) -> bool {
575     isl::val C1 = P1.get_coordinate_val(isl::dim::set, 0);
576     isl::val C2 = P2.get_coordinate_val(isl::dim::set, 0);
577     return C1.lt(C2);
578   });
579 
580   // Convert the points to a sequence of filters.
581   isl::union_set_list List = isl::union_set_list(Ctx, Elts.size());
582   for (isl::point P : Elts) {
583     // Determine the domains that map this scatter element.
584     isl::union_set DomainFilter = PartialSchedUMap.intersect_range(P).domain();
585 
586     List = List.add(DomainFilter);
587   }
588 
589   // Replace original band with unrolled sequence.
590   isl::schedule_node Body =
591       isl::manage(isl_schedule_node_delete(BandToUnroll.release()));
592   Body = Body.insert_sequence(List);
593   return Body.get_schedule();
594 }
595 
596 isl::schedule polly::applyPartialUnroll(isl::schedule_node BandToUnroll,
597                                         int Factor) {
598   assert(Factor > 0 && "Positive unroll factor required");
599   isl::ctx Ctx = BandToUnroll.ctx();
600 
601   // Remove the mark, save the attribute for later use.
602   BandAttr *Attr;
603   BandToUnroll = removeMark(BandToUnroll, Attr);
604   assert(isBandWithSingleLoop(BandToUnroll));
605 
606   isl::multi_union_pw_aff PartialSched = isl::manage(
607       isl_schedule_node_band_get_partial_schedule(BandToUnroll.get()));
608 
609   // { Stmt[] -> [x] }
610   isl::union_pw_aff PartialSchedUAff = PartialSched.at(0);
611 
612   // Here we assume the schedule stride is one and starts with 0, which is not
613   // necessarily the case.
614   isl::union_pw_aff StridedPartialSchedUAff =
615       isl::union_pw_aff::empty(PartialSchedUAff.get_space());
616   isl::val ValFactor{Ctx, Factor};
617   PartialSchedUAff.foreach_pw_aff([&StridedPartialSchedUAff,
618                                    &ValFactor](isl::pw_aff PwAff) -> isl::stat {
619     isl::space Space = PwAff.get_space();
620     isl::set Universe = isl::set::universe(Space.domain());
621     isl::pw_aff AffFactor{Universe, ValFactor};
622     isl::pw_aff DivSchedAff = PwAff.div(AffFactor).floor().mul(AffFactor);
623     StridedPartialSchedUAff = StridedPartialSchedUAff.union_add(DivSchedAff);
624     return isl::stat::ok();
625   });
626 
627   isl::union_set_list List = isl::union_set_list(Ctx, Factor);
628   for (auto i : seq<int>(0, Factor)) {
629     // { Stmt[] -> [x] }
630     isl::union_map UMap =
631         isl::union_map::from(isl::union_pw_multi_aff(PartialSchedUAff));
632 
633     // { [x] }
634     isl::basic_set Divisible = isDivisibleBySet(Ctx, Factor, i);
635 
636     // { Stmt[] }
637     isl::union_set UnrolledDomain = UMap.intersect_range(Divisible).domain();
638 
639     List = List.add(UnrolledDomain);
640   }
641 
642   isl::schedule_node Body =
643       isl::manage(isl_schedule_node_delete(BandToUnroll.copy()));
644   Body = Body.insert_sequence(List);
645   isl::schedule_node NewLoop =
646       Body.insert_partial_schedule(StridedPartialSchedUAff);
647 
648   MDNode *FollowupMD = nullptr;
649   if (Attr && Attr->Metadata)
650     FollowupMD =
651         findOptionalNodeOperand(Attr->Metadata, LLVMLoopUnrollFollowupUnrolled);
652 
653   isl::id NewBandId = createGeneratedLoopAttr(Ctx, FollowupMD);
654   if (!NewBandId.is_null())
655     NewLoop = insertMark(NewLoop, NewBandId);
656 
657   return NewLoop.get_schedule();
658 }
659 
660 isl::set polly::getPartialTilePrefixes(isl::set ScheduleRange,
661                                        int VectorWidth) {
662   isl_size Dims = ScheduleRange.tuple_dim().release();
663   isl::set LoopPrefixes =
664       ScheduleRange.drop_constraints_involving_dims(isl::dim::set, Dims - 1, 1);
665   auto ExtentPrefixes = addExtentConstraints(LoopPrefixes, VectorWidth);
666   isl::set BadPrefixes = ExtentPrefixes.subtract(ScheduleRange);
667   BadPrefixes = BadPrefixes.project_out(isl::dim::set, Dims - 1, 1);
668   LoopPrefixes = LoopPrefixes.project_out(isl::dim::set, Dims - 1, 1);
669   return LoopPrefixes.subtract(BadPrefixes);
670 }
671 
672 isl::union_set polly::getIsolateOptions(isl::set IsolateDomain,
673                                         isl_size OutDimsNum) {
674   isl_size Dims = IsolateDomain.tuple_dim().release();
675   assert(OutDimsNum <= Dims &&
676          "The isl::set IsolateDomain is used to describe the range of schedule "
677          "dimensions values, which should be isolated. Consequently, the "
678          "number of its dimensions should be greater than or equal to the "
679          "number of the schedule dimensions.");
680   isl::map IsolateRelation = isl::map::from_domain(IsolateDomain);
681   IsolateRelation = IsolateRelation.move_dims(isl::dim::out, 0, isl::dim::in,
682                                               Dims - OutDimsNum, OutDimsNum);
683   isl::set IsolateOption = IsolateRelation.wrap();
684   isl::id Id = isl::id::alloc(IsolateOption.ctx(), "isolate", nullptr);
685   IsolateOption = IsolateOption.set_tuple_id(Id);
686   return isl::union_set(IsolateOption);
687 }
688 
689 isl::union_set polly::getDimOptions(isl::ctx Ctx, const char *Option) {
690   isl::space Space(Ctx, 0, 1);
691   auto DimOption = isl::set::universe(Space);
692   auto Id = isl::id::alloc(Ctx, Option, nullptr);
693   DimOption = DimOption.set_tuple_id(Id);
694   return isl::union_set(DimOption);
695 }
696 
697 isl::schedule_node polly::tileNode(isl::schedule_node Node,
698                                    const char *Identifier,
699                                    ArrayRef<int> TileSizes,
700                                    int DefaultTileSize) {
701   auto Space = isl::manage(isl_schedule_node_band_get_space(Node.get()));
702   auto Dims = Space.dim(isl::dim::set);
703   auto Sizes = isl::multi_val::zero(Space);
704   std::string IdentifierString(Identifier);
705   for (auto i : seq<isl_size>(0, Dims.release())) {
706     auto tileSize =
707         i < (isl_size)TileSizes.size() ? TileSizes[i] : DefaultTileSize;
708     Sizes = Sizes.set_val(i, isl::val(Node.ctx(), tileSize));
709   }
710   auto TileLoopMarkerStr = IdentifierString + " - Tiles";
711   auto TileLoopMarker = isl::id::alloc(Node.ctx(), TileLoopMarkerStr, nullptr);
712   Node = Node.insert_mark(TileLoopMarker);
713   Node = Node.child(0);
714   Node =
715       isl::manage(isl_schedule_node_band_tile(Node.release(), Sizes.release()));
716   Node = Node.child(0);
717   auto PointLoopMarkerStr = IdentifierString + " - Points";
718   auto PointLoopMarker =
719       isl::id::alloc(Node.ctx(), PointLoopMarkerStr, nullptr);
720   Node = Node.insert_mark(PointLoopMarker);
721   return Node.child(0);
722 }
723 
724 isl::schedule_node polly::applyRegisterTiling(isl::schedule_node Node,
725                                               ArrayRef<int> TileSizes,
726                                               int DefaultTileSize) {
727   Node = tileNode(Node, "Register tiling", TileSizes, DefaultTileSize);
728   auto Ctx = Node.ctx();
729   return Node.as<isl::schedule_node_band>().set_ast_build_options(
730       isl::union_set(Ctx, "{unroll[x]}"));
731 }
732