1 //===- Support/GICHelper.h -- Helper functions for ISL --------------------===//
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 // Helper functions for isl objects.
10 //
11 //===----------------------------------------------------------------------===//
12 //
13 #ifndef POLLY_SUPPORT_GIC_HELPER_H
14 #define POLLY_SUPPORT_GIC_HELPER_H
15 
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/IR/DiagnosticInfo.h"
18 #include "llvm/Support/raw_ostream.h"
19 #include "isl/ctx.h"
20 #include "isl/isl-noexceptions.h"
21 #include "isl/options.h"
22 
23 namespace polly {
24 
25 /// Translate an llvm::APInt to an isl_val.
26 ///
27 /// Translate the bitsequence without sign information as provided by APInt into
28 /// a signed isl_val type. Depending on the value of @p IsSigned @p Int is
29 /// interpreted as unsigned value or as signed value in two's complement
30 /// representation.
31 ///
32 /// Input IsSigned                 Output
33 ///
34 ///     0        0           ->    0
35 ///     1        0           ->    1
36 ///    00        0           ->    0
37 ///    01        0           ->    1
38 ///    10        0           ->    2
39 ///    11        0           ->    3
40 ///
41 ///     0        1           ->    0
42 ///     1        1           ->   -1
43 ///    00        1           ->    0
44 ///    01        1           ->    1
45 ///    10        1           ->   -2
46 ///    11        1           ->   -1
47 ///
48 /// @param Ctx      The isl_ctx to create the isl_val in.
49 /// @param Int      The integer value to translate.
50 /// @param IsSigned If the APInt should be interpreted as signed or unsigned
51 ///                 value.
52 ///
53 /// @return The isl_val corresponding to @p Int.
54 __isl_give isl_val *isl_valFromAPInt(isl_ctx *Ctx, const llvm::APInt Int,
55                                      bool IsSigned);
56 
57 /// Translate an llvm::APInt to an isl::val.
58 ///
59 /// Translate the bitsequence without sign information as provided by APInt into
60 /// a signed isl::val type. Depending on the value of @p IsSigned @p Int is
61 /// interpreted as unsigned value or as signed value in two's complement
62 /// representation.
63 ///
64 /// Input IsSigned                 Output
65 ///
66 ///     0        0           ->    0
67 ///     1        0           ->    1
68 ///    00        0           ->    0
69 ///    01        0           ->    1
70 ///    10        0           ->    2
71 ///    11        0           ->    3
72 ///
73 ///     0        1           ->    0
74 ///     1        1           ->   -1
75 ///    00        1           ->    0
76 ///    01        1           ->    1
77 ///    10        1           ->   -2
78 ///    11        1           ->   -1
79 ///
80 /// @param Ctx      The isl_ctx to create the isl::val in.
81 /// @param Int      The integer value to translate.
82 /// @param IsSigned If the APInt should be interpreted as signed or unsigned
83 ///                 value.
84 ///
85 /// @return The isl::val corresponding to @p Int.
valFromAPInt(isl_ctx * Ctx,const llvm::APInt Int,bool IsSigned)86 inline isl::val valFromAPInt(isl_ctx *Ctx, const llvm::APInt Int,
87                              bool IsSigned) {
88   return isl::manage(isl_valFromAPInt(Ctx, Int, IsSigned));
89 }
90 
91 /// Translate isl_val to llvm::APInt.
92 ///
93 /// This function can only be called on isl_val values which are integers.
94 /// Calling this function with a non-integral rational, NaN or infinity value
95 /// is not allowed.
96 ///
97 /// As the input isl_val may be negative, the APInt that this function returns
98 /// must always be interpreted as signed two's complement value. The bitwidth of
99 /// the generated APInt is always the minimal bitwidth necessary to model the
100 /// provided integer when interpreting the bit pattern as signed value.
101 ///
102 /// Some example conversions are:
103 ///
104 ///   Input      Bits    Signed  Bitwidth
105 ///       0 ->      0         0         1
106 ///      -1 ->      1        -1         1
107 ///       1 ->     01         1         2
108 ///      -2 ->     10        -2         2
109 ///       2 ->    010         2         3
110 ///      -3 ->    101        -3         3
111 ///       3 ->    011         3         3
112 ///      -4 ->    100        -4         3
113 ///       4 ->   0100         4         4
114 ///
115 /// @param Val The isl val to translate.
116 ///
117 /// @return The APInt value corresponding to @p Val.
118 llvm::APInt APIntFromVal(__isl_take isl_val *Val);
119 
120 /// Translate isl::val to llvm::APInt.
121 ///
122 /// This function can only be called on isl::val values which are integers.
123 /// Calling this function with a non-integral rational, NaN or infinity value
124 /// is not allowed.
125 ///
126 /// As the input isl::val may be negative, the APInt that this function returns
127 /// must always be interpreted as signed two's complement value. The bitwidth of
128 /// the generated APInt is always the minimal bitwidth necessary to model the
129 /// provided integer when interpreting the bit pattern as signed value.
130 ///
131 /// Some example conversions are:
132 ///
133 ///   Input      Bits    Signed  Bitwidth
134 ///       0 ->      0         0         1
135 ///      -1 ->      1        -1         1
136 ///       1 ->     01         1         2
137 ///      -2 ->     10        -2         2
138 ///       2 ->    010         2         3
139 ///      -3 ->    101        -3         3
140 ///       3 ->    011         3         3
141 ///      -4 ->    100        -4         3
142 ///       4 ->   0100         4         4
143 ///
144 /// @param Val The isl val to translate.
145 ///
146 /// @return The APInt value corresponding to @p Val.
APIntFromVal(isl::val V)147 inline llvm::APInt APIntFromVal(isl::val V) {
148   return APIntFromVal(V.release());
149 }
150 
151 /// Get c++ string from Isl objects.
152 //@{
153 #define ISL_CPP_OBJECT_TO_STRING(name)                                         \
154   inline std::string stringFromIslObj(const name &Obj,                         \
155                                       std::string DefaultValue = "") {         \
156     return stringFromIslObj(Obj.get(), DefaultValue);                          \
157   }
158 
159 #define ISL_OBJECT_TO_STRING(name)                                             \
160   std::string stringFromIslObj(__isl_keep isl_##name *Obj,                     \
161                                std::string DefaultValue = "");                 \
162   ISL_CPP_OBJECT_TO_STRING(isl::name)
163 
164 ISL_OBJECT_TO_STRING(aff)
165 ISL_OBJECT_TO_STRING(ast_expr)
166 ISL_OBJECT_TO_STRING(ast_node)
167 ISL_OBJECT_TO_STRING(basic_map)
168 ISL_OBJECT_TO_STRING(basic_set)
169 ISL_OBJECT_TO_STRING(map)
170 ISL_OBJECT_TO_STRING(set)
171 ISL_OBJECT_TO_STRING(id)
172 ISL_OBJECT_TO_STRING(multi_aff)
173 ISL_OBJECT_TO_STRING(multi_pw_aff)
174 ISL_OBJECT_TO_STRING(multi_union_pw_aff)
175 ISL_OBJECT_TO_STRING(point)
176 ISL_OBJECT_TO_STRING(pw_aff)
177 ISL_OBJECT_TO_STRING(pw_multi_aff)
178 ISL_OBJECT_TO_STRING(schedule)
179 ISL_OBJECT_TO_STRING(schedule_node)
180 ISL_OBJECT_TO_STRING(space)
181 ISL_OBJECT_TO_STRING(union_access_info)
182 ISL_OBJECT_TO_STRING(union_flow)
183 ISL_OBJECT_TO_STRING(union_set)
184 ISL_OBJECT_TO_STRING(union_map)
185 ISL_OBJECT_TO_STRING(union_pw_aff)
186 ISL_OBJECT_TO_STRING(union_pw_multi_aff)
187 //@}
188 
189 inline llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
190                                      __isl_keep isl_union_map *Map) {
191   OS << polly::stringFromIslObj(Map, "null");
192   return OS;
193 }
194 
195 inline llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
196                                      __isl_keep isl_map *Map) {
197   OS << polly::stringFromIslObj(Map, "null");
198   return OS;
199 }
200 
201 inline llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
202                                      __isl_keep isl_set *Set) {
203   OS << polly::stringFromIslObj(Set, "null");
204   return OS;
205 }
206 
207 inline llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
208                                      __isl_keep isl_pw_aff *Map) {
209   OS << polly::stringFromIslObj(Map, "null");
210   return OS;
211 }
212 
213 inline llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
214                                      __isl_keep isl_pw_multi_aff *PMA) {
215   OS << polly::stringFromIslObj(PMA, "null");
216   return OS;
217 }
218 
219 inline llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
220                                      __isl_keep isl_multi_aff *MA) {
221   OS << polly::stringFromIslObj(MA, "null");
222   return OS;
223 }
224 
225 inline llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
226                                      __isl_keep isl_union_pw_multi_aff *UPMA) {
227   OS << polly::stringFromIslObj(UPMA, "null");
228   return OS;
229 }
230 
231 inline llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
232                                      __isl_keep isl_schedule *Schedule) {
233   OS << polly::stringFromIslObj(Schedule, "null");
234   return OS;
235 }
236 
237 inline llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
238                                      __isl_keep isl_space *Space) {
239   OS << polly::stringFromIslObj(Space, "null");
240   return OS;
241 }
242 
243 /// Combine Prefix, Val (or Number) and Suffix to an isl-compatible name.
244 ///
245 /// In case @p UseInstructionNames is set, this function returns:
246 ///
247 /// @p Prefix + "_" + @p Val->getName() + @p Suffix
248 ///
249 /// otherwise
250 ///
251 /// @p Prefix + to_string(Number) + @p Suffix
252 ///
253 /// We ignore the value names by default, as they may change between release
254 /// and debug mode and can consequently not be used when aiming for reproducible
255 /// builds. However, for debugging named statements are often helpful, hence
256 /// we allow their optional use.
257 std::string getIslCompatibleName(const std::string &Prefix,
258                                  const llvm::Value *Val, long Number,
259                                  const std::string &Suffix,
260                                  bool UseInstructionNames);
261 
262 /// Combine Prefix, Name (or Number) and Suffix to an isl-compatible name.
263 ///
264 /// In case @p UseInstructionNames is set, this function returns:
265 ///
266 /// @p Prefix + "_" + Name + @p Suffix
267 ///
268 /// otherwise
269 ///
270 /// @p Prefix + to_string(Number) + @p Suffix
271 ///
272 /// We ignore @p Name by default, as they may change between release
273 /// and debug mode and can consequently not be used when aiming for reproducible
274 /// builds. However, for debugging named statements are often helpful, hence
275 /// we allow their optional use.
276 std::string getIslCompatibleName(const std::string &Prefix,
277                                  const std::string &Middle, long Number,
278                                  const std::string &Suffix,
279                                  bool UseInstructionNames);
280 
281 std::string getIslCompatibleName(const std::string &Prefix,
282                                  const std::string &Middle,
283                                  const std::string &Suffix);
284 
285 inline llvm::DiagnosticInfoOptimizationBase &
286 operator<<(llvm::DiagnosticInfoOptimizationBase &OS,
287            const isl::union_map &Obj) {
288   OS << stringFromIslObj(Obj);
289   return OS;
290 }
291 
292 /// Scope guard for code that allows arbitrary isl function to return an error
293 /// if the max-operations quota exceeds.
294 ///
295 /// This allows to opt-in code sections that have known long executions times.
296 /// code not in a hot path can continue to assume that no unexpected error
297 /// occurs.
298 ///
299 /// This is typically used inside a nested IslMaxOperationsGuard scope. The
300 /// IslMaxOperationsGuard defines the number of allowed base operations for some
301 /// code, IslQuotaScope defines where it is allowed to return an error result.
302 class IslQuotaScope {
303   isl_ctx *IslCtx;
304   int OldOnError;
305 
306 public:
IslQuotaScope()307   IslQuotaScope() : IslCtx(nullptr) {}
308   IslQuotaScope(const IslQuotaScope &) = delete;
IslQuotaScope(IslQuotaScope && Other)309   IslQuotaScope(IslQuotaScope &&Other)
310       : IslCtx(Other.IslCtx), OldOnError(Other.OldOnError) {
311     Other.IslCtx = nullptr;
312   }
313   const IslQuotaScope &operator=(IslQuotaScope &&Other) {
314     std::swap(this->IslCtx, Other.IslCtx);
315     std::swap(this->OldOnError, Other.OldOnError);
316     return *this;
317   }
318 
319   /// Enter a quota-aware scope.
320   ///
321   /// Should not be used directly. Use IslMaxOperationsGuard::enter() instead.
IslQuotaScope(isl_ctx * IslCtx,unsigned long LocalMaxOps)322   explicit IslQuotaScope(isl_ctx *IslCtx, unsigned long LocalMaxOps)
323       : IslCtx(IslCtx) {
324     assert(IslCtx);
325     assert(isl_ctx_get_max_operations(IslCtx) == 0 && "Incorrect nesting");
326     if (LocalMaxOps == 0) {
327       this->IslCtx = nullptr;
328       return;
329     }
330 
331     OldOnError = isl_options_get_on_error(IslCtx);
332     isl_options_set_on_error(IslCtx, ISL_ON_ERROR_CONTINUE);
333     isl_ctx_reset_error(IslCtx);
334     isl_ctx_set_max_operations(IslCtx, LocalMaxOps);
335   }
336 
~IslQuotaScope()337   ~IslQuotaScope() {
338     if (!IslCtx)
339       return;
340 
341     assert(isl_ctx_get_max_operations(IslCtx) > 0 && "Incorrect nesting");
342     assert(isl_options_get_on_error(IslCtx) == ISL_ON_ERROR_CONTINUE &&
343            "Incorrect nesting");
344     isl_ctx_set_max_operations(IslCtx, 0);
345     isl_options_set_on_error(IslCtx, OldOnError);
346   }
347 
348   /// Return whether the current quota has exceeded.
hasQuotaExceeded()349   bool hasQuotaExceeded() const {
350     if (!IslCtx)
351       return false;
352 
353     return isl_ctx_last_error(IslCtx) == isl_error_quota;
354   }
355 };
356 
357 /// Scoped limit of ISL operations.
358 ///
359 /// Limits the number of ISL operations during the lifetime of this object. The
360 /// idea is to use this as an RAII guard for the scope where the code is aware
361 /// that ISL can return errors even when all input is valid. After leaving the
362 /// scope, it will return to the error setting as it was before. That also means
363 /// that the error setting should not be changed while in that scope.
364 ///
365 /// Such scopes are not allowed to be nested because the previous operations
366 /// counter cannot be reset to the previous state, or one that adds the
367 /// operations while being in the nested scope. Use therefore is only allowed
368 /// while currently a no operations-limit is active.
369 class IslMaxOperationsGuard {
370 private:
371   /// The ISL context to set the operations limit.
372   ///
373   /// If set to nullptr, there is no need for any action at the end of the
374   /// scope.
375   isl_ctx *IslCtx;
376 
377   /// Maximum number of operations for the scope.
378   unsigned long LocalMaxOps;
379 
380   /// When AutoEnter is enabled, holds the IslQuotaScope object.
381   IslQuotaScope TopLevelScope;
382 
383 public:
384   /// Enter a max operations scope.
385   ///
386   /// @param IslCtx      The ISL context to set the operations limit for.
387   /// @param LocalMaxOps Maximum number of operations allowed in the
388   ///                    scope. If set to zero, no operations limit is enforced.
389   /// @param AutoEnter   If true, automatically enters an IslQuotaScope such
390   ///                    that isl operations may return quota errors
391   ///                    immediately. If false, only starts the operations
392   ///                    counter, but isl does not return quota errors before
393   ///                    calling enter().
394   IslMaxOperationsGuard(isl_ctx *IslCtx, unsigned long LocalMaxOps,
395                         bool AutoEnter = true)
IslCtx(IslCtx)396       : IslCtx(IslCtx), LocalMaxOps(LocalMaxOps) {
397     assert(IslCtx);
398     assert(isl_ctx_get_max_operations(IslCtx) == 0 &&
399            "Nested max operations not supported");
400 
401     // Users of this guard may check whether the last error was isl_error_quota.
402     // Reset the last error such that a previous out-of-quota error is not
403     // mistaken to have occurred in the in this quota, even if the max number of
404     // operations is set to infinite (LocalMaxOps == 0).
405     isl_ctx_reset_error(IslCtx);
406 
407     if (LocalMaxOps == 0) {
408       // No limit on operations; also disable restoring on_error/max_operations.
409       this->IslCtx = nullptr;
410       return;
411     }
412 
413     isl_ctx_reset_operations(IslCtx);
414     TopLevelScope = enter(AutoEnter);
415   }
416 
417   /// Enter a scope that can handle out-of-quota errors.
418   ///
419   /// @param AllowReturnNull Whether the scoped code can handle out-of-quota
420   ///                        errors. If false, returns a dummy scope object that
421   ///                        does nothing.
422   IslQuotaScope enter(bool AllowReturnNull = true) {
423     return AllowReturnNull && IslCtx ? IslQuotaScope(IslCtx, LocalMaxOps)
424                                      : IslQuotaScope();
425   }
426 
427   /// Return whether the current quota has exceeded.
hasQuotaExceeded()428   bool hasQuotaExceeded() const {
429     if (!IslCtx)
430       return false;
431 
432     return isl_ctx_last_error(IslCtx) == isl_error_quota;
433   }
434 };
435 } // end namespace polly
436 
437 #endif
438