1 //===- BuiltinTypes.cpp - MLIR Builtin Type Classes -----------------------===//
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 #include "mlir/IR/BuiltinTypes.h"
10 #include "TypeDetail.h"
11 #include "mlir/IR/AffineExpr.h"
12 #include "mlir/IR/AffineMap.h"
13 #include "mlir/IR/Diagnostics.h"
14 #include "mlir/IR/Dialect.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/BitVector.h"
17 #include "llvm/ADT/Sequence.h"
18 #include "llvm/ADT/Twine.h"
19 
20 using namespace mlir;
21 using namespace mlir::detail;
22 
23 //===----------------------------------------------------------------------===//
24 /// Tablegen Type Definitions
25 //===----------------------------------------------------------------------===//
26 
27 #define GET_TYPEDEF_CLASSES
28 #include "mlir/IR/BuiltinTypes.cpp.inc"
29 
30 //===----------------------------------------------------------------------===//
31 /// ComplexType
32 //===----------------------------------------------------------------------===//
33 
34 /// Verify the construction of an integer type.
35 LogicalResult ComplexType::verifyConstructionInvariants(Location loc,
36                                                         Type elementType) {
37   if (!elementType.isIntOrFloat())
38     return emitError(loc, "invalid element type for complex");
39   return success();
40 }
41 
42 //===----------------------------------------------------------------------===//
43 // Integer Type
44 //===----------------------------------------------------------------------===//
45 
46 // static constexpr must have a definition (until in C++17 and inline variable).
47 constexpr unsigned IntegerType::kMaxWidth;
48 
49 /// Verify the construction of an integer type.
50 LogicalResult
51 IntegerType::verifyConstructionInvariants(Location loc, unsigned width,
52                                           SignednessSemantics signedness) {
53   if (width > IntegerType::kMaxWidth) {
54     return emitError(loc) << "integer bitwidth is limited to "
55                           << IntegerType::kMaxWidth << " bits";
56   }
57   return success();
58 }
59 
60 unsigned IntegerType::getWidth() const { return getImpl()->width; }
61 
62 IntegerType::SignednessSemantics IntegerType::getSignedness() const {
63   return getImpl()->signedness;
64 }
65 
66 IntegerType IntegerType::scaleElementBitwidth(unsigned scale) {
67   if (!scale)
68     return IntegerType();
69   return IntegerType::get(getContext(), scale * getWidth(), getSignedness());
70 }
71 
72 //===----------------------------------------------------------------------===//
73 // Float Type
74 //===----------------------------------------------------------------------===//
75 
76 unsigned FloatType::getWidth() {
77   if (isa<Float16Type, BFloat16Type>())
78     return 16;
79   if (isa<Float32Type>())
80     return 32;
81   if (isa<Float64Type>())
82     return 64;
83   if (isa<Float80Type>())
84     return 80;
85   if (isa<Float128Type>())
86     return 128;
87   llvm_unreachable("unexpected float type");
88 }
89 
90 /// Returns the floating semantics for the given type.
91 const llvm::fltSemantics &FloatType::getFloatSemantics() {
92   if (isa<BFloat16Type>())
93     return APFloat::BFloat();
94   if (isa<Float16Type>())
95     return APFloat::IEEEhalf();
96   if (isa<Float32Type>())
97     return APFloat::IEEEsingle();
98   if (isa<Float64Type>())
99     return APFloat::IEEEdouble();
100   if (isa<Float80Type>())
101     return APFloat::x87DoubleExtended();
102   if (isa<Float128Type>())
103     return APFloat::IEEEquad();
104   llvm_unreachable("non-floating point type used");
105 }
106 
107 FloatType FloatType::scaleElementBitwidth(unsigned scale) {
108   if (!scale)
109     return FloatType();
110   MLIRContext *ctx = getContext();
111   if (isF16() || isBF16()) {
112     if (scale == 2)
113       return FloatType::getF32(ctx);
114     if (scale == 4)
115       return FloatType::getF64(ctx);
116   }
117   if (isF32())
118     if (scale == 2)
119       return FloatType::getF64(ctx);
120   return FloatType();
121 }
122 
123 //===----------------------------------------------------------------------===//
124 // FunctionType
125 //===----------------------------------------------------------------------===//
126 
127 unsigned FunctionType::getNumInputs() const { return getImpl()->numInputs; }
128 
129 ArrayRef<Type> FunctionType::getInputs() const {
130   return getImpl()->getInputs();
131 }
132 
133 unsigned FunctionType::getNumResults() const { return getImpl()->numResults; }
134 
135 ArrayRef<Type> FunctionType::getResults() const {
136   return getImpl()->getResults();
137 }
138 
139 /// Helper to call a callback once on each index in the range
140 /// [0, `totalIndices`), *except* for the indices given in `indices`.
141 /// `indices` is allowed to have duplicates and can be in any order.
142 inline void iterateIndicesExcept(unsigned totalIndices,
143                                  ArrayRef<unsigned> indices,
144                                  function_ref<void(unsigned)> callback) {
145   llvm::BitVector skipIndices(totalIndices);
146   for (unsigned i : indices)
147     skipIndices.set(i);
148 
149   for (unsigned i = 0; i < totalIndices; ++i)
150     if (!skipIndices.test(i))
151       callback(i);
152 }
153 
154 /// Returns a new function type without the specified arguments and results.
155 FunctionType
156 FunctionType::getWithoutArgsAndResults(ArrayRef<unsigned> argIndices,
157                                        ArrayRef<unsigned> resultIndices) {
158   ArrayRef<Type> newInputTypes = getInputs();
159   SmallVector<Type, 4> newInputTypesBuffer;
160   if (!argIndices.empty()) {
161     unsigned originalNumArgs = getNumInputs();
162     iterateIndicesExcept(originalNumArgs, argIndices, [&](unsigned i) {
163       newInputTypesBuffer.emplace_back(getInput(i));
164     });
165     newInputTypes = newInputTypesBuffer;
166   }
167 
168   ArrayRef<Type> newResultTypes = getResults();
169   SmallVector<Type, 4> newResultTypesBuffer;
170   if (!resultIndices.empty()) {
171     unsigned originalNumResults = getNumResults();
172     iterateIndicesExcept(originalNumResults, resultIndices, [&](unsigned i) {
173       newResultTypesBuffer.emplace_back(getResult(i));
174     });
175     newResultTypes = newResultTypesBuffer;
176   }
177 
178   return get(getContext(), newInputTypes, newResultTypes);
179 }
180 
181 //===----------------------------------------------------------------------===//
182 // OpaqueType
183 //===----------------------------------------------------------------------===//
184 
185 /// Verify the construction of an opaque type.
186 LogicalResult OpaqueType::verifyConstructionInvariants(Location loc,
187                                                        Identifier dialect,
188                                                        StringRef typeData) {
189   if (!Dialect::isValidNamespace(dialect.strref()))
190     return emitError(loc, "invalid dialect namespace '") << dialect << "'";
191   return success();
192 }
193 
194 //===----------------------------------------------------------------------===//
195 // ShapedType
196 //===----------------------------------------------------------------------===//
197 constexpr int64_t ShapedType::kDynamicSize;
198 constexpr int64_t ShapedType::kDynamicStrideOrOffset;
199 
200 Type ShapedType::getElementType() const {
201   return static_cast<ImplType *>(impl)->elementType;
202 }
203 
204 unsigned ShapedType::getElementTypeBitWidth() const {
205   return getElementType().getIntOrFloatBitWidth();
206 }
207 
208 int64_t ShapedType::getNumElements() const {
209   assert(hasStaticShape() && "cannot get element count of dynamic shaped type");
210   auto shape = getShape();
211   int64_t num = 1;
212   for (auto dim : shape)
213     num *= dim;
214   return num;
215 }
216 
217 int64_t ShapedType::getRank() const {
218   assert(hasRank() && "cannot query rank of unranked shaped type");
219   return getShape().size();
220 }
221 
222 bool ShapedType::hasRank() const {
223   return !isa<UnrankedMemRefType, UnrankedTensorType>();
224 }
225 
226 int64_t ShapedType::getDimSize(unsigned idx) const {
227   assert(idx < getRank() && "invalid index for shaped type");
228   return getShape()[idx];
229 }
230 
231 bool ShapedType::isDynamicDim(unsigned idx) const {
232   assert(idx < getRank() && "invalid index for shaped type");
233   return isDynamic(getShape()[idx]);
234 }
235 
236 unsigned ShapedType::getDynamicDimIndex(unsigned index) const {
237   assert(index < getRank() && "invalid index");
238   assert(ShapedType::isDynamic(getDimSize(index)) && "invalid index");
239   return llvm::count_if(getShape().take_front(index), ShapedType::isDynamic);
240 }
241 
242 /// Get the number of bits require to store a value of the given shaped type.
243 /// Compute the value recursively since tensors are allowed to have vectors as
244 /// elements.
245 int64_t ShapedType::getSizeInBits() const {
246   assert(hasStaticShape() &&
247          "cannot get the bit size of an aggregate with a dynamic shape");
248 
249   auto elementType = getElementType();
250   if (elementType.isIntOrFloat())
251     return elementType.getIntOrFloatBitWidth() * getNumElements();
252 
253   if (auto complexType = elementType.dyn_cast<ComplexType>()) {
254     elementType = complexType.getElementType();
255     return elementType.getIntOrFloatBitWidth() * getNumElements() * 2;
256   }
257 
258   // Tensors can have vectors and other tensors as elements, other shaped types
259   // cannot.
260   assert(isa<TensorType>() && "unsupported element type");
261   assert((elementType.isa<VectorType, TensorType>()) &&
262          "unsupported tensor element type");
263   return getNumElements() * elementType.cast<ShapedType>().getSizeInBits();
264 }
265 
266 ArrayRef<int64_t> ShapedType::getShape() const {
267   if (auto vectorType = dyn_cast<VectorType>())
268     return vectorType.getShape();
269   if (auto tensorType = dyn_cast<RankedTensorType>())
270     return tensorType.getShape();
271   return cast<MemRefType>().getShape();
272 }
273 
274 int64_t ShapedType::getNumDynamicDims() const {
275   return llvm::count_if(getShape(), isDynamic);
276 }
277 
278 bool ShapedType::hasStaticShape() const {
279   return hasRank() && llvm::none_of(getShape(), isDynamic);
280 }
281 
282 bool ShapedType::hasStaticShape(ArrayRef<int64_t> shape) const {
283   return hasStaticShape() && getShape() == shape;
284 }
285 
286 //===----------------------------------------------------------------------===//
287 // VectorType
288 //===----------------------------------------------------------------------===//
289 
290 VectorType VectorType::get(ArrayRef<int64_t> shape, Type elementType) {
291   return Base::get(elementType.getContext(), shape, elementType);
292 }
293 
294 VectorType VectorType::getChecked(Location location, ArrayRef<int64_t> shape,
295                                   Type elementType) {
296   return Base::getChecked(location, shape, elementType);
297 }
298 
299 LogicalResult VectorType::verifyConstructionInvariants(Location loc,
300                                                        ArrayRef<int64_t> shape,
301                                                        Type elementType) {
302   if (shape.empty())
303     return emitError(loc, "vector types must have at least one dimension");
304 
305   if (!isValidElementType(elementType))
306     return emitError(loc, "vector elements must be int or float type");
307 
308   if (any_of(shape, [](int64_t i) { return i <= 0; }))
309     return emitError(loc, "vector types must have positive constant sizes");
310 
311   return success();
312 }
313 
314 ArrayRef<int64_t> VectorType::getShape() const { return getImpl()->getShape(); }
315 
316 VectorType VectorType::scaleElementBitwidth(unsigned scale) {
317   if (!scale)
318     return VectorType();
319   if (auto et = getElementType().dyn_cast<IntegerType>())
320     if (auto scaledEt = et.scaleElementBitwidth(scale))
321       return VectorType::get(getShape(), scaledEt);
322   if (auto et = getElementType().dyn_cast<FloatType>())
323     if (auto scaledEt = et.scaleElementBitwidth(scale))
324       return VectorType::get(getShape(), scaledEt);
325   return VectorType();
326 }
327 
328 //===----------------------------------------------------------------------===//
329 // TensorType
330 //===----------------------------------------------------------------------===//
331 
332 // Check if "elementType" can be an element type of a tensor. Emit errors if
333 // location is not nullptr.  Returns failure if check failed.
334 static LogicalResult checkTensorElementType(Location location,
335                                             Type elementType) {
336   if (!TensorType::isValidElementType(elementType))
337     return emitError(location, "invalid tensor element type: ") << elementType;
338   return success();
339 }
340 
341 /// Return true if the specified element type is ok in a tensor.
342 bool TensorType::isValidElementType(Type type) {
343   // Note: Non standard/builtin types are allowed to exist within tensor
344   // types. Dialects are expected to verify that tensor types have a valid
345   // element type within that dialect.
346   return type.isa<ComplexType, FloatType, IntegerType, OpaqueType, VectorType,
347                   IndexType>() ||
348          !type.getDialect().getNamespace().empty();
349 }
350 
351 //===----------------------------------------------------------------------===//
352 // RankedTensorType
353 //===----------------------------------------------------------------------===//
354 
355 RankedTensorType RankedTensorType::get(ArrayRef<int64_t> shape,
356                                        Type elementType) {
357   return Base::get(elementType.getContext(), shape, elementType);
358 }
359 
360 RankedTensorType RankedTensorType::getChecked(Location location,
361                                               ArrayRef<int64_t> shape,
362                                               Type elementType) {
363   return Base::getChecked(location, shape, elementType);
364 }
365 
366 LogicalResult RankedTensorType::verifyConstructionInvariants(
367     Location loc, ArrayRef<int64_t> shape, Type elementType) {
368   for (int64_t s : shape) {
369     if (s < -1)
370       return emitError(loc, "invalid tensor dimension size");
371   }
372   return checkTensorElementType(loc, elementType);
373 }
374 
375 ArrayRef<int64_t> RankedTensorType::getShape() const {
376   return getImpl()->getShape();
377 }
378 
379 //===----------------------------------------------------------------------===//
380 // UnrankedTensorType
381 //===----------------------------------------------------------------------===//
382 
383 UnrankedTensorType UnrankedTensorType::get(Type elementType) {
384   return Base::get(elementType.getContext(), elementType);
385 }
386 
387 UnrankedTensorType UnrankedTensorType::getChecked(Location location,
388                                                   Type elementType) {
389   return Base::getChecked(location, elementType);
390 }
391 
392 LogicalResult
393 UnrankedTensorType::verifyConstructionInvariants(Location loc,
394                                                  Type elementType) {
395   return checkTensorElementType(loc, elementType);
396 }
397 
398 //===----------------------------------------------------------------------===//
399 // BaseMemRefType
400 //===----------------------------------------------------------------------===//
401 
402 unsigned BaseMemRefType::getMemorySpace() const {
403   return static_cast<ImplType *>(impl)->memorySpace;
404 }
405 
406 //===----------------------------------------------------------------------===//
407 // MemRefType
408 //===----------------------------------------------------------------------===//
409 
410 /// Get or create a new MemRefType based on shape, element type, affine
411 /// map composition, and memory space.  Assumes the arguments define a
412 /// well-formed MemRef type.  Use getChecked to gracefully handle MemRefType
413 /// construction failures.
414 MemRefType MemRefType::get(ArrayRef<int64_t> shape, Type elementType,
415                            ArrayRef<AffineMap> affineMapComposition,
416                            unsigned memorySpace) {
417   auto result = getImpl(shape, elementType, affineMapComposition, memorySpace,
418                         /*location=*/llvm::None);
419   assert(result && "Failed to construct instance of MemRefType.");
420   return result;
421 }
422 
423 /// Get or create a new MemRefType based on shape, element type, affine
424 /// map composition, and memory space declared at the given location.
425 /// If the location is unknown, the last argument should be an instance of
426 /// UnknownLoc.  If the MemRefType defined by the arguments would be
427 /// ill-formed, emits errors (to the handler registered with the context or to
428 /// the error stream) and returns nullptr.
429 MemRefType MemRefType::getChecked(Location location, ArrayRef<int64_t> shape,
430                                   Type elementType,
431                                   ArrayRef<AffineMap> affineMapComposition,
432                                   unsigned memorySpace) {
433   return getImpl(shape, elementType, affineMapComposition, memorySpace,
434                  location);
435 }
436 
437 /// Get or create a new MemRefType defined by the arguments.  If the resulting
438 /// type would be ill-formed, return nullptr.  If the location is provided,
439 /// emit detailed error messages.  To emit errors when the location is unknown,
440 /// pass in an instance of UnknownLoc.
441 MemRefType MemRefType::getImpl(ArrayRef<int64_t> shape, Type elementType,
442                                ArrayRef<AffineMap> affineMapComposition,
443                                unsigned memorySpace,
444                                Optional<Location> location) {
445   auto *context = elementType.getContext();
446 
447   if (!BaseMemRefType::isValidElementType(elementType))
448     return emitOptionalError(location, "invalid memref element type"),
449            MemRefType();
450 
451   for (int64_t s : shape) {
452     // Negative sizes are not allowed except for `-1` that means dynamic size.
453     if (s < -1)
454       return emitOptionalError(location, "invalid memref size"), MemRefType();
455   }
456 
457   // Check that the structure of the composition is valid, i.e. that each
458   // subsequent affine map has as many inputs as the previous map has results.
459   // Take the dimensionality of the MemRef for the first map.
460   auto dim = shape.size();
461   unsigned i = 0;
462   for (const auto &affineMap : affineMapComposition) {
463     if (affineMap.getNumDims() != dim) {
464       if (location)
465         emitError(*location)
466             << "memref affine map dimension mismatch between "
467             << (i == 0 ? Twine("memref rank") : "affine map " + Twine(i))
468             << " and affine map" << i + 1 << ": " << dim
469             << " != " << affineMap.getNumDims();
470       return nullptr;
471     }
472 
473     dim = affineMap.getNumResults();
474     ++i;
475   }
476 
477   // Drop identity maps from the composition.
478   // This may lead to the composition becoming empty, which is interpreted as an
479   // implicit identity.
480   SmallVector<AffineMap, 2> cleanedAffineMapComposition;
481   for (const auto &map : affineMapComposition) {
482     if (map.isIdentity())
483       continue;
484     cleanedAffineMapComposition.push_back(map);
485   }
486 
487   return Base::get(context, shape, elementType, cleanedAffineMapComposition,
488                    memorySpace);
489 }
490 
491 ArrayRef<int64_t> MemRefType::getShape() const { return getImpl()->getShape(); }
492 
493 ArrayRef<AffineMap> MemRefType::getAffineMaps() const {
494   return getImpl()->getAffineMaps();
495 }
496 
497 //===----------------------------------------------------------------------===//
498 // UnrankedMemRefType
499 //===----------------------------------------------------------------------===//
500 
501 UnrankedMemRefType UnrankedMemRefType::get(Type elementType,
502                                            unsigned memorySpace) {
503   return Base::get(elementType.getContext(), elementType, memorySpace);
504 }
505 
506 UnrankedMemRefType UnrankedMemRefType::getChecked(Location location,
507                                                   Type elementType,
508                                                   unsigned memorySpace) {
509   return Base::getChecked(location, elementType, memorySpace);
510 }
511 
512 LogicalResult
513 UnrankedMemRefType::verifyConstructionInvariants(Location loc, Type elementType,
514                                                  unsigned memorySpace) {
515   if (!BaseMemRefType::isValidElementType(elementType))
516     return emitError(loc, "invalid memref element type");
517   return success();
518 }
519 
520 // Fallback cases for terminal dim/sym/cst that are not part of a binary op (
521 // i.e. single term). Accumulate the AffineExpr into the existing one.
522 static void extractStridesFromTerm(AffineExpr e,
523                                    AffineExpr multiplicativeFactor,
524                                    MutableArrayRef<AffineExpr> strides,
525                                    AffineExpr &offset) {
526   if (auto dim = e.dyn_cast<AffineDimExpr>())
527     strides[dim.getPosition()] =
528         strides[dim.getPosition()] + multiplicativeFactor;
529   else
530     offset = offset + e * multiplicativeFactor;
531 }
532 
533 /// Takes a single AffineExpr `e` and populates the `strides` array with the
534 /// strides expressions for each dim position.
535 /// The convention is that the strides for dimensions d0, .. dn appear in
536 /// order to make indexing intuitive into the result.
537 static LogicalResult extractStrides(AffineExpr e,
538                                     AffineExpr multiplicativeFactor,
539                                     MutableArrayRef<AffineExpr> strides,
540                                     AffineExpr &offset) {
541   auto bin = e.dyn_cast<AffineBinaryOpExpr>();
542   if (!bin) {
543     extractStridesFromTerm(e, multiplicativeFactor, strides, offset);
544     return success();
545   }
546 
547   if (bin.getKind() == AffineExprKind::CeilDiv ||
548       bin.getKind() == AffineExprKind::FloorDiv ||
549       bin.getKind() == AffineExprKind::Mod)
550     return failure();
551 
552   if (bin.getKind() == AffineExprKind::Mul) {
553     auto dim = bin.getLHS().dyn_cast<AffineDimExpr>();
554     if (dim) {
555       strides[dim.getPosition()] =
556           strides[dim.getPosition()] + bin.getRHS() * multiplicativeFactor;
557       return success();
558     }
559     // LHS and RHS may both contain complex expressions of dims. Try one path
560     // and if it fails try the other. This is guaranteed to succeed because
561     // only one path may have a `dim`, otherwise this is not an AffineExpr in
562     // the first place.
563     if (bin.getLHS().isSymbolicOrConstant())
564       return extractStrides(bin.getRHS(), multiplicativeFactor * bin.getLHS(),
565                             strides, offset);
566     return extractStrides(bin.getLHS(), multiplicativeFactor * bin.getRHS(),
567                           strides, offset);
568   }
569 
570   if (bin.getKind() == AffineExprKind::Add) {
571     auto res1 =
572         extractStrides(bin.getLHS(), multiplicativeFactor, strides, offset);
573     auto res2 =
574         extractStrides(bin.getRHS(), multiplicativeFactor, strides, offset);
575     return success(succeeded(res1) && succeeded(res2));
576   }
577 
578   llvm_unreachable("unexpected binary operation");
579 }
580 
581 LogicalResult mlir::getStridesAndOffset(MemRefType t,
582                                         SmallVectorImpl<AffineExpr> &strides,
583                                         AffineExpr &offset) {
584   auto affineMaps = t.getAffineMaps();
585   // For now strides are only computed on a single affine map with a single
586   // result (i.e. the closed subset of linearization maps that are compatible
587   // with striding semantics).
588   // TODO: support more forms on a per-need basis.
589   if (affineMaps.size() > 1)
590     return failure();
591   if (affineMaps.size() == 1 && affineMaps[0].getNumResults() != 1)
592     return failure();
593 
594   auto zero = getAffineConstantExpr(0, t.getContext());
595   auto one = getAffineConstantExpr(1, t.getContext());
596   offset = zero;
597   strides.assign(t.getRank(), zero);
598 
599   AffineMap m;
600   if (!affineMaps.empty()) {
601     m = affineMaps.front();
602     assert(!m.isIdentity() && "unexpected identity map");
603   }
604 
605   // Canonical case for empty map.
606   if (!m) {
607     // 0-D corner case, offset is already 0.
608     if (t.getRank() == 0)
609       return success();
610     auto stridedExpr =
611         makeCanonicalStridedLayoutExpr(t.getShape(), t.getContext());
612     if (succeeded(extractStrides(stridedExpr, one, strides, offset)))
613       return success();
614     assert(false && "unexpected failure: extract strides in canonical layout");
615   }
616 
617   // Non-canonical case requires more work.
618   auto stridedExpr =
619       simplifyAffineExpr(m.getResult(0), m.getNumDims(), m.getNumSymbols());
620   if (failed(extractStrides(stridedExpr, one, strides, offset))) {
621     offset = AffineExpr();
622     strides.clear();
623     return failure();
624   }
625 
626   // Simplify results to allow folding to constants and simple checks.
627   unsigned numDims = m.getNumDims();
628   unsigned numSymbols = m.getNumSymbols();
629   offset = simplifyAffineExpr(offset, numDims, numSymbols);
630   for (auto &stride : strides)
631     stride = simplifyAffineExpr(stride, numDims, numSymbols);
632 
633   /// In practice, a strided memref must be internally non-aliasing. Test
634   /// against 0 as a proxy.
635   /// TODO: static cases can have more advanced checks.
636   /// TODO: dynamic cases would require a way to compare symbolic
637   /// expressions and would probably need an affine set context propagated
638   /// everywhere.
639   if (llvm::any_of(strides, [](AffineExpr e) {
640         return e == getAffineConstantExpr(0, e.getContext());
641       })) {
642     offset = AffineExpr();
643     strides.clear();
644     return failure();
645   }
646 
647   return success();
648 }
649 
650 LogicalResult mlir::getStridesAndOffset(MemRefType t,
651                                         SmallVectorImpl<int64_t> &strides,
652                                         int64_t &offset) {
653   AffineExpr offsetExpr;
654   SmallVector<AffineExpr, 4> strideExprs;
655   if (failed(::getStridesAndOffset(t, strideExprs, offsetExpr)))
656     return failure();
657   if (auto cst = offsetExpr.dyn_cast<AffineConstantExpr>())
658     offset = cst.getValue();
659   else
660     offset = ShapedType::kDynamicStrideOrOffset;
661   for (auto e : strideExprs) {
662     if (auto c = e.dyn_cast<AffineConstantExpr>())
663       strides.push_back(c.getValue());
664     else
665       strides.push_back(ShapedType::kDynamicStrideOrOffset);
666   }
667   return success();
668 }
669 
670 //===----------------------------------------------------------------------===//
671 /// TupleType
672 //===----------------------------------------------------------------------===//
673 
674 /// Return the elements types for this tuple.
675 ArrayRef<Type> TupleType::getTypes() const { return getImpl()->getTypes(); }
676 
677 /// Accumulate the types contained in this tuple and tuples nested within it.
678 /// Note that this only flattens nested tuples, not any other container type,
679 /// e.g. a tuple<i32, tensor<i32>, tuple<f32, tuple<i64>>> is flattened to
680 /// (i32, tensor<i32>, f32, i64)
681 void TupleType::getFlattenedTypes(SmallVectorImpl<Type> &types) {
682   for (Type type : getTypes()) {
683     if (auto nestedTuple = type.dyn_cast<TupleType>())
684       nestedTuple.getFlattenedTypes(types);
685     else
686       types.push_back(type);
687   }
688 }
689 
690 /// Return the number of element types.
691 size_t TupleType::size() const { return getImpl()->size(); }
692 
693 //===----------------------------------------------------------------------===//
694 // Type Utilities
695 //===----------------------------------------------------------------------===//
696 
697 AffineMap mlir::makeStridedLinearLayoutMap(ArrayRef<int64_t> strides,
698                                            int64_t offset,
699                                            MLIRContext *context) {
700   AffineExpr expr;
701   unsigned nSymbols = 0;
702 
703   // AffineExpr for offset.
704   // Static case.
705   if (offset != MemRefType::getDynamicStrideOrOffset()) {
706     auto cst = getAffineConstantExpr(offset, context);
707     expr = cst;
708   } else {
709     // Dynamic case, new symbol for the offset.
710     auto sym = getAffineSymbolExpr(nSymbols++, context);
711     expr = sym;
712   }
713 
714   // AffineExpr for strides.
715   for (auto en : llvm::enumerate(strides)) {
716     auto dim = en.index();
717     auto stride = en.value();
718     assert(stride != 0 && "Invalid stride specification");
719     auto d = getAffineDimExpr(dim, context);
720     AffineExpr mult;
721     // Static case.
722     if (stride != MemRefType::getDynamicStrideOrOffset())
723       mult = getAffineConstantExpr(stride, context);
724     else
725       // Dynamic case, new symbol for each new stride.
726       mult = getAffineSymbolExpr(nSymbols++, context);
727     expr = expr + d * mult;
728   }
729 
730   return AffineMap::get(strides.size(), nSymbols, expr);
731 }
732 
733 /// Return a version of `t` with identity layout if it can be determined
734 /// statically that the layout is the canonical contiguous strided layout.
735 /// Otherwise pass `t`'s layout into `simplifyAffineMap` and return a copy of
736 /// `t` with simplified layout.
737 /// If `t` has multiple layout maps or a multi-result layout, just return `t`.
738 MemRefType mlir::canonicalizeStridedLayout(MemRefType t) {
739   auto affineMaps = t.getAffineMaps();
740   // Already in canonical form.
741   if (affineMaps.empty())
742     return t;
743 
744   // Can't reduce to canonical identity form, return in canonical form.
745   if (affineMaps.size() > 1 || affineMaps[0].getNumResults() > 1)
746     return t;
747 
748   // If the canonical strided layout for the sizes of `t` is equal to the
749   // simplified layout of `t` we can just return an empty layout. Otherwise,
750   // just simplify the existing layout.
751   AffineExpr expr =
752       makeCanonicalStridedLayoutExpr(t.getShape(), t.getContext());
753   auto m = affineMaps[0];
754   auto simplifiedLayoutExpr =
755       simplifyAffineExpr(m.getResult(0), m.getNumDims(), m.getNumSymbols());
756   if (expr != simplifiedLayoutExpr)
757     return MemRefType::Builder(t).setAffineMaps({AffineMap::get(
758         m.getNumDims(), m.getNumSymbols(), simplifiedLayoutExpr)});
759   return MemRefType::Builder(t).setAffineMaps({});
760 }
761 
762 AffineExpr mlir::makeCanonicalStridedLayoutExpr(ArrayRef<int64_t> sizes,
763                                                 ArrayRef<AffineExpr> exprs,
764                                                 MLIRContext *context) {
765   // Size 0 corner case is useful for canonicalizations.
766   if (llvm::is_contained(sizes, 0))
767     return getAffineConstantExpr(0, context);
768 
769   auto maps = AffineMap::inferFromExprList(exprs);
770   assert(!maps.empty() && "Expected one non-empty map");
771   unsigned numDims = maps[0].getNumDims(), nSymbols = maps[0].getNumSymbols();
772 
773   AffineExpr expr;
774   bool dynamicPoisonBit = false;
775   int64_t runningSize = 1;
776   for (auto en : llvm::zip(llvm::reverse(exprs), llvm::reverse(sizes))) {
777     int64_t size = std::get<1>(en);
778     // Degenerate case, no size =-> no stride
779     if (size == 0)
780       continue;
781     AffineExpr dimExpr = std::get<0>(en);
782     AffineExpr stride = dynamicPoisonBit
783                             ? getAffineSymbolExpr(nSymbols++, context)
784                             : getAffineConstantExpr(runningSize, context);
785     expr = expr ? expr + dimExpr * stride : dimExpr * stride;
786     if (size > 0)
787       runningSize *= size;
788     else
789       dynamicPoisonBit = true;
790   }
791   return simplifyAffineExpr(expr, numDims, nSymbols);
792 }
793 
794 /// Return a version of `t` with a layout that has all dynamic offset and
795 /// strides. This is used to erase the static layout.
796 MemRefType mlir::eraseStridedLayout(MemRefType t) {
797   auto val = ShapedType::kDynamicStrideOrOffset;
798   return MemRefType::Builder(t).setAffineMaps(makeStridedLinearLayoutMap(
799       SmallVector<int64_t, 4>(t.getRank(), val), val, t.getContext()));
800 }
801 
802 AffineExpr mlir::makeCanonicalStridedLayoutExpr(ArrayRef<int64_t> sizes,
803                                                 MLIRContext *context) {
804   SmallVector<AffineExpr, 4> exprs;
805   exprs.reserve(sizes.size());
806   for (auto dim : llvm::seq<unsigned>(0, sizes.size()))
807     exprs.push_back(getAffineDimExpr(dim, context));
808   return makeCanonicalStridedLayoutExpr(sizes, exprs, context);
809 }
810 
811 /// Return true if the layout for `t` is compatible with strided semantics.
812 bool mlir::isStrided(MemRefType t) {
813   int64_t offset;
814   SmallVector<int64_t, 4> stridesAndOffset;
815   auto res = getStridesAndOffset(t, stridesAndOffset, offset);
816   return succeeded(res);
817 }
818