[mlir] (NFC) run clang-format on all files

This commit is contained in:
Jeff Niu 2022-07-14 13:31:47 -07:00
parent edee61b55c
commit b7f93c2809
94 changed files with 737 additions and 594 deletions

View File

@ -60,7 +60,8 @@ private:
} // namespace } // namespace
/// Return a formatted string for the location of any node /// Return a formatted string for the location of any node
template <typename T> static std::string loc(T *node) { template <typename T>
static std::string loc(T *node) {
const auto &loc = node->loc(); const auto &loc = node->loc();
return (llvm::Twine("@") + *loc.file + ":" + llvm::Twine(loc.line) + ":" + return (llvm::Twine("@") + *loc.file + ":" + llvm::Twine(loc.line) + ":" +
llvm::Twine(loc.col)) llvm::Twine(loc.col))

View File

@ -60,7 +60,8 @@ private:
} // namespace } // namespace
/// Return a formatted string for the location of any node /// Return a formatted string for the location of any node
template <typename T> static std::string loc(T *node) { template <typename T>
static std::string loc(T *node) {
const auto &loc = node->loc(); const auto &loc = node->loc();
return (llvm::Twine("@") + *loc.file + ":" + llvm::Twine(loc.line) + ":" + return (llvm::Twine("@") + *loc.file + ":" + llvm::Twine(loc.line) + ":" +
llvm::Twine(loc.col)) llvm::Twine(loc.col))

View File

@ -60,7 +60,8 @@ private:
} // namespace } // namespace
/// Return a formatted string for the location of any node /// Return a formatted string for the location of any node
template <typename T> static std::string loc(T *node) { template <typename T>
static std::string loc(T *node) {
const auto &loc = node->loc(); const auto &loc = node->loc();
return (llvm::Twine("@") + *loc.file + ":" + llvm::Twine(loc.line) + ":" + return (llvm::Twine("@") + *loc.file + ":" + llvm::Twine(loc.line) + ":" +
llvm::Twine(loc.col)) llvm::Twine(loc.col))

View File

@ -60,7 +60,8 @@ private:
} // namespace } // namespace
/// Return a formatted string for the location of any node /// Return a formatted string for the location of any node
template <typename T> static std::string loc(T *node) { template <typename T>
static std::string loc(T *node) {
const auto &loc = node->loc(); const auto &loc = node->loc();
return (llvm::Twine("@") + *loc.file + ":" + llvm::Twine(loc.line) + ":" + return (llvm::Twine("@") + *loc.file + ":" + llvm::Twine(loc.line) + ":" +
llvm::Twine(loc.col)) llvm::Twine(loc.col))

View File

@ -104,24 +104,25 @@ struct BinaryOpLowering : public ConversionPattern {
matchAndRewrite(Operation *op, ArrayRef<Value> operands, matchAndRewrite(Operation *op, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const final { ConversionPatternRewriter &rewriter) const final {
auto loc = op->getLoc(); auto loc = op->getLoc();
lowerOpToLoops( lowerOpToLoops(op, operands, rewriter,
op, operands, rewriter,
[loc](OpBuilder &builder, ValueRange memRefOperands, [loc](OpBuilder &builder, ValueRange memRefOperands,
ValueRange loopIvs) { ValueRange loopIvs) {
// Generate an adaptor for the remapped operands of the BinaryOp. This // Generate an adaptor for the remapped operands of the
// allows for using the nice named accessors that are generated by the // BinaryOp. This allows for using the nice named accessors
// ODS. // that are generated by the ODS.
typename BinaryOp::Adaptor binaryAdaptor(memRefOperands); typename BinaryOp::Adaptor binaryAdaptor(memRefOperands);
// Generate loads for the element of 'lhs' and 'rhs' at the inner // Generate loads for the element of 'lhs' and 'rhs' at the
// loop. // inner loop.
auto loadedLhs = builder.create<AffineLoadOp>( auto loadedLhs = builder.create<AffineLoadOp>(
loc, binaryAdaptor.getLhs(), loopIvs); loc, binaryAdaptor.getLhs(), loopIvs);
auto loadedRhs = builder.create<AffineLoadOp>( auto loadedRhs = builder.create<AffineLoadOp>(
loc, binaryAdaptor.getRhs(), loopIvs); loc, binaryAdaptor.getRhs(), loopIvs);
// Create the binary operation performed on the loaded values. // Create the binary operation performed on the loaded
return builder.create<LoweredBinaryOp>(loc, loadedLhs, loadedRhs); // values.
return builder.create<LoweredBinaryOp>(loc, loadedLhs,
loadedRhs);
}); });
return success(); return success();
} }

View File

@ -60,7 +60,8 @@ private:
} // namespace } // namespace
/// Return a formatted string for the location of any node /// Return a formatted string for the location of any node
template <typename T> static std::string loc(T *node) { template <typename T>
static std::string loc(T *node) {
const auto &loc = node->loc(); const auto &loc = node->loc();
return (llvm::Twine("@") + *loc.file + ":" + llvm::Twine(loc.line) + ":" + return (llvm::Twine("@") + *loc.file + ":" + llvm::Twine(loc.line) + ":" +
llvm::Twine(loc.col)) llvm::Twine(loc.col))

View File

@ -104,24 +104,25 @@ struct BinaryOpLowering : public ConversionPattern {
matchAndRewrite(Operation *op, ArrayRef<Value> operands, matchAndRewrite(Operation *op, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const final { ConversionPatternRewriter &rewriter) const final {
auto loc = op->getLoc(); auto loc = op->getLoc();
lowerOpToLoops( lowerOpToLoops(op, operands, rewriter,
op, operands, rewriter,
[loc](OpBuilder &builder, ValueRange memRefOperands, [loc](OpBuilder &builder, ValueRange memRefOperands,
ValueRange loopIvs) { ValueRange loopIvs) {
// Generate an adaptor for the remapped operands of the BinaryOp. This // Generate an adaptor for the remapped operands of the
// allows for using the nice named accessors that are generated by the // BinaryOp. This allows for using the nice named accessors
// ODS. // that are generated by the ODS.
typename BinaryOp::Adaptor binaryAdaptor(memRefOperands); typename BinaryOp::Adaptor binaryAdaptor(memRefOperands);
// Generate loads for the element of 'lhs' and 'rhs' at the inner // Generate loads for the element of 'lhs' and 'rhs' at the
// loop. // inner loop.
auto loadedLhs = builder.create<AffineLoadOp>( auto loadedLhs = builder.create<AffineLoadOp>(
loc, binaryAdaptor.getLhs(), loopIvs); loc, binaryAdaptor.getLhs(), loopIvs);
auto loadedRhs = builder.create<AffineLoadOp>( auto loadedRhs = builder.create<AffineLoadOp>(
loc, binaryAdaptor.getRhs(), loopIvs); loc, binaryAdaptor.getRhs(), loopIvs);
// Create the binary operation performed on the loaded values. // Create the binary operation performed on the loaded
return builder.create<LoweredBinaryOp>(loc, loadedLhs, loadedRhs); // values.
return builder.create<LoweredBinaryOp>(loc, loadedLhs,
loadedRhs);
}); });
return success(); return success();
} }

View File

@ -60,7 +60,8 @@ private:
} // namespace } // namespace
/// Return a formatted string for the location of any node /// Return a formatted string for the location of any node
template <typename T> static std::string loc(T *node) { template <typename T>
static std::string loc(T *node) {
const auto &loc = node->loc(); const auto &loc = node->loc();
return (llvm::Twine("@") + *loc.file + ":" + llvm::Twine(loc.line) + ":" + return (llvm::Twine("@") + *loc.file + ":" + llvm::Twine(loc.line) + ":" +
llvm::Twine(loc.col)) llvm::Twine(loc.col))

View File

@ -104,24 +104,25 @@ struct BinaryOpLowering : public ConversionPattern {
matchAndRewrite(Operation *op, ArrayRef<Value> operands, matchAndRewrite(Operation *op, ArrayRef<Value> operands,
ConversionPatternRewriter &rewriter) const final { ConversionPatternRewriter &rewriter) const final {
auto loc = op->getLoc(); auto loc = op->getLoc();
lowerOpToLoops( lowerOpToLoops(op, operands, rewriter,
op, operands, rewriter,
[loc](OpBuilder &builder, ValueRange memRefOperands, [loc](OpBuilder &builder, ValueRange memRefOperands,
ValueRange loopIvs) { ValueRange loopIvs) {
// Generate an adaptor for the remapped operands of the BinaryOp. This // Generate an adaptor for the remapped operands of the
// allows for using the nice named accessors that are generated by the // BinaryOp. This allows for using the nice named accessors
// ODS. // that are generated by the ODS.
typename BinaryOp::Adaptor binaryAdaptor(memRefOperands); typename BinaryOp::Adaptor binaryAdaptor(memRefOperands);
// Generate loads for the element of 'lhs' and 'rhs' at the inner // Generate loads for the element of 'lhs' and 'rhs' at the
// loop. // inner loop.
auto loadedLhs = builder.create<AffineLoadOp>( auto loadedLhs = builder.create<AffineLoadOp>(
loc, binaryAdaptor.getLhs(), loopIvs); loc, binaryAdaptor.getLhs(), loopIvs);
auto loadedRhs = builder.create<AffineLoadOp>( auto loadedRhs = builder.create<AffineLoadOp>(
loc, binaryAdaptor.getRhs(), loopIvs); loc, binaryAdaptor.getRhs(), loopIvs);
// Create the binary operation performed on the loaded values. // Create the binary operation performed on the loaded
return builder.create<LoweredBinaryOp>(loc, loadedLhs, loadedRhs); // values.
return builder.create<LoweredBinaryOp>(loc, loadedLhs,
loadedRhs);
}); });
return success(); return success();
} }

View File

@ -62,7 +62,8 @@ private:
} // namespace } // namespace
/// Return a formatted string for the location of any node /// Return a formatted string for the location of any node
template <typename T> static std::string loc(T *node) { template <typename T>
static std::string loc(T *node) {
const auto &loc = node->loc(); const auto &loc = node->loc();
return (llvm::Twine("@") + *loc.file + ":" + llvm::Twine(loc.line) + ":" + return (llvm::Twine("@") + *loc.file + ":" + llvm::Twine(loc.line) + ":" +
llvm::Twine(loc.col)) llvm::Twine(loc.col))

View File

@ -193,7 +193,8 @@ struct AliasAnalysisTraits {
/// `ImplT`. A model is instantiated for each alias analysis implementation /// `ImplT`. A model is instantiated for each alias analysis implementation
/// to implement the `Concept` without the need for the derived /// to implement the `Concept` without the need for the derived
/// implementation to inherit from the `Concept` class. /// implementation to inherit from the `Concept` class.
template <typename ImplT> class Model final : public Concept { template <typename ImplT>
class Model final : public Concept {
public: public:
explicit Model(ImplT &&impl) : impl(std::forward<ImplT>(impl)) {} explicit Model(ImplT &&impl) : impl(std::forward<ImplT>(impl)) {}
~Model() override = default; ~Model() override = default;

View File

@ -221,7 +221,8 @@ private:
namespace llvm { namespace llvm {
// Provide graph traits for traversing call graphs using standard graph // Provide graph traits for traversing call graphs using standard graph
// traversals. // traversals.
template <> struct GraphTraits<const mlir::CallGraphNode *> { template <>
struct GraphTraits<const mlir::CallGraphNode *> {
using NodeRef = mlir::CallGraphNode *; using NodeRef = mlir::CallGraphNode *;
static NodeRef getEntryNode(NodeRef node) { return node; } static NodeRef getEntryNode(NodeRef node) { return node; }

View File

@ -21,7 +21,8 @@
namespace mlir { namespace mlir {
class ModuleOp; class ModuleOp;
template <typename T> class OperationPass; template <typename T>
class OperationPass;
std::unique_ptr<OperationPass<ModuleOp>> std::unique_ptr<OperationPass<ModuleOp>>
createConvertVulkanLaunchFuncToVulkanCallsPass(); createConvertVulkanLaunchFuncToVulkanCallsPass();

View File

@ -49,7 +49,8 @@ public:
/// Allow the given dialects. /// Allow the given dialects.
/// ///
/// This function adds one or multiple ALLOW entries. /// This function adds one or multiple ALLOW entries.
template <typename... DialectTs> void allowDialect() { template <typename... DialectTs>
void allowDialect() {
// The following expands a call to allowDialectImpl for each dialect // The following expands a call to allowDialectImpl for each dialect
// in 'DialectTs'. This magic is necessary due to a limitation in the places // in 'DialectTs'. This magic is necessary due to a limitation in the places
// that a parameter pack can be expanded in c++11. // that a parameter pack can be expanded in c++11.
@ -60,7 +61,8 @@ public:
/// Deny the given dialects. /// Deny the given dialects.
/// ///
/// This function adds one or multiple DENY entries. /// This function adds one or multiple DENY entries.
template <typename... DialectTs> void denyDialect() { template <typename... DialectTs>
void denyDialect() {
// FIXME: In c++17 this can be simplified by using 'fold expressions'. // FIXME: In c++17 this can be simplified by using 'fold expressions'.
(void)std::initializer_list<int>{0, (denyDialectImpl<DialectTs>(), 0)...}; (void)std::initializer_list<int>{0, (denyDialectImpl<DialectTs>(), 0)...};
} }
@ -78,7 +80,8 @@ public:
/// Allow the given ops. /// Allow the given ops.
/// ///
/// This function adds one or multiple ALLOW entries. /// This function adds one or multiple ALLOW entries.
template <typename... OpTys> void allowOperation() { template <typename... OpTys>
void allowOperation() {
// FIXME: In c++17 this can be simplified by using 'fold expressions'. // FIXME: In c++17 this can be simplified by using 'fold expressions'.
(void)std::initializer_list<int>{0, (allowOperationImpl<OpTys>(), 0)...}; (void)std::initializer_list<int>{0, (allowOperationImpl<OpTys>(), 0)...};
} }
@ -86,7 +89,8 @@ public:
/// Deny the given ops. /// Deny the given ops.
/// ///
/// This function adds one or multiple DENY entries. /// This function adds one or multiple DENY entries.
template <typename... OpTys> void denyOperation() { template <typename... OpTys>
void denyOperation() {
// FIXME: In c++17 this can be simplified by using 'fold expressions'. // FIXME: In c++17 this can be simplified by using 'fold expressions'.
(void)std::initializer_list<int>{0, (denyOperationImpl<OpTys>(), 0)...}; (void)std::initializer_list<int>{0, (denyOperationImpl<OpTys>(), 0)...};
} }
@ -135,22 +139,26 @@ private:
} }
/// Allow a dialect. /// Allow a dialect.
template <typename DialectT> void allowDialectImpl() { template <typename DialectT>
void allowDialectImpl() {
allowDialect(DialectT::getDialectNamespace()); allowDialect(DialectT::getDialectNamespace());
} }
/// Deny a dialect. /// Deny a dialect.
template <typename DialectT> void denyDialectImpl() { template <typename DialectT>
void denyDialectImpl() {
denyDialect(DialectT::getDialectNamespace()); denyDialect(DialectT::getDialectNamespace());
} }
/// Allow an op. /// Allow an op.
template <typename OpTy> void allowOperationImpl() { template <typename OpTy>
void allowOperationImpl() {
allowOperation(OpTy::getOperationName()); allowOperation(OpTy::getOperationName());
} }
/// Deny an op. /// Deny an op.
template <typename OpTy> void denyOperationImpl() { template <typename OpTy>
void denyOperationImpl() {
denyOperation(OpTy::getOperationName()); denyOperation(OpTy::getOperationName());
} }

View File

@ -24,7 +24,8 @@
#include <memory> #include <memory>
namespace llvm { namespace llvm {
template <typename T> class Expected; template <typename T>
class Expected;
class Module; class Module;
class ExecutionEngine; class ExecutionEngine;
class JITEventListener; class JITEventListener;

View File

@ -182,8 +182,8 @@ FOREVERY_O(DECL_SPARSEINDICES)
/// Coordinate-scheme method for adding a new element. /// Coordinate-scheme method for adding a new element.
#define DECL_ADDELT(VNAME, V) \ #define DECL_ADDELT(VNAME, V) \
MLIR_CRUNNERUTILS_EXPORT void *_mlir_ciface_addElt##VNAME( \ MLIR_CRUNNERUTILS_EXPORT void *_mlir_ciface_addElt##VNAME( \
void *coo, \ void *coo, StridedMemRefType<V, 0> *vref, \
StridedMemRefType<V, 0> *vref, StridedMemRefType<index_type, 1> *iref, \ StridedMemRefType<index_type, 1> *iref, \
StridedMemRefType<index_type, 1> *pref); StridedMemRefType<index_type, 1> *pref);
FOREVERY_V(DECL_ADDELT) FOREVERY_V(DECL_ADDELT)
#undef DECL_ADDELT #undef DECL_ADDELT

View File

@ -65,7 +65,8 @@ namespace mlir {
/// just as efficient as having your own switch instruction over the instruction /// just as efficient as having your own switch instruction over the instruction
/// opcode. /// opcode.
template <typename SubClass, typename RetTy = void> class AffineExprVisitor { template <typename SubClass, typename RetTy = void>
class AffineExprVisitor {
//===--------------------------------------------------------------------===// //===--------------------------------------------------------------------===//
// Interface code - This is the public interface of the AffineExprVisitor // Interface code - This is the public interface of the AffineExprVisitor
// that you use to visit affine expressions... // that you use to visit affine expressions...

View File

@ -46,14 +46,18 @@ public:
bool operator!() const { return impl == nullptr; } bool operator!() const { return impl == nullptr; }
template <typename U> bool isa() const; template <typename U>
bool isa() const;
template <typename First, typename Second, typename... Rest> template <typename First, typename Second, typename... Rest>
bool isa() const; bool isa() const;
template <typename First, typename... Rest> template <typename First, typename... Rest>
bool isa_and_nonnull() const; bool isa_and_nonnull() const;
template <typename U> U dyn_cast() const; template <typename U>
template <typename U> U dyn_cast_or_null() const; U dyn_cast() const;
template <typename U> U cast() const; template <typename U>
U dyn_cast_or_null() const;
template <typename U>
U cast() const;
// Support dyn_cast'ing Attribute to itself. // Support dyn_cast'ing Attribute to itself.
static bool classof(Attribute) { return true; } static bool classof(Attribute) { return true; }
@ -106,7 +110,8 @@ inline raw_ostream &operator<<(raw_ostream &os, Attribute attr) {
return os; return os;
} }
template <typename U> bool Attribute::isa() const { template <typename U>
bool Attribute::isa() const {
assert(impl && "isa<> used on a null attribute."); assert(impl && "isa<> used on a null attribute.");
return U::classof(*this); return U::classof(*this);
} }
@ -121,13 +126,16 @@ bool Attribute::isa_and_nonnull() const {
return impl && isa<First, Rest...>(); return impl && isa<First, Rest...>();
} }
template <typename U> U Attribute::dyn_cast() const { template <typename U>
U Attribute::dyn_cast() const {
return isa<U>() ? U(impl) : U(nullptr); return isa<U>() ? U(impl) : U(nullptr);
} }
template <typename U> U Attribute::dyn_cast_or_null() const { template <typename U>
U Attribute::dyn_cast_or_null() const {
return (impl && isa<U>()) ? U(impl) : U(nullptr); return (impl && isa<U>()) ? U(impl) : U(nullptr);
} }
template <typename U> U Attribute::cast() const { template <typename U>
U Attribute::cast() const {
assert(isa<U>()); assert(isa<U>());
return U(impl); return U(impl);
} }
@ -248,7 +256,8 @@ using IsMutable = detail::StorageUserTrait::IsMutable<ConcreteType>;
namespace llvm { namespace llvm {
// Attribute hash just like pointers. // Attribute hash just like pointers.
template <> struct DenseMapInfo<mlir::Attribute> { template <>
struct DenseMapInfo<mlir::Attribute> {
static mlir::Attribute getEmptyKey() { static mlir::Attribute getEmptyKey() {
auto *pointer = llvm::DenseMapInfo<void *>::getEmptyKey(); auto *pointer = llvm::DenseMapInfo<void *>::getEmptyKey();
return mlir::Attribute(static_cast<mlir::Attribute::ImplType *>(pointer)); return mlir::Attribute(static_cast<mlir::Attribute::ImplType *>(pointer));
@ -280,7 +289,8 @@ struct DenseMapInfo<
}; };
/// Allow LLVM to steal the low bits of Attributes. /// Allow LLVM to steal the low bits of Attributes.
template <> struct PointerLikeTypeTraits<mlir::Attribute> { template <>
struct PointerLikeTypeTraits<mlir::Attribute> {
static inline void *getAsVoidPointer(mlir::Attribute attr) { static inline void *getAsVoidPointer(mlir::Attribute attr) {
return const_cast<void *>(attr.getAsOpaquePointer()); return const_cast<void *>(attr.getAsOpaquePointer());
} }
@ -291,7 +301,8 @@ template <> struct PointerLikeTypeTraits<mlir::Attribute> {
mlir::AttributeStorage *>::NumLowBitsAvailable; mlir::AttributeStorage *>::NumLowBitsAvailable;
}; };
template <> struct DenseMapInfo<mlir::NamedAttribute> { template <>
struct DenseMapInfo<mlir::NamedAttribute> {
static mlir::NamedAttribute getEmptyKey() { static mlir::NamedAttribute getEmptyKey() {
auto emptyAttr = llvm::DenseMapInfo<mlir::Attribute>::getEmptyKey(); auto emptyAttr = llvm::DenseMapInfo<mlir::Attribute>::getEmptyKey();
return mlir::NamedAttribute(emptyAttr, emptyAttr); return mlir::NamedAttribute(emptyAttr, emptyAttr);

View File

@ -63,7 +63,8 @@ public:
/// Lookup a mapped value within the map. This asserts the provided value /// Lookup a mapped value within the map. This asserts the provided value
/// exists within the map. /// exists within the map.
template <typename T> T lookup(T from) const { template <typename T>
T lookup(T from) const {
auto result = lookupOrNull(from); auto result = lookupOrNull(from);
assert(result && "expected 'from' to be contained within the map"); assert(result && "expected 'from' to be contained within the map");
return result; return result;

View File

@ -52,7 +52,6 @@ class PredecessorIterator final
static Block *unwrap(BlockOperand &value); static Block *unwrap(BlockOperand &value);
public: public:
/// Initializes the operand type iterator to the specified operand iterator. /// Initializes the operand type iterator to the specified operand iterator.
PredecessorIterator(ValueUseIterator<BlockOperand> it) PredecessorIterator(ValueUseIterator<BlockOperand> it)
: llvm::mapped_iterator<ValueUseIterator<BlockOperand>, : llvm::mapped_iterator<ValueUseIterator<BlockOperand>,
@ -162,7 +161,6 @@ class op_iterator
static OpT unwrap(Operation &op) { return cast<OpT>(op); } static OpT unwrap(Operation &op) { return cast<OpT>(op); }
public: public:
/// Initializes the iterator to the specified filter iterator. /// Initializes the iterator to the specified filter iterator.
op_iterator(op_filter_iterator<OpT, IteratorT> it) op_iterator(op_filter_iterator<OpT, IteratorT> it)
: llvm::mapped_iterator<op_filter_iterator<OpT, IteratorT>, : llvm::mapped_iterator<op_filter_iterator<OpT, IteratorT>,
@ -225,7 +223,8 @@ protected:
}; };
} // namespace ilist_detail } // namespace ilist_detail
template <> struct ilist_traits<::mlir::Operation> { template <>
struct ilist_traits<::mlir::Operation> {
using Operation = ::mlir::Operation; using Operation = ::mlir::Operation;
using op_iterator = simple_ilist<Operation>::iterator; using op_iterator = simple_ilist<Operation>::iterator;

View File

@ -76,7 +76,8 @@ public:
} }
/// Access the element at the given index. /// Access the element at the given index.
template <typename T> T at(uint64_t index) const { template <typename T>
T at(uint64_t index) const {
if (isSplat) if (isSplat)
index = 0; index = 0;
return isContiguous ? conState.at<T>(index) : nonConState.at<T>(index); return isContiguous ? conState.at<T>(index) : nonConState.at<T>(index);
@ -93,7 +94,8 @@ private:
ContiguousState(const void *firstEltPtr) : firstEltPtr(firstEltPtr) {} ContiguousState(const void *firstEltPtr) : firstEltPtr(firstEltPtr) {}
/// Access the element at the given index. /// Access the element at the given index.
template <typename T> const T &at(uint64_t index) const { template <typename T>
const T &at(uint64_t index) const {
return *(reinterpret_cast<const T *>(firstEltPtr) + index); return *(reinterpret_cast<const T *>(firstEltPtr) + index);
} }
@ -171,7 +173,8 @@ private:
NonContiguousState(NonContiguousState &&other) = default; NonContiguousState(NonContiguousState &&other) = default;
/// Access the element at the given index. /// Access the element at the given index.
template <typename T> T at(uint64_t index) const { template <typename T>
T at(uint64_t index) const {
auto *valueIt = static_cast<OpaqueIteratorValueBase<T> *>(iterator.get()); auto *valueIt = static_cast<OpaqueIteratorValueBase<T> *>(iterator.get());
return valueIt->at(index); return valueIt->at(index);
} }

View File

@ -61,7 +61,8 @@ protected:
}; };
/// Type trait detector that checks if a given type T is a complex type. /// Type trait detector that checks if a given type T is a complex type.
template <typename T> struct is_complex_t : public std::false_type {}; template <typename T>
struct is_complex_t : public std::false_type {};
template <typename T> template <typename T>
struct is_complex_t<std::complex<T>> : public std::true_type {}; struct is_complex_t<std::complex<T>> : public std::true_type {};
} // namespace detail } // namespace detail
@ -81,7 +82,8 @@ public:
/// floating point type that can be used to access the underlying element /// floating point type that can be used to access the underlying element
/// types of a DenseElementsAttr. /// types of a DenseElementsAttr.
// TODO: Use std::disjunction when C++17 is supported. // TODO: Use std::disjunction when C++17 is supported.
template <typename T> struct is_valid_cpp_fp_type { template <typename T>
struct is_valid_cpp_fp_type {
/// The type is a valid floating point type if it is a builtin floating /// The type is a valid floating point type if it is a builtin floating
/// point type, or is a potentially user defined floating point type. The /// point type, or is a potentially user defined floating point type. The
/// latter allows for supporting users that have custom types defined for /// latter allows for supporting users that have custom types defined for

View File

@ -201,9 +201,7 @@ public:
/// Stream in an Operation. /// Stream in an Operation.
Diagnostic &operator<<(Operation &val); Diagnostic &operator<<(Operation &val);
Diagnostic &operator<<(Operation *val) { Diagnostic &operator<<(Operation *val) { return *this << *val; }
return *this << *val;
}
/// Append an operation with the given printing flags. /// Append an operation with the given printing flags.
Diagnostic &appendOp(Operation &val, const OpPrintingFlags &flags); Diagnostic &appendOp(Operation &val, const OpPrintingFlags &flags);
@ -234,7 +232,8 @@ public:
return append(std::forward<Arg2>(arg2), std::forward<Args>(args)...); return append(std::forward<Arg2>(arg2), std::forward<Args>(args)...);
} }
/// Append one argument to the diagnostic. /// Append one argument to the diagnostic.
template <typename Arg> Diagnostic &append(Arg &&arg) { template <typename Arg>
Diagnostic &append(Arg &&arg) {
*this << std::forward<Arg>(arg); *this << std::forward<Arg>(arg);
return *this; return *this;
} }
@ -323,21 +322,25 @@ public:
} }
/// Stream operator for new diagnostic arguments. /// Stream operator for new diagnostic arguments.
template <typename Arg> InFlightDiagnostic &operator<<(Arg &&arg) & { template <typename Arg>
InFlightDiagnostic &operator<<(Arg &&arg) & {
return append(std::forward<Arg>(arg)); return append(std::forward<Arg>(arg));
} }
template <typename Arg> InFlightDiagnostic &&operator<<(Arg &&arg) && { template <typename Arg>
InFlightDiagnostic &&operator<<(Arg &&arg) && {
return std::move(append(std::forward<Arg>(arg))); return std::move(append(std::forward<Arg>(arg)));
} }
/// Append arguments to the diagnostic. /// Append arguments to the diagnostic.
template <typename... Args> InFlightDiagnostic &append(Args &&... args) & { template <typename... Args>
InFlightDiagnostic &append(Args &&...args) & {
assert(isActive() && "diagnostic not active"); assert(isActive() && "diagnostic not active");
if (isInFlight()) if (isInFlight())
impl->append(std::forward<Args>(args)...); impl->append(std::forward<Args>(args)...);
return *this; return *this;
} }
template <typename... Args> InFlightDiagnostic &&append(Args &&... args) && { template <typename... Args>
InFlightDiagnostic &&append(Args &&...args) && {
return std::move(append(std::forward<Args>(args)...)); return std::move(append(std::forward<Args>(args)...));
} }
@ -520,7 +523,8 @@ public:
protected: protected:
/// Set the handler to manage via RAII. /// Set the handler to manage via RAII.
template <typename FuncTy> void setHandler(FuncTy &&handler) { template <typename FuncTy>
void setHandler(FuncTy &&handler) {
auto &diagEngine = ctx->getDiagEngine(); auto &diagEngine = ctx->getDiagEngine();
if (handlerID) if (handlerID)
diagEngine.eraseHandler(handlerID); diagEngine.eraseHandler(handlerID);

View File

@ -161,7 +161,8 @@ public:
auto it = registeredInterfaces.find(interfaceID); auto it = registeredInterfaces.find(interfaceID);
return it != registeredInterfaces.end() ? it->getSecond().get() : nullptr; return it != registeredInterfaces.end() ? it->getSecond().get() : nullptr;
} }
template <typename InterfaceT> const InterfaceT *getRegisteredInterface() { template <typename InterfaceT>
const InterfaceT *getRegisteredInterface() {
return static_cast<const InterfaceT *>( return static_cast<const InterfaceT *>(
getRegisteredInterface(InterfaceT::getInterfaceID())); getRegisteredInterface(InterfaceT::getInterfaceID()));
} }
@ -201,13 +202,15 @@ protected:
/// This method is used by derived classes to add their operations to the set. /// This method is used by derived classes to add their operations to the set.
/// ///
template <typename... Args> void addOperations() { template <typename... Args>
void addOperations() {
(void)std::initializer_list<int>{ (void)std::initializer_list<int>{
0, (RegisteredOperationName::insert<Args>(*this), 0)...}; 0, (RegisteredOperationName::insert<Args>(*this), 0)...};
} }
/// Register a set of type classes with this dialect. /// Register a set of type classes with this dialect.
template <typename... Args> void addTypes() { template <typename... Args>
void addTypes() {
(void)std::initializer_list<int>{0, (addType<Args>(), 0)...}; (void)std::initializer_list<int>{0, (addType<Args>(), 0)...};
} }
@ -217,7 +220,8 @@ protected:
void addType(TypeID typeID, AbstractType &&typeInfo); void addType(TypeID typeID, AbstractType &&typeInfo);
/// Register a set of attribute classes with this dialect. /// Register a set of attribute classes with this dialect.
template <typename... Args> void addAttributes() { template <typename... Args>
void addAttributes() {
(void)std::initializer_list<int>{0, (addAttribute<Args>(), 0)...}; (void)std::initializer_list<int>{0, (addAttribute<Args>(), 0)...};
} }
@ -237,14 +241,16 @@ private:
void operator=(Dialect &) = delete; void operator=(Dialect &) = delete;
/// Register an attribute instance with this dialect. /// Register an attribute instance with this dialect.
template <typename T> void addAttribute() { template <typename T>
void addAttribute() {
// Add this attribute to the dialect and register it with the uniquer. // Add this attribute to the dialect and register it with the uniquer.
addAttribute(T::getTypeID(), AbstractAttribute::get<T>(*this)); addAttribute(T::getTypeID(), AbstractAttribute::get<T>(*this));
detail::AttributeUniquer::registerAttribute<T>(context); detail::AttributeUniquer::registerAttribute<T>(context);
} }
/// Register a type instance with this dialect. /// Register a type instance with this dialect.
template <typename T> void addType() { template <typename T>
void addType() {
// Add this type to the dialect and register it with the uniquer. // Add this type to the dialect and register it with the uniquer.
addType(T::getTypeID(), AbstractType::get<T>(*this)); addType(T::getTypeID(), AbstractType::get<T>(*this));
detail::TypeUniquer::registerType<T>(context); detail::TypeUniquer::registerType<T>(context);

View File

@ -126,10 +126,12 @@ protected:
}; };
/// Iterator access to the held interfaces. /// Iterator access to the held interfaces.
template <typename InterfaceT> iterator<InterfaceT> interface_begin() const { template <typename InterfaceT>
iterator<InterfaceT> interface_begin() const {
return iterator<InterfaceT>(orderedInterfaces.begin()); return iterator<InterfaceT>(orderedInterfaces.begin());
} }
template <typename InterfaceT> iterator<InterfaceT> interface_end() const { template <typename InterfaceT>
iterator<InterfaceT> interface_end() const {
return iterator<InterfaceT>(orderedInterfaces.end()); return iterator<InterfaceT>(orderedInterfaces.end());
} }

View File

@ -128,7 +128,8 @@ inline ::llvm::hash_code hash_value(IntegerSet arg) {
namespace llvm { namespace llvm {
// IntegerSet hash just like pointers. // IntegerSet hash just like pointers.
template <> struct DenseMapInfo<mlir::IntegerSet> { template <>
struct DenseMapInfo<mlir::IntegerSet> {
static mlir::IntegerSet getEmptyKey() { static mlir::IntegerSet getEmptyKey() {
auto *pointer = llvm::DenseMapInfo<void *>::getEmptyKey(); auto *pointer = llvm::DenseMapInfo<void *>::getEmptyKey();
return mlir::IntegerSet(static_cast<mlir::IntegerSet::ImplType *>(pointer)); return mlir::IntegerSet(static_cast<mlir::IntegerSet::ImplType *>(pointer));

View File

@ -62,9 +62,18 @@ public:
LocationAttr *operator->() const { return const_cast<LocationAttr *>(&impl); } LocationAttr *operator->() const { return const_cast<LocationAttr *>(&impl); }
/// Type casting utilities on the underlying location. /// Type casting utilities on the underlying location.
template <typename U> bool isa() const { return impl.isa<U>(); } template <typename U>
template <typename U> U dyn_cast() const { return impl.dyn_cast<U>(); } bool isa() const {
template <typename U> U cast() const { return impl.cast<U>(); } return impl.isa<U>();
}
template <typename U>
U dyn_cast() const {
return impl.dyn_cast<U>();
}
template <typename U>
U cast() const {
return impl.cast<U>();
}
/// Comparison operators. /// Comparison operators.
bool operator==(Location rhs) const { return impl == rhs.impl; } bool operator==(Location rhs) const { return impl == rhs.impl; }
@ -128,7 +137,8 @@ inline OpaqueLoc OpaqueLoc::get(T underlyingLocation, MLIRContext *context) {
namespace llvm { namespace llvm {
// Type hash just like pointers. // Type hash just like pointers.
template <> struct DenseMapInfo<mlir::Location> { template <>
struct DenseMapInfo<mlir::Location> {
static mlir::Location getEmptyKey() { static mlir::Location getEmptyKey() {
auto *pointer = llvm::DenseMapInfo<void *>::getEmptyKey(); auto *pointer = llvm::DenseMapInfo<void *>::getEmptyKey();
return mlir::Location::getFromOpaquePointer(pointer); return mlir::Location::getFromOpaquePointer(pointer);
@ -146,7 +156,8 @@ template <> struct DenseMapInfo<mlir::Location> {
}; };
/// We align LocationStorage by 8, so allow LLVM to steal the low bits. /// We align LocationStorage by 8, so allow LLVM to steal the low bits.
template <> struct PointerLikeTypeTraits<mlir::Location> { template <>
struct PointerLikeTypeTraits<mlir::Location> {
public: public:
static inline void *getAsVoidPointer(mlir::Location I) { static inline void *getAsVoidPointer(mlir::Location I) {
return const_cast<void *>(I.getAsOpaquePointer()); return const_cast<void *>(I.getAsOpaquePointer());

View File

@ -1732,14 +1732,16 @@ private:
struct InterfaceTargetOrOpT { struct InterfaceTargetOrOpT {
using type = typename T::ConcreteEntity; using type = typename T::ConcreteEntity;
}; };
template <typename T> struct InterfaceTargetOrOpT<T, false> { template <typename T>
struct InterfaceTargetOrOpT<T, false> {
using type = ConcreteType; using type = ConcreteType;
}; };
/// A hook for static assertion that the external interface model T is /// A hook for static assertion that the external interface model T is
/// targeting the concrete type of this op. The model can also be a fallback /// targeting the concrete type of this op. The model can also be a fallback
/// model that works for every op. /// model that works for every op.
template <typename T> static void checkInterfaceTarget() { template <typename T>
static void checkInterfaceTarget() {
static_assert(std::is_same<typename InterfaceTargetOrOpT<T>::type, static_assert(std::is_same<typename InterfaceTargetOrOpT<T>::type,
ConcreteType>::value, ConcreteType>::value,
"attaching an interface to the wrong op kind"); "attaching an interface to the wrong op kind");

View File

@ -151,10 +151,9 @@ public:
std::enable_if_t<detect_has_print_method<AttrOrType>::value> std::enable_if_t<detect_has_print_method<AttrOrType>::value>
*sfinae = nullptr> *sfinae = nullptr>
void printStrippedAttrOrType(ArrayRef<AttrOrType> attrOrTypes) { void printStrippedAttrOrType(ArrayRef<AttrOrType> attrOrTypes) {
llvm::interleaveComma(attrOrTypes, getStream(), llvm::interleaveComma(
[this](AttrOrType attrOrType) { attrOrTypes, getStream(),
printStrippedAttrOrType(attrOrType); [this](AttrOrType attrOrType) { printStrippedAttrOrType(attrOrType); });
});
} }
/// SFINAE for printing the provided attribute in the context of an operation /// SFINAE for printing the provided attribute in the context of an operation

View File

@ -141,7 +141,8 @@ public:
/// Returns true if the operation was registered with a particular trait, e.g. /// Returns true if the operation was registered with a particular trait, e.g.
/// hasTrait<OperandsAreSignlessIntegerLike>(). Returns false if the operation /// hasTrait<OperandsAreSignlessIntegerLike>(). Returns false if the operation
/// is unregistered. /// is unregistered.
template <template <typename T> class Trait> bool hasTrait() const { template <template <typename T> class Trait>
bool hasTrait() const {
return hasTrait(TypeID::get<Trait>()); return hasTrait(TypeID::get<Trait>());
} }
bool hasTrait(TypeID traitID) const { bool hasTrait(TypeID traitID) const {
@ -151,7 +152,8 @@ public:
/// Returns true if the operation *might* have the provided trait. This /// Returns true if the operation *might* have the provided trait. This
/// means that either the operation is unregistered, or it was registered with /// means that either the operation is unregistered, or it was registered with
/// the provide trait. /// the provide trait.
template <template <typename T> class Trait> bool mightHaveTrait() const { template <template <typename T> class Trait>
bool mightHaveTrait() const {
return mightHaveTrait(TypeID::get<Trait>()); return mightHaveTrait(TypeID::get<Trait>());
} }
bool mightHaveTrait(TypeID traitID) const { bool mightHaveTrait(TypeID traitID) const {
@ -161,12 +163,14 @@ public:
/// Returns an instance of the concept object for the given interface if it /// Returns an instance of the concept object for the given interface if it
/// was registered to this operation, null otherwise. This should not be used /// was registered to this operation, null otherwise. This should not be used
/// directly. /// directly.
template <typename T> typename T::Concept *getInterface() const { template <typename T>
typename T::Concept *getInterface() const {
return impl->interfaceMap.lookup<T>(); return impl->interfaceMap.lookup<T>();
} }
/// Returns true if this operation has the given interface registered to it. /// Returns true if this operation has the given interface registered to it.
template <typename T> bool hasInterface() const { template <typename T>
bool hasInterface() const {
return hasInterface(TypeID::get<T>()); return hasInterface(TypeID::get<T>());
} }
bool hasInterface(TypeID interfaceID) const { bool hasInterface(TypeID interfaceID) const {
@ -345,7 +349,8 @@ public:
} }
/// Returns true if the operation has a particular trait. /// Returns true if the operation has a particular trait.
template <template <typename T> class Trait> bool hasTrait() const { template <template <typename T> class Trait>
bool hasTrait() const {
return hasTrait(TypeID::get<Trait>()); return hasTrait(TypeID::get<Trait>());
} }

View File

@ -19,7 +19,8 @@
#include "llvm/ADT/GraphTraits.h" #include "llvm/ADT/GraphTraits.h"
namespace llvm { namespace llvm {
template <> struct GraphTraits<mlir::Block *> { template <>
struct GraphTraits<mlir::Block *> {
using ChildIteratorType = mlir::Block::succ_iterator; using ChildIteratorType = mlir::Block::succ_iterator;
using Node = mlir::Block; using Node = mlir::Block;
using NodeRef = Node *; using NodeRef = Node *;
@ -32,7 +33,8 @@ template <> struct GraphTraits<mlir::Block *> {
static ChildIteratorType child_end(NodeRef node) { return node->succ_end(); } static ChildIteratorType child_end(NodeRef node) { return node->succ_end(); }
}; };
template <> struct GraphTraits<Inverse<mlir::Block *>> { template <>
struct GraphTraits<Inverse<mlir::Block *>> {
using ChildIteratorType = mlir::Block::pred_iterator; using ChildIteratorType = mlir::Block::pred_iterator;
using Node = mlir::Block; using Node = mlir::Block;
using NodeRef = Node *; using NodeRef = Node *;

View File

@ -105,7 +105,8 @@ public:
/// Provide an implementation of 'classof' that compares the type id of the /// Provide an implementation of 'classof' that compares the type id of the
/// provided value with that of the concrete type. /// provided value with that of the concrete type.
template <typename T> static bool classof(T val) { template <typename T>
static bool classof(T val) {
static_assert(std::is_convertible<ConcreteT, T>::value, static_assert(std::is_convertible<ConcreteT, T>::value,
"casting from a non-convertible type"); "casting from a non-convertible type");
return val.getTypeID() == getTypeID(); return val.getTypeID() == getTypeID();
@ -182,7 +183,8 @@ public:
protected: protected:
/// Mutate the current storage instance. This will not change the unique key. /// Mutate the current storage instance. This will not change the unique key.
/// The arguments are forwarded to 'ConcreteT::mutate'. /// The arguments are forwarded to 'ConcreteT::mutate'.
template <typename... Args> LogicalResult mutate(Args &&...args) { template <typename... Args>
LogicalResult mutate(Args &&...args) {
static_assert(std::is_base_of<StorageUserTrait::IsMutable<ConcreteT>, static_assert(std::is_base_of<StorageUserTrait::IsMutable<ConcreteT>,
ConcreteT>::value, ConcreteT>::value,
"The `mutate` function expects mutable trait " "The `mutate` function expects mutable trait "
@ -192,7 +194,8 @@ protected:
} }
/// Default implementation that just returns success. /// Default implementation that just returns success.
template <typename... Args> static LogicalResult verify(Args... args) { template <typename... Args>
static LogicalResult verify(Args... args) {
return success(); return success();
} }

View File

@ -59,7 +59,8 @@ public:
/// Returns an instance of the concept object for the given interface if it /// Returns an instance of the concept object for the given interface if it
/// was registered to this type, null otherwise. This should not be used /// was registered to this type, null otherwise. This should not be used
/// directly. /// directly.
template <typename T> typename T::Concept *getInterface() const { template <typename T>
typename T::Concept *getInterface() const {
return interfaceMap.lookup<T>(); return interfaceMap.lookup<T>();
} }

View File

@ -94,11 +94,16 @@ public:
bool operator!() const { return impl == nullptr; } bool operator!() const { return impl == nullptr; }
template <typename U> bool isa() const; template <typename U>
template <typename First, typename Second, typename... Rest> bool isa() const; bool isa() const;
template <typename U> U dyn_cast() const; template <typename First, typename Second, typename... Rest>
template <typename U> U dyn_cast_or_null() const; bool isa() const;
template <typename U> U cast() const; template <typename U>
U dyn_cast() const;
template <typename U>
U dyn_cast_or_null() const;
template <typename U>
U cast() const;
// Support type casting Type to itself. // Support type casting Type to itself.
static bool classof(Type) { return true; } static bool classof(Type) { return true; }
@ -243,7 +248,8 @@ inline ::llvm::hash_code hash_value(Type arg) {
return DenseMapInfo<const Type::ImplType *>::getHashValue(arg.impl); return DenseMapInfo<const Type::ImplType *>::getHashValue(arg.impl);
} }
template <typename U> bool Type::isa() const { template <typename U>
bool Type::isa() const {
assert(impl && "isa<> used on a null type."); assert(impl && "isa<> used on a null type.");
return U::classof(*this); return U::classof(*this);
} }
@ -253,13 +259,16 @@ bool Type::isa() const {
return isa<First>() || isa<Second, Rest...>(); return isa<First>() || isa<Second, Rest...>();
} }
template <typename U> U Type::dyn_cast() const { template <typename U>
U Type::dyn_cast() const {
return isa<U>() ? U(impl) : U(nullptr); return isa<U>() ? U(impl) : U(nullptr);
} }
template <typename U> U Type::dyn_cast_or_null() const { template <typename U>
U Type::dyn_cast_or_null() const {
return (impl && isa<U>()) ? U(impl) : U(nullptr); return (impl && isa<U>()) ? U(impl) : U(nullptr);
} }
template <typename U> U Type::cast() const { template <typename U>
U Type::cast() const {
assert(isa<U>()); assert(isa<U>());
return U(impl); return U(impl);
} }
@ -269,7 +278,8 @@ template <typename U> U Type::cast() const {
namespace llvm { namespace llvm {
// Type hash just like pointers. // Type hash just like pointers.
template <> struct DenseMapInfo<mlir::Type> { template <>
struct DenseMapInfo<mlir::Type> {
static mlir::Type getEmptyKey() { static mlir::Type getEmptyKey() {
auto *pointer = llvm::DenseMapInfo<void *>::getEmptyKey(); auto *pointer = llvm::DenseMapInfo<void *>::getEmptyKey();
return mlir::Type(static_cast<mlir::Type::ImplType *>(pointer)); return mlir::Type(static_cast<mlir::Type::ImplType *>(pointer));
@ -296,7 +306,8 @@ struct DenseMapInfo<T, std::enable_if_t<std::is_base_of<mlir::Type, T>::value &&
}; };
/// We align TypeStorage by 8, so allow LLVM to steal the low bits. /// We align TypeStorage by 8, so allow LLVM to steal the low bits.
template <> struct PointerLikeTypeTraits<mlir::Type> { template <>
struct PointerLikeTypeTraits<mlir::Type> {
public: public:
static inline void *getAsVoidPointer(mlir::Type I) { static inline void *getAsVoidPointer(mlir::Type I) {
return const_cast<void *>(I.getAsOpaquePointer()); return const_cast<void *>(I.getAsOpaquePointer());

View File

@ -20,9 +20,12 @@
namespace mlir { namespace mlir {
class Operation; class Operation;
template <typename OperandType> class ValueUseIterator; template <typename OperandType>
template <typename OperandType> class FilteredValueUseIterator; class ValueUseIterator;
template <typename UseIteratorT, typename OperandType> class ValueUserIterator; template <typename OperandType>
class FilteredValueUseIterator;
template <typename UseIteratorT, typename OperandType>
class ValueUserIterator;
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
// IROperand // IROperand
@ -77,7 +80,8 @@ protected:
} }
/// Insert this operand into the given use list. /// Insert this operand into the given use list.
template <typename UseListT> void insertInto(UseListT *useList) { template <typename UseListT>
void insertInto(UseListT *useList) {
back = &useList->firstUse; back = &useList->firstUse;
nextUse = useList->firstUse; nextUse = useList->firstUse;
if (nextUse) if (nextUse)
@ -164,7 +168,8 @@ private:
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
/// This class represents a single IR object that contains a use list. /// This class represents a single IR object that contains a use list.
template <typename OperandType> class IRObjectWithUseList { template <typename OperandType>
class IRObjectWithUseList {
public: public:
~IRObjectWithUseList() { ~IRObjectWithUseList() {
assert(use_empty() && "Cannot destroy a value that still has uses!"); assert(use_empty() && "Cannot destroy a value that still has uses!");

View File

@ -53,7 +53,8 @@ public:
TypeID getEffectID() const { return id; } TypeID getEffectID() const { return id; }
/// Returns a unique instance for the given effect class. /// Returns a unique instance for the given effect class.
template <typename DerivedEffect> static DerivedEffect *get() { template <typename DerivedEffect>
static DerivedEffect *get() {
static_assert(std::is_base_of<Effect, DerivedEffect>::value, static_assert(std::is_base_of<Effect, DerivedEffect>::value,
"expected DerivedEffect to inherit from Effect"); "expected DerivedEffect to inherit from Effect");
@ -134,7 +135,8 @@ struct AutomaticAllocationScopeResource
/// applied, and an optional symbol reference or value(either operand, result, /// applied, and an optional symbol reference or value(either operand, result,
/// or region entry argument) that the effect is applied to, and an optional /// or region entry argument) that the effect is applied to, and an optional
/// parameters attribute further specifying the details of the effect. /// parameters attribute further specifying the details of the effect.
template <typename EffectT> class EffectInstance { template <typename EffectT>
class EffectInstance {
public: public:
EffectInstance(EffectT *effect, Resource *resource = DefaultResource::get()) EffectInstance(EffectT *effect, Resource *resource = DefaultResource::get())
: effect(effect), resource(resource) {} : effect(effect), resource(resource) {}

View File

@ -43,7 +43,8 @@ public:
bool isNone() const { return preservedIDs.empty(); } bool isNone() const { return preservedIDs.empty(); }
/// Preserve the given analyses. /// Preserve the given analyses.
template <typename AnalysisT> void preserve() { template <typename AnalysisT>
void preserve() {
preserve(TypeID::get<AnalysisT>()); preserve(TypeID::get<AnalysisT>());
} }
template <typename AnalysisT, typename AnalysisT2, typename... OtherAnalysesT> template <typename AnalysisT, typename AnalysisT2, typename... OtherAnalysesT>
@ -56,7 +57,8 @@ public:
/// Returns true if the given analysis has been marked as preserved. Note that /// Returns true if the given analysis has been marked as preserved. Note that
/// this simply checks for the presence of a given analysis ID and should not /// this simply checks for the presence of a given analysis ID and should not
/// be used as a general preservation checker. /// be used as a general preservation checker.
template <typename AnalysisT> bool isPreserved() const { template <typename AnalysisT>
bool isPreserved() const {
return isPreserved(TypeID::get<AnalysisT>()); return isPreserved(TypeID::get<AnalysisT>());
} }
bool isPreserved(TypeID id) const { return preservedIDs.count(id); } bool isPreserved(TypeID id) const { return preservedIDs.count(id); }
@ -110,7 +112,8 @@ struct AnalysisConcept {
}; };
/// A derived analysis model used to hold a specific analysis object. /// A derived analysis model used to hold a specific analysis object.
template <typename AnalysisT> struct AnalysisModel : public AnalysisConcept { template <typename AnalysisT>
struct AnalysisModel : public AnalysisConcept {
template <typename... Args> template <typename... Args>
explicit AnalysisModel(Args &&...args) explicit AnalysisModel(Args &&...args)
: analysis(std::forward<Args>(args)...) {} : analysis(std::forward<Args>(args)...) {}
@ -135,7 +138,8 @@ class AnalysisMap {
using ConceptMap = llvm::MapVector<TypeID, std::unique_ptr<AnalysisConcept>>; using ConceptMap = llvm::MapVector<TypeID, std::unique_ptr<AnalysisConcept>>;
/// Utility to return the name of the given analysis class. /// Utility to return the name of the given analysis class.
template <typename AnalysisT> static StringRef getAnalysisName() { template <typename AnalysisT>
static StringRef getAnalysisName() {
StringRef name = llvm::getTypeName<AnalysisT>(); StringRef name = llvm::getTypeName<AnalysisT>();
if (!name.consume_front("mlir::")) if (!name.consume_front("mlir::"))
name.consume_front("(anonymous namespace)::"); name.consume_front("(anonymous namespace)::");
@ -309,7 +313,8 @@ public:
} }
/// Query for the given analysis for the current operation. /// Query for the given analysis for the current operation.
template <typename AnalysisT> AnalysisT &getAnalysis() { template <typename AnalysisT>
AnalysisT &getAnalysis() {
return impl->analyses.getAnalysis<AnalysisT>(getPassInstrumentor(), *this); return impl->analyses.getAnalysis<AnalysisT>(getPassInstrumentor(), *this);
} }
@ -328,7 +333,8 @@ public:
} }
/// Query for an analysis of a child operation, constructing it if necessary. /// Query for an analysis of a child operation, constructing it if necessary.
template <typename AnalysisT> AnalysisT &getChildAnalysis(Operation *op) { template <typename AnalysisT>
AnalysisT &getChildAnalysis(Operation *op) {
return nest(op).template getAnalysis<AnalysisT>(); return nest(op).template getAnalysis<AnalysisT>();
} }

View File

@ -212,7 +212,8 @@ protected:
void signalPassFailure() { getPassState().irAndPassFailed.setInt(true); } void signalPassFailure() { getPassState().irAndPassFailed.setInt(true); }
/// Query an analysis for the current ir unit. /// Query an analysis for the current ir unit.
template <typename AnalysisT> AnalysisT &getAnalysis() { template <typename AnalysisT>
AnalysisT &getAnalysis() {
return getAnalysisManager().getAnalysis<AnalysisT>(); return getAnalysisManager().getAnalysis<AnalysisT>();
} }
@ -236,7 +237,8 @@ protected:
} }
/// Mark the provided analyses as preserved. /// Mark the provided analyses as preserved.
template <typename... AnalysesT> void markAnalysesPreserved() { template <typename... AnalysesT>
void markAnalysesPreserved() {
getPassState().preservedAnalyses.preserve<AnalysesT...>(); getPassState().preservedAnalyses.preserve<AnalysesT...>();
} }
void markAnalysesPreserved(TypeID id) { void markAnalysesPreserved(TypeID id) {
@ -266,7 +268,8 @@ protected:
/// Returns the analysis for the given child operation, or creates it if it /// Returns the analysis for the given child operation, or creates it if it
/// doesn't exist. /// doesn't exist.
template <typename AnalysisT> AnalysisT &getChildAnalysis(Operation *child) { template <typename AnalysisT>
AnalysisT &getChildAnalysis(Operation *child) {
return getAnalysisManager().getChildAnalysis<AnalysisT>(child); return getAnalysisManager().getChildAnalysis<AnalysisT>(child);
} }
@ -343,7 +346,8 @@ private:
/// - A 'void runOnOperation()' method. /// - A 'void runOnOperation()' method.
/// - A 'StringRef getName() const' method. /// - A 'StringRef getName() const' method.
/// - A 'std::unique_ptr<Pass> clonePass() const' method. /// - A 'std::unique_ptr<Pass> clonePass() const' method.
template <typename OpT = void> class OperationPass : public Pass { template <typename OpT = void>
class OperationPass : public Pass {
protected: protected:
OperationPass(TypeID passID) : Pass(passID, OpT::getOperationName()) {} OperationPass(TypeID passID) : Pass(passID, OpT::getOperationName()) {}
OperationPass(const OperationPass &) = default; OperationPass(const OperationPass &) = default;
@ -381,7 +385,8 @@ protected:
/// - A 'void runOnOperation()' method. /// - A 'void runOnOperation()' method.
/// - A 'StringRef getName() const' method. /// - A 'StringRef getName() const' method.
/// - A 'std::unique_ptr<Pass> clonePass() const' method. /// - A 'std::unique_ptr<Pass> clonePass() const' method.
template <> class OperationPass<void> : public Pass { template <>
class OperationPass<void> : public Pass {
protected: protected:
OperationPass(TypeID passID) : Pass(passID) {} OperationPass(TypeID passID) : Pass(passID) {}
OperationPass(const OperationPass &) = default; OperationPass(const OperationPass &) = default;
@ -431,7 +436,8 @@ protected:
/// several necessary utility methods. This should only be used for passes that /// several necessary utility methods. This should only be used for passes that
/// are not suitably represented using the declarative pass specification(i.e. /// are not suitably represented using the declarative pass specification(i.e.
/// tablegen backend). /// tablegen backend).
template <typename PassT, typename BaseT> class PassWrapper : public BaseT { template <typename PassT, typename BaseT>
class PassWrapper : public BaseT {
public: public:
/// Support isa/dyn_cast functionality for the derived pass class. /// Support isa/dyn_cast functionality for the derived pass class.
static bool classof(const Pass *pass) { static bool classof(const Pass *pass) {

View File

@ -125,7 +125,8 @@ private:
} // namespace mlir } // namespace mlir
namespace llvm { namespace llvm {
template <> struct DenseMapInfo<mlir::PassInstrumentation::PipelineParentInfo> { template <>
struct DenseMapInfo<mlir::PassInstrumentation::PipelineParentInfo> {
using T = mlir::PassInstrumentation::PipelineParentInfo; using T = mlir::PassInstrumentation::PipelineParentInfo;
using PairInfo = DenseMapInfo<std::pair<uint64_t, void *>>; using PairInfo = DenseMapInfo<std::pair<uint64_t, void *>>;

View File

@ -98,7 +98,8 @@ public:
/// pass manager. /// pass manager.
OpPassManager &nest(OperationName nestedName); OpPassManager &nest(OperationName nestedName);
OpPassManager &nest(StringRef nestedName); OpPassManager &nest(StringRef nestedName);
template <typename OpT> OpPassManager &nest() { template <typename OpT>
OpPassManager &nest() {
return nest(OpT::getOperationName()); return nest(OpT::getOperationName());
} }
@ -115,7 +116,8 @@ public:
/// Add the given pass to a nested pass manager for the given operation kind /// Add the given pass to a nested pass manager for the given operation kind
/// `OpT`. /// `OpT`.
template <typename OpT> void addNestedPass(std::unique_ptr<Pass> pass) { template <typename OpT>
void addNestedPass(std::unique_ptr<Pass> pass) {
nest<OpT>().addPass(std::move(pass)); nest<OpT>().addPass(std::move(pass));
} }

View File

@ -140,7 +140,8 @@ void registerPass(const PassAllocatorFunction &function);
/// /// At namespace scope. /// /// At namespace scope.
/// static PassRegistration<MyPass> reg; /// static PassRegistration<MyPass> reg;
/// ///
template <typename ConcretePass> struct PassRegistration { template <typename ConcretePass>
struct PassRegistration {
PassRegistration(const PassAllocatorFunction &constructor) { PassRegistration(const PassAllocatorFunction &constructor) {
registerPass(constructor); registerPass(constructor);
} }
@ -184,7 +185,8 @@ struct PassPipelineRegistration {
/// Convenience specialization of PassPipelineRegistration for EmptyPassOptions /// Convenience specialization of PassPipelineRegistration for EmptyPassOptions
/// that does not pass an empty options struct to the pass builder function. /// that does not pass an empty options struct to the pass builder function.
template <> struct PassPipelineRegistration<EmptyPipelineOptions> { template <>
struct PassPipelineRegistration<EmptyPipelineOptions> {
PassPipelineRegistration( PassPipelineRegistration(
StringRef arg, StringRef description, StringRef arg, StringRef description,
const std::function<void(OpPassManager &)> &builder) { const std::function<void(OpPassManager &)> &builder) {

View File

@ -189,7 +189,8 @@ private:
/// This class provides a handler class that can be derived from to handle /// This class provides a handler class that can be derived from to handle
/// instances of this action. The parameters to its query methods map 1-1 to the /// instances of this action. The parameters to its query methods map 1-1 to the
/// types on the action type. /// types on the action type.
template <typename... ParameterTs> class DebugAction { template <typename... ParameterTs>
class DebugAction {
public: public:
class Handler : public DebugActionManager::HandlerBase { class Handler : public DebugActionManager::HandlerBase {
public: public:

View File

@ -71,7 +71,8 @@ template <typename ConcreteType, typename ValueT, typename Traits,
class Interface : public BaseType { class Interface : public BaseType {
public: public:
using Concept = typename Traits::Concept; using Concept = typename Traits::Concept;
template <typename T> using Model = typename Traits::template Model<T>; template <typename T>
using Model = typename Traits::template Model<T>;
template <typename T> template <typename T>
using FallbackModel = typename Traits::template FallbackModel<T>; using FallbackModel = typename Traits::template FallbackModel<T>;
using InterfaceBase = using InterfaceBase =
@ -205,7 +206,8 @@ public:
/// Returns an instance of the concept object for the given interface if it /// Returns an instance of the concept object for the given interface if it
/// was registered to this map, null otherwise. /// was registered to this map, null otherwise.
template <typename T> typename T::Concept *lookup() const { template <typename T>
typename T::Concept *lookup() const {
return reinterpret_cast<typename T::Concept *>(lookup(T::getInterfaceID())); return reinterpret_cast<typename T::Concept *>(lookup(T::getInterfaceID()));
} }

View File

@ -35,41 +35,60 @@
// Forward declarations. // Forward declarations.
namespace llvm { namespace llvm {
// String types // String types
template <unsigned N> class SmallString; template <unsigned N>
class SmallString;
class StringRef; class StringRef;
class StringLiteral; class StringLiteral;
class Twine; class Twine;
// Containers. // Containers.
template <typename T> class ArrayRef; template <typename T>
class ArrayRef;
class BitVector; class BitVector;
namespace detail { namespace detail {
template <typename KeyT, typename ValueT> struct DenseMapPair; template <typename KeyT, typename ValueT>
struct DenseMapPair;
} // namespace detail } // namespace detail
template <typename KeyT, typename ValueT, typename KeyInfoT, typename BucketT> template <typename KeyT, typename ValueT, typename KeyInfoT, typename BucketT>
class DenseMap; class DenseMap;
template <typename T, typename Enable> struct DenseMapInfo; template <typename T, typename Enable>
template <typename ValueT, typename ValueInfoT> class DenseSet; struct DenseMapInfo;
template <typename ValueT, typename ValueInfoT>
class DenseSet;
class MallocAllocator; class MallocAllocator;
template <typename T> class MutableArrayRef; template <typename T>
template <typename T> class Optional; class MutableArrayRef;
template <typename... PT> class PointerUnion; template <typename T>
template <typename T, typename Vector, typename Set> class SetVector; class Optional;
template <typename T, unsigned N> class SmallPtrSet; template <typename... PT>
template <typename T> class SmallPtrSetImpl; class PointerUnion;
template <typename T, unsigned N> class SmallVector; template <typename T, typename Vector, typename Set>
template <typename T> class SmallVectorImpl; class SetVector;
template <typename AllocatorTy> class StringSet; template <typename T, unsigned N>
template <typename T, typename R> class StringSwitch; class SmallPtrSet;
template <typename T> class TinyPtrVector; template <typename T>
template <typename T, typename ResultT> class TypeSwitch; class SmallPtrSetImpl;
template <typename T, unsigned N>
class SmallVector;
template <typename T>
class SmallVectorImpl;
template <typename AllocatorTy>
class StringSet;
template <typename T, typename R>
class StringSwitch;
template <typename T>
class TinyPtrVector;
template <typename T, typename ResultT>
class TypeSwitch;
// Other common classes. // Other common classes.
class APInt; class APInt;
class APSInt; class APSInt;
class APFloat; class APFloat;
template <typename Fn> class function_ref; template <typename Fn>
template <typename IteratorT> class iterator_range; class function_ref;
template <typename IteratorT>
class iterator_range;
class raw_ostream; class raw_ostream;
class SMLoc; class SMLoc;
class SMRange; class SMRange;
@ -126,7 +145,8 @@ using TypeSwitch = llvm::TypeSwitch<T, ResultT>;
using llvm::APFloat; using llvm::APFloat;
using llvm::APInt; using llvm::APInt;
using llvm::APSInt; using llvm::APSInt;
template <typename Fn> using function_ref = llvm::function_ref<Fn>; template <typename Fn>
using function_ref = llvm::function_ref<Fn>;
using llvm::iterator_range; using llvm::iterator_range;
using llvm::raw_ostream; using llvm::raw_ostream;
using llvm::SMLoc; using llvm::SMLoc;

View File

@ -74,7 +74,8 @@ inline bool failed(LogicalResult result) { return result.failed(); }
/// This class provides support for representing a failure result, or a valid /// This class provides support for representing a failure result, or a valid
/// value of type `T`. This allows for integrating with LogicalResult, while /// value of type `T`. This allows for integrating with LogicalResult, while
/// also providing a value on the success path. /// also providing a value on the success path.
template <typename T> class LLVM_NODISCARD FailureOr : public Optional<T> { template <typename T>
class LLVM_NODISCARD FailureOr : public Optional<T> {
public: public:
/// Allow constructing from a LogicalResult. The result *must* be a failure. /// Allow constructing from a LogicalResult. The result *must* be a failure.
/// Success results should use a proper instance of type `T`. /// Success results should use a proper instance of type `T`.

View File

@ -94,7 +94,8 @@ public:
public: public:
/// Copy the specified array of elements into memory managed by our bump /// Copy the specified array of elements into memory managed by our bump
/// pointer allocator. This assumes the elements are all PODs. /// pointer allocator. This assumes the elements are all PODs.
template <typename T> ArrayRef<T> copyInto(ArrayRef<T> elements) { template <typename T>
ArrayRef<T> copyInto(ArrayRef<T> elements) {
if (elements.empty()) if (elements.empty())
return llvm::None; return llvm::None;
auto result = allocator.Allocate<T>(elements.size()); auto result = allocator.Allocate<T>(elements.size());
@ -115,7 +116,10 @@ public:
} }
/// Allocate an instance of the provided type. /// Allocate an instance of the provided type.
template <typename T> T *allocate() { return allocator.Allocate<T>(); } template <typename T>
T *allocate() {
return allocator.Allocate<T>();
}
/// Allocate 'size' bytes of 'alignment' aligned memory. /// Allocate 'size' bytes of 'alignment' aligned memory.
void *allocate(size_t size, size_t alignment) { void *allocate(size_t size, size_t alignment) {
@ -141,7 +145,8 @@ public:
/// Register a new parametric storage class, this is necessary to create /// Register a new parametric storage class, this is necessary to create
/// instances of this class type. `id` is the type identifier that will be /// instances of this class type. `id` is the type identifier that will be
/// used to identify this type when creating instances of it via 'get'. /// used to identify this type when creating instances of it via 'get'.
template <typename Storage> void registerParametricStorageType(TypeID id) { template <typename Storage>
void registerParametricStorageType(TypeID id) {
// If the storage is trivially destructible, we don't need a destructor // If the storage is trivially destructible, we don't need a destructor
// function. // function.
if (std::is_trivially_destructible<Storage>::value) if (std::is_trivially_destructible<Storage>::value)
@ -151,7 +156,8 @@ public:
}); });
} }
/// Utility override when the storage type represents the type id. /// Utility override when the storage type represents the type id.
template <typename Storage> void registerParametricStorageType() { template <typename Storage>
void registerParametricStorageType() {
registerParametricStorageType<Storage>(TypeID::get<Storage>()); registerParametricStorageType<Storage>(TypeID::get<Storage>());
} }
/// Register a new singleton storage class, this is necessary to get the /// Register a new singleton storage class, this is necessary to get the
@ -170,7 +176,8 @@ public:
}; };
registerSingletonImpl(id, ctorFn); registerSingletonImpl(id, ctorFn);
} }
template <typename Storage> void registerSingletonStorageType(TypeID id) { template <typename Storage>
void registerSingletonStorageType(TypeID id) {
registerSingletonStorageType<Storage>(id, llvm::None); registerSingletonStorageType<Storage>(id, llvm::None);
} }
/// Utility override when the storage type represents the type id. /// Utility override when the storage type represents the type id.
@ -219,11 +226,13 @@ public:
/// Gets a uniqued instance of 'Storage' which is a singleton storage type. /// Gets a uniqued instance of 'Storage' which is a singleton storage type.
/// 'id' is the type id used when registering the storage instance. /// 'id' is the type id used when registering the storage instance.
template <typename Storage> Storage *get(TypeID id) { template <typename Storage>
Storage *get(TypeID id) {
return static_cast<Storage *>(getSingletonImpl(id)); return static_cast<Storage *>(getSingletonImpl(id));
} }
/// Utility override when the storage type represents the type id. /// Utility override when the storage type represents the type id.
template <typename Storage> Storage *get() { template <typename Storage>
Storage *get() {
return get<Storage>(TypeID::get<Storage>()); return get<Storage>(TypeID::get<Storage>());
} }

View File

@ -334,7 +334,8 @@ public:
MLIR_DECLARE_EXPLICIT_TYPE_ID(void) MLIR_DECLARE_EXPLICIT_TYPE_ID(void)
namespace llvm { namespace llvm {
template <> struct DenseMapInfo<mlir::TypeID> { template <>
struct DenseMapInfo<mlir::TypeID> {
static inline mlir::TypeID getEmptyKey() { static inline mlir::TypeID getEmptyKey() {
void *pointer = llvm::DenseMapInfo<void *>::getEmptyKey(); void *pointer = llvm::DenseMapInfo<void *>::getEmptyKey();
return mlir::TypeID::getFromOpaquePointer(pointer); return mlir::TypeID::getFromOpaquePointer(pointer);
@ -350,7 +351,8 @@ template <> struct DenseMapInfo<mlir::TypeID> {
}; };
/// We align TypeID::Storage by 8, so allow LLVM to steal the low bits. /// We align TypeID::Storage by 8, so allow LLVM to steal the low bits.
template <> struct PointerLikeTypeTraits<mlir::TypeID> { template <>
struct PointerLikeTypeTraits<mlir::TypeID> {
static inline void *getAsVoidPointer(mlir::TypeID info) { static inline void *getAsVoidPointer(mlir::TypeID info) {
return const_cast<void *>(info.getAsOpaquePointer()); return const_cast<void *>(info.getAsOpaquePointer());
} }

View File

@ -216,15 +216,16 @@ private:
std::string escapeString(StringRef value); std::string escapeString(StringRef value);
namespace detail { namespace detail {
template <typename> struct stringifier { template <typename>
template <typename T> static std::string apply(T &&t) { struct stringifier {
template <typename T>
static std::string apply(T &&t) {
return std::string(std::forward<T>(t)); return std::string(std::forward<T>(t));
} }
}; };
template <> struct stringifier<Twine> { template <>
static std::string apply(const Twine &twine) { struct stringifier<Twine> {
return twine.str(); static std::string apply(const Twine &twine) { return twine.str(); }
}
}; };
template <typename OptionalT> template <typename OptionalT>
struct stringifier<Optional<OptionalT>> { struct stringifier<Optional<OptionalT>> {
@ -235,7 +236,8 @@ struct stringifier<Optional<OptionalT>> {
} // namespace detail } // namespace detail
/// Generically convert a value to a std::string. /// Generically convert a value to a std::string.
template <typename T> std::string stringify(T &&t) { template <typename T>
std::string stringify(T &&t) {
return detail::stringifier<std::remove_reference_t<std::remove_const_t<T>>>:: return detail::stringifier<std::remove_reference_t<std::remove_const_t<T>>>::
apply(std::forward<T>(t)); apply(std::forward<T>(t));
} }

View File

@ -165,19 +165,24 @@ public:
return s.str(); return s.str();
} }
template <unsigned N> SmallString<N> sstr() const { template <unsigned N>
SmallString<N> sstr() const {
SmallString<N> result; SmallString<N> result;
llvm::raw_svector_ostream s(result); llvm::raw_svector_ostream s(result);
format(s); format(s);
return result; return result;
} }
template <unsigned N> operator SmallString<N>() const { return sstr<N>(); } template <unsigned N>
operator SmallString<N>() const {
return sstr<N>();
}
operator std::string() const { return str(); } operator std::string() const { return str(); }
}; };
template <typename Tuple> class FmtObject : public FmtObjectBase { template <typename Tuple>
class FmtObject : public FmtObjectBase {
// Storage for the parameter adapters. Since the base class erases the type // Storage for the parameter adapters. Since the base class erases the type
// of the parameters, we have to own the storage for the parameters here, and // of the parameters, we have to own the storage for the parameters here, and
// have the base class store type-erased pointers into this tuple. // have the base class store type-erased pointers into this tuple.

View File

@ -34,8 +34,7 @@ class VariableDecl;
/// This class provides a convenient API for interacting with source names. It /// This class provides a convenient API for interacting with source names. It
/// contains a string name as well as the source location for that name. /// contains a string name as well as the source location for that name.
struct Name { struct Name {
static const Name &create(Context &ctx, StringRef name, static const Name &create(Context &ctx, StringRef name, SMRange location);
SMRange location);
/// Return the raw string name. /// Return the raw string name.
StringRef getName() const { return name; } StringRef getName() const { return name; }
@ -47,8 +46,7 @@ private:
Name() = delete; Name() = delete;
Name(const Name &) = delete; Name(const Name &) = delete;
Name &operator=(const Name &) = delete; Name &operator=(const Name &) = delete;
Name(StringRef name, SMRange location) Name(StringRef name, SMRange location) : name(name), location(location) {}
: name(name), location(location) {}
/// The string name of the decl. /// The string name of the decl.
StringRef name; StringRef name;
@ -80,13 +78,15 @@ public:
/// Lookup a decl with the given name starting from this scope. Returns /// Lookup a decl with the given name starting from this scope. Returns
/// nullptr if no decl could be found. /// nullptr if no decl could be found.
Decl *lookup(StringRef name); Decl *lookup(StringRef name);
template <typename T> T *lookup(StringRef name) { template <typename T>
T *lookup(StringRef name) {
return dyn_cast_or_null<T>(lookup(name)); return dyn_cast_or_null<T>(lookup(name));
} }
const Decl *lookup(StringRef name) const { const Decl *lookup(StringRef name) const {
return const_cast<DeclScope *>(this)->lookup(name); return const_cast<DeclScope *>(this)->lookup(name);
} }
template <typename T> const T *lookup(StringRef name) const { template <typename T>
const T *lookup(StringRef name) const {
return dyn_cast_or_null<T>(lookup(name)); return dyn_cast_or_null<T>(lookup(name));
} }
@ -107,7 +107,8 @@ private:
class Node { class Node {
public: public:
/// This CRTP class provides several utilies when defining new AST nodes. /// This CRTP class provides several utilies when defining new AST nodes.
template <typename T, typename BaseT> class NodeBase : public BaseT { template <typename T, typename BaseT>
class NodeBase : public BaseT {
public: public:
using Base = NodeBase<T, BaseT>; using Base = NodeBase<T, BaseT>;
@ -208,15 +209,13 @@ private:
/// to define variables. /// to define variables.
class LetStmt final : public Node::NodeBase<LetStmt, Stmt> { class LetStmt final : public Node::NodeBase<LetStmt, Stmt> {
public: public:
static LetStmt *create(Context &ctx, SMRange loc, static LetStmt *create(Context &ctx, SMRange loc, VariableDecl *varDecl);
VariableDecl *varDecl);
/// Return the variable defined by this statement. /// Return the variable defined by this statement.
VariableDecl *getVarDecl() const { return varDecl; } VariableDecl *getVarDecl() const { return varDecl; }
private: private:
LetStmt(SMRange loc, VariableDecl *varDecl) LetStmt(SMRange loc, VariableDecl *varDecl) : Base(loc), varDecl(varDecl) {}
: Base(loc), varDecl(varDecl) {}
/// The variable defined by this statement. /// The variable defined by this statement.
VariableDecl *varDecl; VariableDecl *varDecl;
@ -351,8 +350,7 @@ public:
static bool classof(const Node *node); static bool classof(const Node *node);
protected: protected:
Expr(TypeID typeID, SMRange loc, Type type) Expr(TypeID typeID, SMRange loc, Type type) : Stmt(typeID, loc), type(type) {}
: Stmt(typeID, loc), type(type) {}
private: private:
/// The type of this expression. /// The type of this expression.
@ -367,8 +365,7 @@ private:
/// textual assembly format of that attribute. /// textual assembly format of that attribute.
class AttributeExpr : public Node::NodeBase<AttributeExpr, Expr> { class AttributeExpr : public Node::NodeBase<AttributeExpr, Expr> {
public: public:
static AttributeExpr *create(Context &ctx, SMRange loc, static AttributeExpr *create(Context &ctx, SMRange loc, StringRef value);
StringRef value);
/// Get the raw value of this expression. This is the textual assembly format /// Get the raw value of this expression. This is the textual assembly format
/// of the MLIR Attribute. /// of the MLIR Attribute.
@ -426,8 +423,7 @@ private:
/// This expression represents a reference to a Decl node. /// This expression represents a reference to a Decl node.
class DeclRefExpr : public Node::NodeBase<DeclRefExpr, Expr> { class DeclRefExpr : public Node::NodeBase<DeclRefExpr, Expr> {
public: public:
static DeclRefExpr *create(Context &ctx, SMRange loc, Decl *decl, static DeclRefExpr *create(Context &ctx, SMRange loc, Decl *decl, Type type);
Type type);
/// Get the decl referenced by this expression. /// Get the decl referenced by this expression.
Decl *getDecl() const { return decl; } Decl *getDecl() const { return decl; }
@ -459,8 +455,8 @@ public:
StringRef getMemberName() const { return memberName; } StringRef getMemberName() const { return memberName; }
private: private:
MemberAccessExpr(SMRange loc, const Expr *parentExpr, MemberAccessExpr(SMRange loc, const Expr *parentExpr, StringRef memberName,
StringRef memberName, Type type) Type type)
: Base(loc, type), parentExpr(parentExpr), memberName(memberName) {} : Base(loc, type), parentExpr(parentExpr), memberName(memberName) {}
/// The parent expression of this access. /// The parent expression of this access.
@ -578,8 +574,7 @@ private:
class TupleExpr final : public Node::NodeBase<TupleExpr, Expr>, class TupleExpr final : public Node::NodeBase<TupleExpr, Expr>,
private llvm::TrailingObjects<TupleExpr, Expr *> { private llvm::TrailingObjects<TupleExpr, Expr *> {
public: public:
static TupleExpr *create(Context &ctx, SMRange loc, static TupleExpr *create(Context &ctx, SMRange loc, ArrayRef<Expr *> elements,
ArrayRef<Expr *> elements,
ArrayRef<StringRef> elementNames); ArrayRef<StringRef> elementNames);
/// Return the element expressions of this tuple. /// Return the element expressions of this tuple.
@ -697,8 +692,7 @@ public:
static bool classof(const Node *node); static bool classof(const Node *node);
protected: protected:
CoreConstraintDecl(TypeID typeID, SMRange loc, CoreConstraintDecl(TypeID typeID, SMRange loc, const Name *name = nullptr)
const Name *name = nullptr)
: ConstraintDecl(typeID, loc, name) {} : ConstraintDecl(typeID, loc, name) {}
}; };
@ -786,8 +780,7 @@ protected:
class ValueConstraintDecl class ValueConstraintDecl
: public Node::NodeBase<ValueConstraintDecl, CoreConstraintDecl> { : public Node::NodeBase<ValueConstraintDecl, CoreConstraintDecl> {
public: public:
static ValueConstraintDecl *create(Context &ctx, SMRange loc, static ValueConstraintDecl *create(Context &ctx, SMRange loc, Expr *typeExpr);
Expr *typeExpr);
/// Return the optional type the value is constrained to. /// Return the optional type the value is constrained to.
Expr *getTypeExpr() { return typeExpr; } Expr *getTypeExpr() { return typeExpr; }
@ -996,8 +989,8 @@ private:
/// This Decl represents a single Pattern. /// This Decl represents a single Pattern.
class PatternDecl : public Node::NodeBase<PatternDecl, Decl> { class PatternDecl : public Node::NodeBase<PatternDecl, Decl> {
public: public:
static PatternDecl *create(Context &ctx, SMRange location, static PatternDecl *create(Context &ctx, SMRange location, const Name *name,
const Name *name, Optional<uint16_t> benefit, Optional<uint16_t> benefit,
bool hasBoundedRecursion, bool hasBoundedRecursion,
const CompoundStmt *body); const CompoundStmt *body);
@ -1249,8 +1242,7 @@ private:
class Module final : public Node::NodeBase<Module, Node>, class Module final : public Node::NodeBase<Module, Node>,
private llvm::TrailingObjects<Module, Decl *> { private llvm::TrailingObjects<Module, Decl *> {
public: public:
static Module *create(Context &ctx, SMLoc loc, static Module *create(Context &ctx, SMLoc loc, ArrayRef<Decl *> children);
ArrayRef<Decl *> children);
/// Return the children of this module. /// Return the children of this module.
MutableArrayRef<Decl *> getChildren() { MutableArrayRef<Decl *> getChildren() {

View File

@ -62,20 +62,25 @@ public:
explicit operator bool() const { return impl; } explicit operator bool() const { return impl; }
/// Provide type casting support. /// Provide type casting support.
template <typename U> bool isa() const { template <typename U>
bool isa() const {
assert(impl && "isa<> used on a null type."); assert(impl && "isa<> used on a null type.");
return U::classof(*this); return U::classof(*this);
} }
template <typename U, typename V, typename... Others> bool isa() const { template <typename U, typename V, typename... Others>
bool isa() const {
return isa<U>() || isa<V, Others...>(); return isa<U>() || isa<V, Others...>();
} }
template <typename U> U dyn_cast() const { template <typename U>
U dyn_cast() const {
return isa<U>() ? U(impl) : U(nullptr); return isa<U>() ? U(impl) : U(nullptr);
} }
template <typename U> U dyn_cast_or_null() const { template <typename U>
U dyn_cast_or_null() const {
return (impl && isa<U>()) ? U(impl) : U(nullptr); return (impl && isa<U>()) ? U(impl) : U(nullptr);
} }
template <typename U> U cast() const { template <typename U>
U cast() const {
assert(isa<U>()); assert(isa<U>());
return U(impl); return U(impl);
} }
@ -99,7 +104,8 @@ public:
protected: protected:
/// Return the internal storage instance of this type reinterpreted as the /// Return the internal storage instance of this type reinterpreted as the
/// given derived storage type. /// given derived storage type.
template <typename T> const T *getImplAs() const { template <typename T>
const T *getImplAs() const {
return static_cast<const T *>(impl); return static_cast<const T *>(impl);
} }
@ -296,7 +302,8 @@ MLIR_DECLARE_EXPLICIT_TYPE_ID(mlir::pdll::ast::detail::TypeTypeStorage)
MLIR_DECLARE_EXPLICIT_TYPE_ID(mlir::pdll::ast::detail::ValueTypeStorage) MLIR_DECLARE_EXPLICIT_TYPE_ID(mlir::pdll::ast::detail::ValueTypeStorage)
namespace llvm { namespace llvm {
template <> struct DenseMapInfo<mlir::pdll::ast::Type> { template <>
struct DenseMapInfo<mlir::pdll::ast::Type> {
static mlir::pdll::ast::Type getEmptyKey() { static mlir::pdll::ast::Type getEmptyKey() {
void *pointer = llvm::DenseMapInfo<void *>::getEmptyKey(); void *pointer = llvm::DenseMapInfo<void *>::getEmptyKey();
return mlir::pdll::ast::Type( return mlir::pdll::ast::Type(

View File

@ -20,8 +20,7 @@ namespace mlir {
class Pass; class Pass;
/// Creates a pass to print op graphs. /// Creates a pass to print op graphs.
std::unique_ptr<Pass> std::unique_ptr<Pass> createPrintOpGraphPass(raw_ostream &os = llvm::errs());
createPrintOpGraphPass(raw_ostream &os = llvm::errs());
} // namespace mlir } // namespace mlir

View File

@ -11,8 +11,8 @@
// //
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
#include "../PassDetail.h"
#include "mlir/Conversion/BufferizationToMemRef/BufferizationToMemRef.h" #include "mlir/Conversion/BufferizationToMemRef/BufferizationToMemRef.h"
#include "../PassDetail.h"
#include "mlir/Dialect/Arithmetic/IR/Arithmetic.h" #include "mlir/Dialect/Arithmetic/IR/Arithmetic.h"
#include "mlir/Dialect/Bufferization/IR/Bufferization.h" #include "mlir/Dialect/Bufferization/IR/Bufferization.h"
#include "mlir/Dialect/MemRef/IR/MemRef.h" #include "mlir/Dialect/MemRef/IR/MemRef.h"

View File

@ -766,8 +766,8 @@ struct SqrtOpConversion : public OpConversionPattern<complex::SqrtOp> {
Value absArg = b.create<complex::AbsOp>(elementType, arg); Value absArg = b.create<complex::AbsOp>(elementType, arg);
Value addAbs = b.create<arith::AddFOp>(absLhs, absArg); Value addAbs = b.create<arith::AddFOp>(absLhs, absArg);
Value half = b.create<arith::ConstantOp>( Value half = b.create<arith::ConstantOp>(elementType,
elementType, b.getFloatAttr(elementType, 0.5)); b.getFloatAttr(elementType, 0.5));
Value halfAddAbs = b.create<arith::MulFOp>(addAbs, half); Value halfAddAbs = b.create<arith::MulFOp>(addAbs, half);
Value sqrtAddAbs = b.create<math::SqrtOp>(halfAddAbs); Value sqrtAddAbs = b.create<math::SqrtOp>(halfAddAbs);

View File

@ -877,8 +877,8 @@ mlir::createGpuToLLVMConversionPass() {
return std::make_unique<GpuToLLVMConversionPass>(); return std::make_unique<GpuToLLVMConversionPass>();
} }
void mlir::populateGpuToLLVMConversionPatterns( void mlir::populateGpuToLLVMConversionPatterns(LLVMTypeConverter &converter,
LLVMTypeConverter &converter, RewritePatternSet &patterns, RewritePatternSet &patterns,
StringRef gpuBinaryAnnotation) { StringRef gpuBinaryAnnotation) {
converter.addConversion( converter.addConversion(
[context = &converter.getContext()](gpu::AsyncTokenType type) -> Type { [context = &converter.getContext()](gpu::AsyncTokenType type) -> Type {

View File

@ -146,7 +146,6 @@ LogicalResult SingleWorkgroupReduction::matchAndRewrite(
// TODO: Load to Workgroup storage class first. // TODO: Load to Workgroup storage class first.
// Get the input element accessed by this invocation. // Get the input element accessed by this invocation.
Value inputElementPtr = spirv::getElementPtr( Value inputElementPtr = spirv::getElementPtr(
*typeConverter, originalInputType, convertedInput, {x}, loc, rewriter); *typeConverter, originalInputType, convertedInput, {x}, loc, rewriter);

View File

@ -111,7 +111,6 @@ LogicalResult mlir::linalg::LinalgOpToLibraryCallRewrite::matchAndRewrite(
return success(); return success();
} }
/// Populate the given list with patterns that convert from Linalg to Standard. /// Populate the given list with patterns that convert from Linalg to Standard.
void mlir::linalg::populateLinalgToStandardConversionPatterns( void mlir::linalg::populateLinalgToStandardConversionPatterns(
RewritePatternSet &patterns) { RewritePatternSet &patterns) {

View File

@ -2753,7 +2753,8 @@ LogicalResult AffineStoreOp::fold(ArrayRef<Attribute> cstOperands,
// AffineMinMaxOpBase // AffineMinMaxOpBase
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
template <typename T> static LogicalResult verifyAffineMinMaxOp(T op) { template <typename T>
static LogicalResult verifyAffineMinMaxOp(T op) {
// Verify that operand count matches affine map dimension and symbol count. // Verify that operand count matches affine map dimension and symbol count.
if (op.getNumOperands() != if (op.getNumOperands() !=
op.getMap().getNumDims() + op.getMap().getNumSymbols()) op.getMap().getNumDims() + op.getMap().getNumSymbols())
@ -2762,7 +2763,8 @@ template <typename T> static LogicalResult verifyAffineMinMaxOp(T op) {
return success(); return success();
} }
template <typename T> static void printAffineMinMaxOp(OpAsmPrinter &p, T op) { template <typename T>
static void printAffineMinMaxOp(OpAsmPrinter &p, T op) {
p << ' ' << op->getAttr(T::getMapAttrStrName()); p << ' ' << op->getAttr(T::getMapAttrStrName());
auto operands = op.getOperands(); auto operands = op.getOperands();
unsigned numDims = op.getMap().getNumDims(); unsigned numDims = op.getMap().getNumDims();
@ -2870,7 +2872,8 @@ struct DeduplicateAffineMinMaxExpressions : public OpRewritePattern<T> {
/// ///
/// %1 = affine.min affine_map< /// %1 = affine.min affine_map<
/// ()[s0, s1] -> (s0 + 4, s1 + 16, s1 * 8)> ()[%sym2, %sym1] /// ()[s0, s1] -> (s0 + 4, s1 + 16, s1 * 8)> ()[%sym2, %sym1]
template <typename T> struct MergeAffineMinMaxOp : public OpRewritePattern<T> { template <typename T>
struct MergeAffineMinMaxOp : public OpRewritePattern<T> {
using OpRewritePattern<T>::OpRewritePattern; using OpRewritePattern<T>::OpRewritePattern;
LogicalResult matchAndRewrite(T affineOp, LogicalResult matchAndRewrite(T affineOp,

View File

@ -209,8 +209,8 @@ OpFoldResult arith::AddIOp::fold(ArrayRef<Attribute> operands) {
operands, [](APInt a, const APInt &b) { return std::move(a) + b; }); operands, [](APInt a, const APInt &b) { return std::move(a) + b; });
} }
void arith::AddIOp::getCanonicalizationPatterns( void arith::AddIOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
RewritePatternSet &patterns, MLIRContext *context) { MLIRContext *context) {
patterns.add<AddIAddConstant, AddISubConstantRHS, AddISubConstantLHS>( patterns.add<AddIAddConstant, AddISubConstantRHS, AddISubConstantLHS>(
context); context);
} }
@ -231,8 +231,8 @@ OpFoldResult arith::SubIOp::fold(ArrayRef<Attribute> operands) {
operands, [](APInt a, const APInt &b) { return std::move(a) - b; }); operands, [](APInt a, const APInt &b) { return std::move(a) - b; });
} }
void arith::SubIOp::getCanonicalizationPatterns( void arith::SubIOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
RewritePatternSet &patterns, MLIRContext *context) { MLIRContext *context) {
patterns patterns
.add<SubIRHSAddConstant, SubILHSAddConstant, SubIRHSSubConstantRHS, .add<SubIRHSAddConstant, SubILHSAddConstant, SubIRHSSubConstantRHS,
SubIRHSSubConstantLHS, SubILHSSubConstantRHS, SubILHSSubConstantLHS>( SubIRHSSubConstantLHS, SubILHSSubConstantRHS, SubILHSSubConstantLHS>(
@ -539,8 +539,8 @@ OpFoldResult arith::XOrIOp::fold(ArrayRef<Attribute> operands) {
operands, [](APInt a, const APInt &b) { return std::move(a) ^ b; }); operands, [](APInt a, const APInt &b) { return std::move(a) ^ b; });
} }
void arith::XOrIOp::getCanonicalizationPatterns( void arith::XOrIOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
RewritePatternSet &patterns, MLIRContext *context) { MLIRContext *context) {
patterns.add<XOrINotCmpI>(context); patterns.add<XOrINotCmpI>(context);
} }
@ -921,8 +921,8 @@ bool arith::ExtSIOp::areCastCompatible(TypeRange inputs, TypeRange outputs) {
return checkWidthChangeCast<std::greater, IntegerType>(inputs, outputs); return checkWidthChangeCast<std::greater, IntegerType>(inputs, outputs);
} }
void arith::ExtSIOp::getCanonicalizationPatterns( void arith::ExtSIOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
RewritePatternSet &patterns, MLIRContext *context) { MLIRContext *context) {
patterns.add<ExtSIOfExtUI>(context); patterns.add<ExtSIOfExtUI>(context);
} }
@ -1017,8 +1017,8 @@ LogicalResult arith::TruncFOp::verify() {
// AndIOp // AndIOp
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
void arith::AndIOp::getCanonicalizationPatterns( void arith::AndIOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
RewritePatternSet &patterns, MLIRContext *context) { MLIRContext *context) {
patterns.add<AndOfExtUI, AndOfExtSI>(context); patterns.add<AndOfExtUI, AndOfExtSI>(context);
} }
@ -1026,8 +1026,8 @@ void arith::AndIOp::getCanonicalizationPatterns(
// OrIOp // OrIOp
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
void arith::OrIOp::getCanonicalizationPatterns( void arith::OrIOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
RewritePatternSet &patterns, MLIRContext *context) { MLIRContext *context) {
patterns.add<OrOfExtUI, OrOfExtSI>(context); patterns.add<OrOfExtUI, OrOfExtSI>(context);
} }
@ -1226,8 +1226,8 @@ OpFoldResult arith::BitcastOp::fold(ArrayRef<Attribute> operands) {
return IntegerAttr::get(resType, bits); return IntegerAttr::get(resType, bits);
} }
void arith::BitcastOp::getCanonicalizationPatterns( void arith::BitcastOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
RewritePatternSet &patterns, MLIRContext *context) { MLIRContext *context) {
patterns.add<BitcastOfBitcast>(context); patterns.add<BitcastOfBitcast>(context);
} }

View File

@ -212,8 +212,7 @@ struct OneShotBufferizePass
}; };
// Configure op filter. // Configure op filter.
OpFilter::Entry::FilterFn filterFn = OpFilter::Entry::FilterFn filterFn = [&](Operation *op) {
[&](Operation *op) {
// Filter may be specified via options. // Filter may be specified via options.
if (this->dialectFilter.hasValue()) if (this->dialectFilter.hasValue())
return llvm::is_contained(this->dialectFilter, return llvm::is_contained(this->dialectFilter,

View File

@ -133,8 +133,7 @@ SerializeToCubinPass::serializeISA(const std::string &isa) {
// Register pass to serialize GPU kernel functions to a CUBIN binary annotation. // Register pass to serialize GPU kernel functions to a CUBIN binary annotation.
void mlir::registerGpuSerializeToCubinPass() { void mlir::registerGpuSerializeToCubinPass() {
PassRegistration<SerializeToCubinPass> registerSerializeToCubin( PassRegistration<SerializeToCubinPass> registerSerializeToCubin([] {
[] {
// Initialize LLVM NVPTX backend. // Initialize LLVM NVPTX backend.
LLVMInitializeNVPTXTarget(); LLVMInitializeNVPTXTarget();
LLVMInitializeNVPTXTargetInfo(); LLVMInitializeNVPTXTargetInfo();

View File

@ -360,8 +360,7 @@ SerializeToHsacoPass::assembleIsa(const std::string &isa) {
} }
llvm::SourceMgr srcMgr; llvm::SourceMgr srcMgr;
srcMgr.AddNewSourceBuffer(llvm::MemoryBuffer::getMemBuffer(isa), srcMgr.AddNewSourceBuffer(llvm::MemoryBuffer::getMemBuffer(isa), SMLoc());
SMLoc());
const llvm::MCTargetOptions mcOptions; const llvm::MCTargetOptions mcOptions;
std::unique_ptr<llvm::MCRegisterInfo> mri( std::unique_ptr<llvm::MCRegisterInfo> mri(
@ -469,8 +468,7 @@ SerializeToHsacoPass::serializeISA(const std::string &isa) {
// Register pass to serialize GPU kernel functions to a HSACO binary annotation. // Register pass to serialize GPU kernel functions to a HSACO binary annotation.
void mlir::registerGpuSerializeToHsacoPass() { void mlir::registerGpuSerializeToHsacoPass() {
PassRegistration<SerializeToHsacoPass> registerSerializeToHSACO( PassRegistration<SerializeToHsacoPass> registerSerializeToHSACO([] {
[] {
// Initialize LLVM AMDGPU backend. // Initialize LLVM AMDGPU backend.
LLVMInitializeAMDGPUAsmParser(); LLVMInitializeAMDGPUAsmParser();
LLVMInitializeAMDGPUAsmPrinter(); LLVMInitializeAMDGPUAsmPrinter();
@ -478,8 +476,8 @@ void mlir::registerGpuSerializeToHsacoPass() {
LLVMInitializeAMDGPUTargetInfo(); LLVMInitializeAMDGPUTargetInfo();
LLVMInitializeAMDGPUTargetMC(); LLVMInitializeAMDGPUTargetMC();
return std::make_unique<SerializeToHsacoPass>("amdgcn-amd-amdhsa", "", return std::make_unique<SerializeToHsacoPass>("amdgcn-amd-amdhsa", "", "",
"", 2); 2);
}); });
} }

View File

@ -485,7 +485,8 @@ recordStructIndices(Type baseGEPType, unsigned indexPos,
unsigned dynamicIndexPos = indexPos; unsigned dynamicIndexPos = indexPos;
if (!isStaticIndex) if (!isStaticIndex)
dynamicIndexPos = llvm::count(structIndices.take_front(indexPos + 1), dynamicIndexPos = llvm::count(structIndices.take_front(indexPos + 1),
LLVM::GEPOp::kDynamicIndex) - 1; LLVM::GEPOp::kDynamicIndex) -
1;
return llvm::TypeSwitch<Type, llvm::Error>(baseGEPType) return llvm::TypeSwitch<Type, llvm::Error>(baseGEPType)
.Case<LLVMStructType>([&](LLVMStructType structType) -> llvm::Error { .Case<LLVMStructType>([&](LLVMStructType structType) -> llvm::Error {

View File

@ -311,8 +311,7 @@ static LLVMArrayType parseArrayType(AsmParser &parser) {
/// error at `subtypesLoc` in case of failure. /// error at `subtypesLoc` in case of failure.
static LLVMStructType trySetStructBody(LLVMStructType type, static LLVMStructType trySetStructBody(LLVMStructType type,
ArrayRef<Type> subtypes, bool isPacked, ArrayRef<Type> subtypes, bool isPacked,
AsmParser &parser, AsmParser &parser, SMLoc subtypesLoc) {
SMLoc subtypesLoc) {
for (Type t : subtypes) { for (Type t : subtypes) {
if (!LLVMStructType::isValidElementType(t)) { if (!LLVMStructType::isValidElementType(t)) {
parser.emitError(subtypesLoc) parser.emitError(subtypesLoc)

View File

@ -127,7 +127,7 @@ struct ComposeSubViewOpPattern : public OpRewritePattern<memref::SubViewOp> {
} // namespace } // namespace
void mlir::memref::populateComposeSubViewPatterns( void mlir::memref::populateComposeSubViewPatterns(RewritePatternSet &patterns,
RewritePatternSet &patterns, MLIRContext *context) { MLIRContext *context) {
patterns.add<ComposeSubViewOpPattern>(context); patterns.add<ComposeSubViewOpPattern>(context);
} }

View File

@ -483,7 +483,8 @@ namespace {
// parseAndVerify does the actual parsing and verification of individual // parseAndVerify does the actual parsing and verification of individual
// elements. This is a functor since parsing the last element of the list // elements. This is a functor since parsing the last element of the list
// (termination condition) needs partial specialization. // (termination condition) needs partial specialization.
template <typename ParseType, typename... Args> struct ParseCommaSeparatedList { template <typename ParseType, typename... Args>
struct ParseCommaSeparatedList {
Optional<std::tuple<ParseType, Args...>> Optional<std::tuple<ParseType, Args...>>
operator()(SPIRVDialect const &dialect, DialectAsmParser &parser) const { operator()(SPIRVDialect const &dialect, DialectAsmParser &parser) const {
auto parseVal = parseAndVerify<ParseType>(dialect, parser); auto parseVal = parseAndVerify<ParseType>(dialect, parser);
@ -503,7 +504,8 @@ template <typename ParseType, typename... Args> struct ParseCommaSeparatedList {
// Partial specialization of the function to parse a comma separated list of // Partial specialization of the function to parse a comma separated list of
// specs to parse the last element of the list. // specs to parse the last element of the list.
template <typename ParseType> struct ParseCommaSeparatedList<ParseType> { template <typename ParseType>
struct ParseCommaSeparatedList<ParseType> {
Optional<std::tuple<ParseType>> operator()(SPIRVDialect const &dialect, Optional<std::tuple<ParseType>> operator()(SPIRVDialect const &dialect,
DialectAsmParser &parser) const { DialectAsmParser &parser) const {
if (auto value = parseAndVerify<ParseType>(dialect, parser)) if (auto value = parseAndVerify<ParseType>(dialect, parser))

View File

@ -259,33 +259,42 @@ void CooperativeMatrixNVType::getCapabilities(
// ImageType // ImageType
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
template <typename T> static constexpr unsigned getNumBits() { return 0; } template <typename T>
template <> constexpr unsigned getNumBits<Dim>() { static constexpr unsigned getNumBits() {
return 0;
}
template <>
constexpr unsigned getNumBits<Dim>() {
static_assert((1 << 3) > getMaxEnumValForDim(), static_assert((1 << 3) > getMaxEnumValForDim(),
"Not enough bits to encode Dim value"); "Not enough bits to encode Dim value");
return 3; return 3;
} }
template <> constexpr unsigned getNumBits<ImageDepthInfo>() { template <>
constexpr unsigned getNumBits<ImageDepthInfo>() {
static_assert((1 << 2) > getMaxEnumValForImageDepthInfo(), static_assert((1 << 2) > getMaxEnumValForImageDepthInfo(),
"Not enough bits to encode ImageDepthInfo value"); "Not enough bits to encode ImageDepthInfo value");
return 2; return 2;
} }
template <> constexpr unsigned getNumBits<ImageArrayedInfo>() { template <>
constexpr unsigned getNumBits<ImageArrayedInfo>() {
static_assert((1 << 1) > getMaxEnumValForImageArrayedInfo(), static_assert((1 << 1) > getMaxEnumValForImageArrayedInfo(),
"Not enough bits to encode ImageArrayedInfo value"); "Not enough bits to encode ImageArrayedInfo value");
return 1; return 1;
} }
template <> constexpr unsigned getNumBits<ImageSamplingInfo>() { template <>
constexpr unsigned getNumBits<ImageSamplingInfo>() {
static_assert((1 << 1) > getMaxEnumValForImageSamplingInfo(), static_assert((1 << 1) > getMaxEnumValForImageSamplingInfo(),
"Not enough bits to encode ImageSamplingInfo value"); "Not enough bits to encode ImageSamplingInfo value");
return 1; return 1;
} }
template <> constexpr unsigned getNumBits<ImageSamplerUseInfo>() { template <>
constexpr unsigned getNumBits<ImageSamplerUseInfo>() {
static_assert((1 << 2) > getMaxEnumValForImageSamplerUseInfo(), static_assert((1 << 2) > getMaxEnumValForImageSamplerUseInfo(),
"Not enough bits to encode ImageSamplerUseInfo value"); "Not enough bits to encode ImageSamplerUseInfo value");
return 2; return 2;
} }
template <> constexpr unsigned getNumBits<ImageFormat>() { template <>
constexpr unsigned getNumBits<ImageFormat>() {
static_assert((1 << 6) > getMaxEnumValForImageFormat(), static_assert((1 << 6) > getMaxEnumValForImageFormat(),
"Not enough bits to encode ImageFormat value"); "Not enough bits to encode ImageFormat value");
return 6; return 6;

View File

@ -8,8 +8,8 @@
#include <utility> #include <utility>
#include "mlir/IR/AffineExpr.h"
#include "AffineExprDetail.h" #include "AffineExprDetail.h"
#include "mlir/IR/AffineExpr.h"
#include "mlir/IR/AffineExprVisitor.h" #include "mlir/IR/AffineExprVisitor.h"
#include "mlir/IR/AffineMap.h" #include "mlir/IR/AffineMap.h"
#include "mlir/IR/IntegerSet.h" #include "mlir/IR/IntegerSet.h"

View File

@ -930,8 +930,7 @@ private:
}; };
} // namespace } // namespace
SSANameState::SSANameState( SSANameState::SSANameState(Operation *op, const OpPrintingFlags &printerFlags)
Operation *op, const OpPrintingFlags &printerFlags)
: printerFlags(printerFlags) { : printerFlags(printerFlags) {
llvm::SaveAndRestore<unsigned> valueIDSaver(nextValueID); llvm::SaveAndRestore<unsigned> valueIDSaver(nextValueID);
llvm::SaveAndRestore<unsigned> argumentIDSaver(nextArgumentID); llvm::SaveAndRestore<unsigned> argumentIDSaver(nextArgumentID);

View File

@ -373,8 +373,7 @@ struct SourceMgrDiagnosticHandlerImpl {
// Otherwise, try to load the source file. // Otherwise, try to load the source file.
std::string ignored; std::string ignored;
unsigned id = unsigned id = mgr.AddIncludeFile(std::string(filename), SMLoc(), ignored);
mgr.AddIncludeFile(std::string(filename), SMLoc(), ignored);
filenameToBufId[filename] = id; filenameToBufId[filename] = id;
return id; return id;
} }

View File

@ -261,10 +261,8 @@ TypeRange mlir::function_interface_impl::insertTypesInto(
return storage; return storage;
} }
TypeRange TypeRange mlir::function_interface_impl::filterTypesOut(
mlir::function_interface_impl::filterTypesOut(TypeRange types, TypeRange types, const BitVector &indices, SmallVectorImpl<Type> &storage) {
const BitVector &indices,
SmallVectorImpl<Type> &storage) {
if (indices.none()) if (indices.none())
return types; return types;

View File

@ -292,8 +292,7 @@ void detail::OperandStorage::eraseOperands(unsigned start, unsigned length) {
operands[numOperands + i].~OpOperand(); operands[numOperands + i].~OpOperand();
} }
void detail::OperandStorage::eraseOperands( void detail::OperandStorage::eraseOperands(const BitVector &eraseIndices) {
const BitVector &eraseIndices) {
MutableArrayRef<OpOperand> operands = getOperands(); MutableArrayRef<OpOperand> operands = getOperands();
assert(eraseIndices.size() == operands.size()); assert(eraseIndices.size() == operands.size());

View File

@ -212,4 +212,3 @@ unsigned BlockOperand::getOperandNumber() {
unsigned OpOperand::getOperandNumber() { unsigned OpOperand::getOperandNumber() {
return this - &getOwner()->getOpOperands()[0]; return this - &getOwner()->getOpOperands()[0];
} }

View File

@ -51,9 +51,7 @@ public:
/// Get the location of the next token and store it into the argument. This /// Get the location of the next token and store it into the argument. This
/// always succeeds. /// always succeeds.
SMLoc getCurrentLocation() override { SMLoc getCurrentLocation() override { return parser.getToken().getLoc(); }
return parser.getToken().getLoc();
}
/// Re-encode the given source location as an MLIR location and return it. /// Re-encode the given source location as an MLIR location and return it.
Location getEncodedSourceLoc(SMLoc loc) override { Location getEncodedSourceLoc(SMLoc loc) override {

View File

@ -259,8 +259,7 @@ void AsmParserState::addDefinition(Block *block, SMLoc location) {
impl->blocks[it->second]->definition.loc = convertIdLocToRange(location); impl->blocks[it->second]->definition.loc = convertIdLocToRange(location);
} }
void AsmParserState::addDefinition(BlockArgument blockArg, void AsmParserState::addDefinition(BlockArgument blockArg, SMLoc location) {
SMLoc location) {
auto it = impl->blocksToIdx.find(blockArg.getOwner()); auto it = impl->blocksToIdx.find(blockArg.getOwner());
assert(it != impl->blocksToIdx.end() && assert(it != impl->blocksToIdx.end() &&
"expected owner block to have an entry"); "expected owner block to have an entry");

View File

@ -525,8 +525,7 @@ ParseResult TensorLiteralParser::parse(bool allowHex) {
/// Build a dense attribute instance with the parsed elements and the given /// Build a dense attribute instance with the parsed elements and the given
/// shaped type. /// shaped type.
DenseElementsAttr TensorLiteralParser::getAttr(SMLoc loc, DenseElementsAttr TensorLiteralParser::getAttr(SMLoc loc, ShapedType type) {
ShapedType type) {
Type eltType = type.getElementType(); Type eltType = type.getElementType();
// Check to see if we parse the literal from a hex string. // Check to see if we parse the literal from a hex string.
@ -676,8 +675,7 @@ TensorLiteralParser::getFloatAttrElements(SMLoc loc, FloatType eltTy,
} }
/// Build a Dense String attribute for the given type. /// Build a Dense String attribute for the given type.
DenseElementsAttr TensorLiteralParser::getStringAttr(SMLoc loc, DenseElementsAttr TensorLiteralParser::getStringAttr(SMLoc loc, ShapedType type,
ShapedType type,
Type eltTy) { Type eltTy) {
if (hexStorage.has_value()) { if (hexStorage.has_value()) {
auto stringValue = hexStorage.value().getStringValue(); auto stringValue = hexStorage.value().getStringValue();
@ -698,8 +696,7 @@ DenseElementsAttr TensorLiteralParser::getStringAttr(SMLoc loc,
} }
/// Build a Dense attribute with hex data for the given type. /// Build a Dense attribute with hex data for the given type.
DenseElementsAttr TensorLiteralParser::getHexAttr(SMLoc loc, DenseElementsAttr TensorLiteralParser::getHexAttr(SMLoc loc, ShapedType type) {
ShapedType type) {
Type elementType = type.getElementType(); Type elementType = type.getElementType();
if (!elementType.isIntOrIndexOrFloat() && !elementType.isa<ComplexType>()) { if (!elementType.isIntOrIndexOrFloat() && !elementType.isa<ComplexType>()) {
p.emitError(loc) p.emitError(loc)

View File

@ -62,7 +62,8 @@ public:
} }
private: private:
template <typename T> void addDataToHash(llvm::SHA1 &hasher, const T &data) { template <typename T>
void addDataToHash(llvm::SHA1 &hasher, const T &data) {
hasher.update( hasher.update(
ArrayRef<uint8_t>(reinterpret_cast<const uint8_t *>(&data), sizeof(T))); ArrayRef<uint8_t>(reinterpret_cast<const uint8_t *>(&data), sizeof(T)));
} }

View File

@ -8,9 +8,9 @@
#include <utility> #include <utility>
#include "mlir/Pass/PassRegistry.h"
#include "mlir/Pass/Pass.h" #include "mlir/Pass/Pass.h"
#include "mlir/Pass/PassManager.h" #include "mlir/Pass/PassManager.h"
#include "mlir/Pass/PassRegistry.h"
#include "llvm/ADT/DenseMap.h" #include "llvm/ADT/DenseMap.h"
#include "llvm/Support/Format.h" #include "llvm/Support/Format.h"
#include "llvm/Support/ManagedStatic.h" #include "llvm/Support/ManagedStatic.h"

View File

@ -341,10 +341,9 @@ static LogicalResult convertDataOp(acc::DataOp &op,
mapperAllocas))) mapperAllocas)))
return failure(); return failure();
if (failed(processOperands(builder, moduleTranslation, op, if (failed(processOperands(
op.createOperands(), totalNbOperand, builder, moduleTranslation, op, op.createOperands(), totalNbOperand,
kCreateFlag | kHoldFlag, flags, names, index, kCreateFlag | kHoldFlag, flags, names, index, mapperAllocas)))
mapperAllocas)))
return failure(); return failure();
// TODO create zero currenlty handled as create. Update when extension // TODO create zero currenlty handled as create. Update when extension
@ -355,10 +354,9 @@ static LogicalResult convertDataOp(acc::DataOp &op,
mapperAllocas))) mapperAllocas)))
return failure(); return failure();
if (failed(processOperands(builder, moduleTranslation, op, if (failed(processOperands(
op.presentOperands(), totalNbOperand, builder, moduleTranslation, op, op.presentOperands(), totalNbOperand,
kPresentFlag | kHoldFlag, flags, names, index, kPresentFlag | kHoldFlag, flags, names, index, mapperAllocas)))
mapperAllocas)))
return failure(); return failure();
llvm::GlobalVariable *maptypes = llvm::GlobalVariable *maptypes =

View File

@ -467,7 +467,8 @@ private:
/// Method to deserialize an operation in the SPIR-V dialect that is a mirror /// Method to deserialize an operation in the SPIR-V dialect that is a mirror
/// of an instruction in the SPIR-V spec. This is auto generated if hasOpcode /// of an instruction in the SPIR-V spec. This is auto generated if hasOpcode
/// == 1 and autogenSerialization == 1 in ODS. /// == 1 and autogenSerialization == 1 in ODS.
template <typename OpTy> LogicalResult processOp(ArrayRef<uint32_t> words) { template <typename OpTy>
LogicalResult processOp(ArrayRef<uint32_t> words) {
return emitError(unknownLoc, "unsupported deserialization for ") return emitError(unknownLoc, "unsupported deserialization for ")
<< OpTy::getOperationName() << " op"; << OpTy::getOperationName() << " op";
} }

View File

@ -297,7 +297,8 @@ private:
/// Serializes an operation in the SPIR-V dialect that is a mirror of an /// Serializes an operation in the SPIR-V dialect that is a mirror of an
/// instruction in the SPIR-V spec. This is auto generated if hasOpcode == 1 /// instruction in the SPIR-V spec. This is auto generated if hasOpcode == 1
/// and autogenSerialization == 1 in ODS. /// and autogenSerialization == 1 in ODS.
template <typename OpTy> LogicalResult processOp(OpTy op) { template <typename OpTy>
LogicalResult processOp(OpTy op) {
return op.emitError("unsupported op serialization"); return op.emitError("unsupported op serialization");
} }

View File

@ -199,8 +199,7 @@ CompoundStmt *CompoundStmt::create(Context &ctx, SMRange loc,
// LetStmt // LetStmt
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
LetStmt *LetStmt::create(Context &ctx, SMRange loc, LetStmt *LetStmt::create(Context &ctx, SMRange loc, VariableDecl *varDecl) {
VariableDecl *varDecl) {
return new (ctx.getAllocator().Allocate<LetStmt>()) LetStmt(loc, varDecl); return new (ctx.getAllocator().Allocate<LetStmt>()) LetStmt(loc, varDecl);
} }
@ -394,8 +393,7 @@ Optional<StringRef> OpConstraintDecl::getName() const {
// TypeConstraintDecl // TypeConstraintDecl
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
TypeConstraintDecl *TypeConstraintDecl::create(Context &ctx, TypeConstraintDecl *TypeConstraintDecl::create(Context &ctx, SMRange loc) {
SMRange loc) {
return new (ctx.getAllocator().Allocate<TypeConstraintDecl>()) return new (ctx.getAllocator().Allocate<TypeConstraintDecl>())
TypeConstraintDecl(loc); TypeConstraintDecl(loc);
} }
@ -414,8 +412,8 @@ TypeRangeConstraintDecl *TypeRangeConstraintDecl::create(Context &ctx,
// ValueConstraintDecl // ValueConstraintDecl
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
ValueConstraintDecl * ValueConstraintDecl *ValueConstraintDecl::create(Context &ctx, SMRange loc,
ValueConstraintDecl::create(Context &ctx, SMRange loc, Expr *typeExpr) { Expr *typeExpr) {
return new (ctx.getAllocator().Allocate<ValueConstraintDecl>()) return new (ctx.getAllocator().Allocate<ValueConstraintDecl>())
ValueConstraintDecl(loc, typeExpr); ValueConstraintDecl(loc, typeExpr);
} }
@ -424,9 +422,8 @@ ValueConstraintDecl::create(Context &ctx, SMRange loc, Expr *typeExpr) {
// ValueRangeConstraintDecl // ValueRangeConstraintDecl
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
ValueRangeConstraintDecl *ValueRangeConstraintDecl::create(Context &ctx, ValueRangeConstraintDecl *
SMRange loc, ValueRangeConstraintDecl::create(Context &ctx, SMRange loc, Expr *typeExpr) {
Expr *typeExpr) {
return new (ctx.getAllocator().Allocate<ValueRangeConstraintDecl>()) return new (ctx.getAllocator().Allocate<ValueRangeConstraintDecl>())
ValueRangeConstraintDecl(loc, typeExpr); ValueRangeConstraintDecl(loc, typeExpr);
} }
@ -498,8 +495,8 @@ OpNameDecl *OpNameDecl::create(Context &ctx, SMRange loc) {
// PatternDecl // PatternDecl
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
PatternDecl *PatternDecl::create(Context &ctx, SMRange loc, PatternDecl *PatternDecl::create(Context &ctx, SMRange loc, const Name *name,
const Name *name, Optional<uint16_t> benefit, Optional<uint16_t> benefit,
bool hasBoundedRecursion, bool hasBoundedRecursion,
const CompoundStmt *body) { const CompoundStmt *body) {
return new (ctx.getAllocator().Allocate<PatternDecl>()) return new (ctx.getAllocator().Allocate<PatternDecl>())
@ -554,8 +551,7 @@ VariableDecl *VariableDecl::create(Context &ctx, const Name &name, Type type,
// Module // Module
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
Module *Module::create(Context &ctx, SMLoc loc, Module *Module::create(Context &ctx, SMLoc loc, ArrayRef<Decl *> children) {
ArrayRef<Decl *> children) {
unsigned allocSize = Module::totalSizeToAlloc<Decl *>(children.size()); unsigned allocSize = Module::totalSizeToAlloc<Decl *>(children.size());
void *rawData = ctx.getAllocator().Allocate(allocSize, alignof(Module)); void *rawData = ctx.getAllocator().Allocate(allocSize, alignof(Module));

View File

@ -101,7 +101,8 @@ Lexer::Lexer(llvm::SourceMgr &mgr, ast::DiagnosticEngine &diagEngine,
} }
Lexer::~Lexer() { Lexer::~Lexer() {
if (addedHandlerToDiagEngine) diagEngine.setHandlerFn(nullptr); if (addedHandlerToDiagEngine)
diagEngine.setHandlerFn(nullptr);
} }
LogicalResult Lexer::pushInclude(StringRef filename, SMRange includeLoc) { LogicalResult Lexer::pushInclude(StringRef filename, SMRange includeLoc) {
@ -121,15 +122,14 @@ Token Lexer::emitError(SMRange loc, const Twine &msg) {
diagEngine.emitError(loc, msg); diagEngine.emitError(loc, msg);
return formToken(Token::error, loc.Start.getPointer()); return formToken(Token::error, loc.Start.getPointer());
} }
Token Lexer::emitErrorAndNote(SMRange loc, const Twine &msg, Token Lexer::emitErrorAndNote(SMRange loc, const Twine &msg, SMRange noteLoc,
SMRange noteLoc, const Twine &note) { const Twine &note) {
diagEngine.emitError(loc, msg)->attachNote(note, noteLoc); diagEngine.emitError(loc, msg)->attachNote(note, noteLoc);
return formToken(Token::error, loc.Start.getPointer()); return formToken(Token::error, loc.Start.getPointer());
} }
Token Lexer::emitError(const char *loc, const Twine &msg) { Token Lexer::emitError(const char *loc, const Twine &msg) {
return emitError(SMRange(SMLoc::getFromPointer(loc), return emitError(
SMLoc::getFromPointer(loc + 1)), SMRange(SMLoc::getFromPointer(loc), SMLoc::getFromPointer(loc + 1)), msg);
msg);
} }
int Lexer::getNextChar() { int Lexer::getNextChar() {
@ -140,7 +140,8 @@ int Lexer::getNextChar() {
case 0: { case 0: {
// A nul character in the stream is either the end of the current buffer // A nul character in the stream is either the end of the current buffer
// or a random nul in the file. Disambiguate that here. // or a random nul in the file. Disambiguate that here.
if (curPtr - 1 != curBuffer.end()) return 0; if (curPtr - 1 != curBuffer.end())
return 0;
// Otherwise, return end of file. // Otherwise, return end of file.
--curPtr; --curPtr;
@ -170,7 +171,8 @@ Token Lexer::lexToken() {
switch (curChar) { switch (curChar) {
default: default:
// Handle identifiers: [a-zA-Z_] // Handle identifiers: [a-zA-Z_]
if (isalpha(curChar) || curChar == '_') return lexIdentifier(tokStart); if (isalpha(curChar) || curChar == '_')
return lexIdentifier(tokStart);
// Unknown character, emit an error. // Unknown character, emit an error.
return emitError(tokStart, "unexpected character"); return emitError(tokStart, "unexpected character");
@ -293,7 +295,8 @@ void Lexer::lexComment() {
Token Lexer::lexDirective(const char *tokStart) { Token Lexer::lexDirective(const char *tokStart) {
// Match the rest with an identifier regex: [0-9a-zA-Z_]* // Match the rest with an identifier regex: [0-9a-zA-Z_]*
while (isalnum(*curPtr) || *curPtr == '_') ++curPtr; while (isalnum(*curPtr) || *curPtr == '_')
++curPtr;
StringRef str(tokStart, curPtr - tokStart); StringRef str(tokStart, curPtr - tokStart);
return Token(Token::directive, str); return Token(Token::directive, str);
@ -301,7 +304,8 @@ Token Lexer::lexDirective(const char *tokStart) {
Token Lexer::lexIdentifier(const char *tokStart) { Token Lexer::lexIdentifier(const char *tokStart) {
// Match the rest of the identifier regex: [0-9a-zA-Z_]* // Match the rest of the identifier regex: [0-9a-zA-Z_]*
while (isalnum(*curPtr) || *curPtr == '_') ++curPtr; while (isalnum(*curPtr) || *curPtr == '_')
++curPtr;
// Check to see if this identifier is a keyword. // Check to see if this identifier is a keyword.
StringRef str(tokStart, curPtr - tokStart); StringRef str(tokStart, curPtr - tokStart);
@ -334,7 +338,8 @@ Token Lexer::lexNumber(const char *tokStart) {
assert(isdigit(curPtr[-1])); assert(isdigit(curPtr[-1]));
// Handle the normal decimal case. // Handle the normal decimal case.
while (isdigit(*curPtr)) ++curPtr; while (isdigit(*curPtr))
++curPtr;
return formToken(Token::integer, tokStart); return formToken(Token::integer, tokStart);
} }

View File

@ -133,7 +133,8 @@ public:
/// Return if the token does not have the given kind. /// Return if the token does not have the given kind.
bool isNot(Kind k) const { return k != kind; } bool isNot(Kind k) const { return k != kind; }
template <typename... T> bool isNot(Kind k1, Kind k2, T... others) const { template <typename... T>
bool isNot(Kind k1, Kind k2, T... others) const {
return !isAny(k1, k2, others...); return !isAny(k1, k2, others...);
} }
@ -141,17 +142,13 @@ public:
bool is(Kind k) const { return kind == k; } bool is(Kind k) const { return kind == k; }
/// Return a location for the start of this token. /// Return a location for the start of this token.
SMLoc getStartLoc() const { SMLoc getStartLoc() const { return SMLoc::getFromPointer(spelling.data()); }
return SMLoc::getFromPointer(spelling.data());
}
/// Return a location at the end of this token. /// Return a location at the end of this token.
SMLoc getEndLoc() const { SMLoc getEndLoc() const {
return SMLoc::getFromPointer(spelling.data() + spelling.size()); return SMLoc::getFromPointer(spelling.data() + spelling.size());
} }
/// Return a location for the range of this token. /// Return a location for the range of this token.
SMRange getLoc() const { SMRange getLoc() const { return SMRange(getStartLoc(), getEndLoc()); }
return SMRange(getStartLoc(), getEndLoc());
}
private: private:
/// Discriminator that indicates the kind of token this is. /// Discriminator that indicates the kind of token this is.
@ -193,8 +190,8 @@ public:
/// Emit an error to the lexer with the given location and message. /// Emit an error to the lexer with the given location and message.
Token emitError(SMRange loc, const Twine &msg); Token emitError(SMRange loc, const Twine &msg);
Token emitError(const char *loc, const Twine &msg); Token emitError(const char *loc, const Twine &msg);
Token emitErrorAndNote(SMRange loc, const Twine &msg, Token emitErrorAndNote(SMRange loc, const Twine &msg, SMRange noteLoc,
SMRange noteLoc, const Twine &note); const Twine &note);
private: private:
Token formToken(Token::Kind kind, const char *tokStart) { Token formToken(Token::Kind kind, const char *tokStart) {

View File

@ -314,8 +314,7 @@ private:
} // namespace } // namespace
std::unique_ptr<Pass> std::unique_ptr<Pass> mlir::createPrintOpGraphPass(raw_ostream &os) {
mlir::createPrintOpGraphPass(raw_ostream &os) {
return std::make_unique<PrintOpPass>(os); return std::make_unique<PrintOpPass>(os);
} }

View File

@ -2147,7 +2147,8 @@ void OperationFormat::genPrinter(Operator &op, OpClass &opClass) {
/// Function to find an element within the given range that has the same name as /// Function to find an element within the given range that has the same name as
/// 'name'. /// 'name'.
template <typename RangeT> static auto findArg(RangeT &&range, StringRef name) { template <typename RangeT>
static auto findArg(RangeT &&range, StringRef name) {
auto it = llvm::find_if(range, [=](auto &arg) { return arg.name == name; }); auto it = llvm::find_if(range, [=](auto &arg) { return arg.name == name; });
return it != range.end() ? &*it : nullptr; return it != range.end() ? &*it : nullptr;
} }

View File

@ -70,9 +70,7 @@ TEST(DebugActionTest, DebugCounterHandler) {
// Handler that uses the number of action executions as the decider. // Handler that uses the number of action executions as the decider.
struct DebugCounterHandler : public SimpleAction::Handler { struct DebugCounterHandler : public SimpleAction::Handler {
FailureOr<bool> shouldExecute() final { FailureOr<bool> shouldExecute() final { return numExecutions++ < 3; }
return numExecutions++ < 3;
}
unsigned numExecutions = 0; unsigned numExecutions = 0;
}; };
manager.registerActionHandler<DebugCounterHandler>(); manager.registerActionHandler<DebugCounterHandler>();

View File

@ -77,8 +77,8 @@ protected:
verifyOp(std::move(op), {i32Ty}, {*cstI32, *cstI32}, noAttrs); verifyOp(std::move(op), {i32Ty}, {*cstI32, *cstI32}, noAttrs);
// Test collective params build method. // Test collective params build method.
op = op = builder.create<OpTy>(loc, TypeRange{i32Ty},
builder.create<OpTy>(loc, TypeRange{i32Ty}, ValueRange{*cstI32, *cstI32}); ValueRange{*cstI32, *cstI32});
verifyOp(std::move(op), {i32Ty}, {*cstI32, *cstI32}, noAttrs); verifyOp(std::move(op), {i32Ty}, {*cstI32, *cstI32}, noAttrs);
// Test build method with no result types, default value of attributes. // Test build method with no result types, default value of attributes.