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