1 //===- MLIRContext.cpp - MLIR Type Classes --------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "mlir/IR/MLIRContext.h"
10 #include "AffineExprDetail.h"
11 #include "AffineMapDetail.h"
12 #include "AttributeDetail.h"
13 #include "IntegerSetDetail.h"
14 #include "LocationDetail.h"
15 #include "TypeDetail.h"
16 #include "mlir/IR/AffineExpr.h"
17 #include "mlir/IR/AffineMap.h"
18 #include "mlir/IR/Attributes.h"
19 #include "mlir/IR/BuiltinDialect.h"
20 #include "mlir/IR/Diagnostics.h"
21 #include "mlir/IR/Dialect.h"
22 #include "mlir/IR/Identifier.h"
23 #include "mlir/IR/IntegerSet.h"
24 #include "mlir/IR/Location.h"
25 #include "mlir/IR/OpImplementation.h"
26 #include "mlir/IR/Types.h"
27 #include "mlir/Support/ThreadLocalCache.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/DenseSet.h"
30 #include "llvm/ADT/SetVector.h"
31 #include "llvm/ADT/StringSet.h"
32 #include "llvm/ADT/Twine.h"
33 #include "llvm/Support/Allocator.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/RWMutex.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include <memory>
39 
40 #define DEBUG_TYPE "mlircontext"
41 
42 using namespace mlir;
43 using namespace mlir::detail;
44 
45 using llvm::hash_combine;
46 using llvm::hash_combine_range;
47 
48 //===----------------------------------------------------------------------===//
49 // MLIRContext CommandLine Options
50 //===----------------------------------------------------------------------===//
51 
52 namespace {
53 /// This struct contains command line options that can be used to initialize
54 /// various bits of an MLIRContext. This uses a struct wrapper to avoid the need
55 /// for global command line options.
56 struct MLIRContextOptions {
57   llvm::cl::opt<bool> disableThreading{
58       "mlir-disable-threading",
59       llvm::cl::desc("Disabling multi-threading within MLIR")};
60 
61   llvm::cl::opt<bool> printOpOnDiagnostic{
62       "mlir-print-op-on-diagnostic",
63       llvm::cl::desc("When a diagnostic is emitted on an operation, also print "
64                      "the operation as an attached note"),
65       llvm::cl::init(true)};
66 
67   llvm::cl::opt<bool> printStackTraceOnDiagnostic{
68       "mlir-print-stacktrace-on-diagnostic",
69       llvm::cl::desc("When a diagnostic is emitted, also print the stack trace "
70                      "as an attached note")};
71 };
72 } // end anonymous namespace
73 
74 static llvm::ManagedStatic<MLIRContextOptions> clOptions;
75 
76 /// Register a set of useful command-line options that can be used to configure
77 /// various flags within the MLIRContext. These flags are used when constructing
78 /// an MLIR context for initialization.
79 void mlir::registerMLIRContextCLOptions() {
80   // Make sure that the options struct has been initialized.
81   *clOptions;
82 }
83 
84 //===----------------------------------------------------------------------===//
85 // Locking Utilities
86 //===----------------------------------------------------------------------===//
87 
88 namespace {
89 /// Utility reader lock that takes a runtime flag that specifies if we really
90 /// need to lock.
91 struct ScopedReaderLock {
92   ScopedReaderLock(llvm::sys::SmartRWMutex<true> &mutexParam, bool shouldLock)
93       : mutex(shouldLock ? &mutexParam : nullptr) {
94     if (mutex)
95       mutex->lock_shared();
96   }
97   ~ScopedReaderLock() {
98     if (mutex)
99       mutex->unlock_shared();
100   }
101   llvm::sys::SmartRWMutex<true> *mutex;
102 };
103 /// Utility writer lock that takes a runtime flag that specifies if we really
104 /// need to lock.
105 struct ScopedWriterLock {
106   ScopedWriterLock(llvm::sys::SmartRWMutex<true> &mutexParam, bool shouldLock)
107       : mutex(shouldLock ? &mutexParam : nullptr) {
108     if (mutex)
109       mutex->lock();
110   }
111   ~ScopedWriterLock() {
112     if (mutex)
113       mutex->unlock();
114   }
115   llvm::sys::SmartRWMutex<true> *mutex;
116 };
117 } // end anonymous namespace.
118 
119 //===----------------------------------------------------------------------===//
120 // AffineMap and IntegerSet hashing
121 //===----------------------------------------------------------------------===//
122 
123 /// A utility function to safely get or create a uniqued instance within the
124 /// given set container.
125 template <typename ValueT, typename DenseInfoT, typename KeyT,
126           typename ConstructorFn>
127 static ValueT safeGetOrCreate(DenseSet<ValueT, DenseInfoT> &container,
128                               KeyT &&key, llvm::sys::SmartRWMutex<true> &mutex,
129                               bool threadingIsEnabled,
130                               ConstructorFn &&constructorFn) {
131   // Check for an existing instance in read-only mode.
132   if (threadingIsEnabled) {
133     llvm::sys::SmartScopedReader<true> instanceLock(mutex);
134     auto it = container.find_as(key);
135     if (it != container.end())
136       return *it;
137   }
138 
139   // Acquire a writer-lock so that we can safely create the new instance.
140   ScopedWriterLock instanceLock(mutex, threadingIsEnabled);
141 
142   // Check for an existing instance again here, because another writer thread
143   // may have already created one. Otherwise, construct a new instance.
144   auto existing = container.insert_as(ValueT(), key);
145   if (existing.second)
146     return *existing.first = constructorFn();
147   return *existing.first;
148 }
149 
150 namespace {
151 struct AffineMapKeyInfo : DenseMapInfo<AffineMap> {
152   // Affine maps are uniqued based on their dim/symbol counts and affine
153   // expressions.
154   using KeyTy = std::tuple<unsigned, unsigned, ArrayRef<AffineExpr>>;
155   using DenseMapInfo<AffineMap>::isEqual;
156 
157   static unsigned getHashValue(const AffineMap &key) {
158     return getHashValue(
159         KeyTy(key.getNumDims(), key.getNumSymbols(), key.getResults()));
160   }
161 
162   static unsigned getHashValue(KeyTy key) {
163     return hash_combine(
164         std::get<0>(key), std::get<1>(key),
165         hash_combine_range(std::get<2>(key).begin(), std::get<2>(key).end()));
166   }
167 
168   static bool isEqual(const KeyTy &lhs, AffineMap rhs) {
169     if (rhs == getEmptyKey() || rhs == getTombstoneKey())
170       return false;
171     return lhs == std::make_tuple(rhs.getNumDims(), rhs.getNumSymbols(),
172                                   rhs.getResults());
173   }
174 };
175 
176 struct IntegerSetKeyInfo : DenseMapInfo<IntegerSet> {
177   // Integer sets are uniqued based on their dim/symbol counts, affine
178   // expressions appearing in the LHS of constraints, and eqFlags.
179   using KeyTy =
180       std::tuple<unsigned, unsigned, ArrayRef<AffineExpr>, ArrayRef<bool>>;
181   using DenseMapInfo<IntegerSet>::isEqual;
182 
183   static unsigned getHashValue(const IntegerSet &key) {
184     return getHashValue(KeyTy(key.getNumDims(), key.getNumSymbols(),
185                               key.getConstraints(), key.getEqFlags()));
186   }
187 
188   static unsigned getHashValue(KeyTy key) {
189     return hash_combine(
190         std::get<0>(key), std::get<1>(key),
191         hash_combine_range(std::get<2>(key).begin(), std::get<2>(key).end()),
192         hash_combine_range(std::get<3>(key).begin(), std::get<3>(key).end()));
193   }
194 
195   static bool isEqual(const KeyTy &lhs, IntegerSet rhs) {
196     if (rhs == getEmptyKey() || rhs == getTombstoneKey())
197       return false;
198     return lhs == std::make_tuple(rhs.getNumDims(), rhs.getNumSymbols(),
199                                   rhs.getConstraints(), rhs.getEqFlags());
200   }
201 };
202 } // end anonymous namespace.
203 
204 //===----------------------------------------------------------------------===//
205 // MLIRContextImpl
206 //===----------------------------------------------------------------------===//
207 
208 namespace mlir {
209 /// This is the implementation of the MLIRContext class, using the pImpl idiom.
210 /// This class is completely private to this file, so everything is public.
211 class MLIRContextImpl {
212 public:
213   //===--------------------------------------------------------------------===//
214   // Identifier uniquing
215   //===--------------------------------------------------------------------===//
216 
217   // Identifier allocator and mutex for thread safety.
218   llvm::BumpPtrAllocator identifierAllocator;
219   llvm::sys::SmartRWMutex<true> identifierMutex;
220 
221   //===--------------------------------------------------------------------===//
222   // Diagnostics
223   //===--------------------------------------------------------------------===//
224   DiagnosticEngine diagEngine;
225 
226   //===--------------------------------------------------------------------===//
227   // Options
228   //===--------------------------------------------------------------------===//
229 
230   /// In most cases, creating operation in unregistered dialect is not desired
231   /// and indicate a misconfiguration of the compiler. This option enables to
232   /// detect such use cases
233   bool allowUnregisteredDialects = false;
234 
235   /// Enable support for multi-threading within MLIR.
236   bool threadingIsEnabled = true;
237 
238   /// Track if we are currently executing in a threaded execution environment
239   /// (like the pass-manager): this is only a debugging feature to help reducing
240   /// the chances of data races one some context APIs.
241 #ifndef NDEBUG
242   std::atomic<int> multiThreadedExecutionContext{0};
243 #endif
244 
245   /// If the operation should be attached to diagnostics printed via the
246   /// Operation::emit methods.
247   bool printOpOnDiagnostic = true;
248 
249   /// If the current stack trace should be attached when emitting diagnostics.
250   bool printStackTraceOnDiagnostic = false;
251 
252   //===--------------------------------------------------------------------===//
253   // Other
254   //===--------------------------------------------------------------------===//
255 
256   /// This is a list of dialects that are created referring to this context.
257   /// The MLIRContext owns the objects.
258   DenseMap<StringRef, std::unique_ptr<Dialect>> loadedDialects;
259   DialectRegistry dialectsRegistry;
260 
261   /// This is a mapping from operation name to AbstractOperation for registered
262   /// operations.
263   llvm::StringMap<AbstractOperation> registeredOperations;
264 
265   /// Identifiers are uniqued by string value and use the internal string set
266   /// for storage.
267   llvm::StringMap<PointerUnion<Dialect *, MLIRContext *>,
268                   llvm::BumpPtrAllocator &>
269       identifiers;
270   /// A thread local cache of identifiers to reduce lock contention.
271   ThreadLocalCache<llvm::StringMap<
272       llvm::StringMapEntry<PointerUnion<Dialect *, MLIRContext *>> *>>
273       localIdentifierCache;
274 
275   /// An allocator used for AbstractAttribute and AbstractType objects.
276   llvm::BumpPtrAllocator abstractDialectSymbolAllocator;
277 
278   //===--------------------------------------------------------------------===//
279   // Affine uniquing
280   //===--------------------------------------------------------------------===//
281 
282   // Affine allocator and mutex for thread safety.
283   llvm::BumpPtrAllocator affineAllocator;
284   llvm::sys::SmartRWMutex<true> affineMutex;
285 
286   // Affine map uniquing.
287   using AffineMapSet = DenseSet<AffineMap, AffineMapKeyInfo>;
288   AffineMapSet affineMaps;
289 
290   // Integer set uniquing.
291   using IntegerSets = DenseSet<IntegerSet, IntegerSetKeyInfo>;
292   IntegerSets integerSets;
293 
294   // Affine expression uniquing.
295   StorageUniquer affineUniquer;
296 
297   //===--------------------------------------------------------------------===//
298   // Type uniquing
299   //===--------------------------------------------------------------------===//
300 
301   DenseMap<TypeID, const AbstractType *> registeredTypes;
302   StorageUniquer typeUniquer;
303 
304   /// Cached Type Instances.
305   BFloat16Type bf16Ty;
306   Float16Type f16Ty;
307   Float32Type f32Ty;
308   Float64Type f64Ty;
309   Float80Type f80Ty;
310   Float128Type f128Ty;
311   IndexType indexTy;
312   IntegerType int1Ty, int8Ty, int16Ty, int32Ty, int64Ty, int128Ty;
313   NoneType noneType;
314 
315   //===--------------------------------------------------------------------===//
316   // Attribute uniquing
317   //===--------------------------------------------------------------------===//
318 
319   DenseMap<TypeID, const AbstractAttribute *> registeredAttributes;
320   StorageUniquer attributeUniquer;
321 
322   /// Cached Attribute Instances.
323   BoolAttr falseAttr, trueAttr;
324   UnitAttr unitAttr;
325   UnknownLoc unknownLocAttr;
326   DictionaryAttr emptyDictionaryAttr;
327 
328 public:
329   MLIRContextImpl() : identifiers(identifierAllocator) {}
330   ~MLIRContextImpl() {
331     for (auto typeMapping : registeredTypes)
332       typeMapping.second->~AbstractType();
333     for (auto attrMapping : registeredAttributes)
334       attrMapping.second->~AbstractAttribute();
335   }
336 };
337 } // end namespace mlir
338 
339 MLIRContext::MLIRContext() : MLIRContext(DialectRegistry()) {}
340 
341 MLIRContext::MLIRContext(const DialectRegistry &registry)
342     : impl(new MLIRContextImpl) {
343   // Initialize values based on the command line flags if they were provided.
344   if (clOptions.isConstructed()) {
345     disableMultithreading(clOptions->disableThreading);
346     printOpOnDiagnostic(clOptions->printOpOnDiagnostic);
347     printStackTraceOnDiagnostic(clOptions->printStackTraceOnDiagnostic);
348   }
349 
350   // Ensure the builtin dialect is always pre-loaded.
351   getOrLoadDialect<BuiltinDialect>();
352 
353   // Pre-populate the registry.
354   registry.appendTo(impl->dialectsRegistry);
355 
356   // Initialize several common attributes and types to avoid the need to lock
357   // the context when accessing them.
358 
359   //// Types.
360   /// Floating-point Types.
361   impl->bf16Ty = TypeUniquer::get<BFloat16Type>(this);
362   impl->f16Ty = TypeUniquer::get<Float16Type>(this);
363   impl->f32Ty = TypeUniquer::get<Float32Type>(this);
364   impl->f64Ty = TypeUniquer::get<Float64Type>(this);
365   impl->f80Ty = TypeUniquer::get<Float80Type>(this);
366   impl->f128Ty = TypeUniquer::get<Float128Type>(this);
367   /// Index Type.
368   impl->indexTy = TypeUniquer::get<IndexType>(this);
369   /// Integer Types.
370   impl->int1Ty = TypeUniquer::get<IntegerType>(this, 1, IntegerType::Signless);
371   impl->int8Ty = TypeUniquer::get<IntegerType>(this, 8, IntegerType::Signless);
372   impl->int16Ty =
373       TypeUniquer::get<IntegerType>(this, 16, IntegerType::Signless);
374   impl->int32Ty =
375       TypeUniquer::get<IntegerType>(this, 32, IntegerType::Signless);
376   impl->int64Ty =
377       TypeUniquer::get<IntegerType>(this, 64, IntegerType::Signless);
378   impl->int128Ty =
379       TypeUniquer::get<IntegerType>(this, 128, IntegerType::Signless);
380   /// None Type.
381   impl->noneType = TypeUniquer::get<NoneType>(this);
382 
383   //// Attributes.
384   //// Note: These must be registered after the types as they may generate one
385   //// of the above types internally.
386   /// Bool Attributes.
387   impl->falseAttr = AttributeUniquer::get<IntegerAttr>(
388                         this, impl->int1Ty, APInt(/*numBits=*/1, false))
389                         .cast<BoolAttr>();
390   impl->trueAttr = AttributeUniquer::get<IntegerAttr>(
391                        this, impl->int1Ty, APInt(/*numBits=*/1, true))
392                        .cast<BoolAttr>();
393   /// Unit Attribute.
394   impl->unitAttr = AttributeUniquer::get<UnitAttr>(this);
395   /// Unknown Location Attribute.
396   impl->unknownLocAttr = AttributeUniquer::get<UnknownLoc>(this);
397   /// The empty dictionary attribute.
398   impl->emptyDictionaryAttr =
399       AttributeUniquer::get<DictionaryAttr>(this, ArrayRef<NamedAttribute>());
400 
401   // Register the affine storage objects with the uniquer.
402   impl->affineUniquer
403       .registerParametricStorageType<AffineBinaryOpExprStorage>();
404   impl->affineUniquer
405       .registerParametricStorageType<AffineConstantExprStorage>();
406   impl->affineUniquer.registerParametricStorageType<AffineDimExprStorage>();
407 }
408 
409 MLIRContext::~MLIRContext() {}
410 
411 /// Copy the specified array of elements into memory managed by the provided
412 /// bump pointer allocator.  This assumes the elements are all PODs.
413 template <typename T>
414 static ArrayRef<T> copyArrayRefInto(llvm::BumpPtrAllocator &allocator,
415                                     ArrayRef<T> elements) {
416   auto result = allocator.Allocate<T>(elements.size());
417   std::uninitialized_copy(elements.begin(), elements.end(), result);
418   return ArrayRef<T>(result, elements.size());
419 }
420 
421 //===----------------------------------------------------------------------===//
422 // Diagnostic Handlers
423 //===----------------------------------------------------------------------===//
424 
425 /// Returns the diagnostic engine for this context.
426 DiagnosticEngine &MLIRContext::getDiagEngine() { return getImpl().diagEngine; }
427 
428 //===----------------------------------------------------------------------===//
429 // Dialect and Operation Registration
430 //===----------------------------------------------------------------------===//
431 
432 void MLIRContext::appendDialectRegistry(const DialectRegistry &registry) {
433   registry.appendTo(impl->dialectsRegistry);
434 
435   // For the already loaded dialects, register the interfaces immediately.
436   for (const auto &kvp : impl->loadedDialects)
437     registry.registerDelayedInterfaces(kvp.second.get());
438 }
439 
440 const DialectRegistry &MLIRContext::getDialectRegistry() {
441   return impl->dialectsRegistry;
442 }
443 
444 /// Return information about all registered IR dialects.
445 std::vector<Dialect *> MLIRContext::getLoadedDialects() {
446   std::vector<Dialect *> result;
447   result.reserve(impl->loadedDialects.size());
448   for (auto &dialect : impl->loadedDialects)
449     result.push_back(dialect.second.get());
450   llvm::array_pod_sort(result.begin(), result.end(),
451                        [](Dialect *const *lhs, Dialect *const *rhs) -> int {
452                          return (*lhs)->getNamespace() < (*rhs)->getNamespace();
453                        });
454   return result;
455 }
456 std::vector<StringRef> MLIRContext::getAvailableDialects() {
457   std::vector<StringRef> result;
458   for (auto dialect : impl->dialectsRegistry.getDialectNames())
459     result.push_back(dialect);
460   return result;
461 }
462 
463 /// Get a registered IR dialect with the given namespace. If none is found,
464 /// then return nullptr.
465 Dialect *MLIRContext::getLoadedDialect(StringRef name) {
466   // Dialects are sorted by name, so we can use binary search for lookup.
467   auto it = impl->loadedDialects.find(name);
468   return (it != impl->loadedDialects.end()) ? it->second.get() : nullptr;
469 }
470 
471 Dialect *MLIRContext::getOrLoadDialect(StringRef name) {
472   Dialect *dialect = getLoadedDialect(name);
473   if (dialect)
474     return dialect;
475   DialectAllocatorFunctionRef allocator =
476       impl->dialectsRegistry.getDialectAllocator(name);
477   return allocator ? allocator(this) : nullptr;
478 }
479 
480 /// Get a dialect for the provided namespace and TypeID: abort the program if a
481 /// dialect exist for this namespace with different TypeID. Returns a pointer to
482 /// the dialect owned by the context.
483 Dialect *
484 MLIRContext::getOrLoadDialect(StringRef dialectNamespace, TypeID dialectID,
485                               function_ref<std::unique_ptr<Dialect>()> ctor) {
486   auto &impl = getImpl();
487   // Get the correct insertion position sorted by namespace.
488   std::unique_ptr<Dialect> &dialect = impl.loadedDialects[dialectNamespace];
489 
490   if (!dialect) {
491     LLVM_DEBUG(llvm::dbgs()
492                << "Load new dialect in Context " << dialectNamespace << "\n");
493 #ifndef NDEBUG
494     if (impl.multiThreadedExecutionContext != 0)
495       llvm::report_fatal_error(
496           "Loading a dialect (" + dialectNamespace +
497           ") while in a multi-threaded execution context (maybe "
498           "the PassManager): this can indicate a "
499           "missing `dependentDialects` in a pass for example.");
500 #endif
501     dialect = ctor();
502     assert(dialect && "dialect ctor failed");
503 
504     // Refresh all the identifiers dialect field, this catches cases where a
505     // dialect may be loaded after identifier prefixed with this dialect name
506     // were already created.
507     for (auto &identifierEntry : impl.identifiers)
508       if (!identifierEntry.second &&
509           identifierEntry.first().startswith(dialectNamespace))
510         identifierEntry.second = dialect.get();
511 
512     // Actually register the interfaces with delayed registration.
513     impl.dialectsRegistry.registerDelayedInterfaces(dialect.get());
514     return dialect.get();
515   }
516 
517   // Abort if dialect with namespace has already been registered.
518   if (dialect->getTypeID() != dialectID)
519     llvm::report_fatal_error("a dialect with namespace '" + dialectNamespace +
520                              "' has already been registered");
521 
522   return dialect.get();
523 }
524 
525 void MLIRContext::loadAllAvailableDialects() {
526   for (StringRef name : getAvailableDialects())
527     getOrLoadDialect(name);
528 }
529 
530 llvm::hash_code MLIRContext::getRegistryHash() {
531   llvm::hash_code hash(0);
532   // Factor in number of loaded dialects, attributes, operations, types.
533   hash = llvm::hash_combine(hash, impl->loadedDialects.size());
534   hash = llvm::hash_combine(hash, impl->registeredAttributes.size());
535   hash = llvm::hash_combine(hash, impl->registeredOperations.size());
536   hash = llvm::hash_combine(hash, impl->registeredTypes.size());
537   return hash;
538 }
539 
540 bool MLIRContext::allowsUnregisteredDialects() {
541   return impl->allowUnregisteredDialects;
542 }
543 
544 void MLIRContext::allowUnregisteredDialects(bool allowing) {
545   impl->allowUnregisteredDialects = allowing;
546 }
547 
548 /// Return true if multi-threading is disabled by the context.
549 bool MLIRContext::isMultithreadingEnabled() {
550   return impl->threadingIsEnabled && llvm::llvm_is_multithreaded();
551 }
552 
553 /// Set the flag specifying if multi-threading is disabled by the context.
554 void MLIRContext::disableMultithreading(bool disable) {
555   impl->threadingIsEnabled = !disable;
556 
557   // Update the threading mode for each of the uniquers.
558   impl->affineUniquer.disableMultithreading(disable);
559   impl->attributeUniquer.disableMultithreading(disable);
560   impl->typeUniquer.disableMultithreading(disable);
561 }
562 
563 void MLIRContext::enterMultiThreadedExecution() {
564 #ifndef NDEBUG
565   ++impl->multiThreadedExecutionContext;
566 #endif
567 }
568 void MLIRContext::exitMultiThreadedExecution() {
569 #ifndef NDEBUG
570   --impl->multiThreadedExecutionContext;
571 #endif
572 }
573 
574 /// Return true if we should attach the operation to diagnostics emitted via
575 /// Operation::emit.
576 bool MLIRContext::shouldPrintOpOnDiagnostic() {
577   return impl->printOpOnDiagnostic;
578 }
579 
580 /// Set the flag specifying if we should attach the operation to diagnostics
581 /// emitted via Operation::emit.
582 void MLIRContext::printOpOnDiagnostic(bool enable) {
583   impl->printOpOnDiagnostic = enable;
584 }
585 
586 /// Return true if we should attach the current stacktrace to diagnostics when
587 /// emitted.
588 bool MLIRContext::shouldPrintStackTraceOnDiagnostic() {
589   return impl->printStackTraceOnDiagnostic;
590 }
591 
592 /// Set the flag specifying if we should attach the current stacktrace when
593 /// emitting diagnostics.
594 void MLIRContext::printStackTraceOnDiagnostic(bool enable) {
595   impl->printStackTraceOnDiagnostic = enable;
596 }
597 
598 /// Return information about all registered operations.  This isn't very
599 /// efficient, typically you should ask the operations about their properties
600 /// directly.
601 std::vector<AbstractOperation *> MLIRContext::getRegisteredOperations() {
602   // We just have the operations in a non-deterministic hash table order. Dump
603   // into a temporary array, then sort it by operation name to get a stable
604   // ordering.
605   llvm::StringMap<AbstractOperation> &registeredOps =
606       impl->registeredOperations;
607 
608   std::vector<AbstractOperation *> result;
609   result.reserve(registeredOps.size());
610   for (auto &elt : registeredOps)
611     result.push_back(&elt.second);
612   llvm::array_pod_sort(
613       result.begin(), result.end(),
614       [](AbstractOperation *const *lhs, AbstractOperation *const *rhs) {
615         return (*lhs)->name.compare((*rhs)->name);
616       });
617 
618   return result;
619 }
620 
621 bool MLIRContext::isOperationRegistered(StringRef name) {
622   return impl->registeredOperations.count(name);
623 }
624 
625 void Dialect::addType(TypeID typeID, AbstractType &&typeInfo) {
626   auto &impl = context->getImpl();
627   assert(impl.multiThreadedExecutionContext == 0 &&
628          "Registering a new type kind while in a multi-threaded execution "
629          "context");
630   auto *newInfo =
631       new (impl.abstractDialectSymbolAllocator.Allocate<AbstractType>())
632           AbstractType(std::move(typeInfo));
633   if (!impl.registeredTypes.insert({typeID, newInfo}).second)
634     llvm::report_fatal_error("Dialect Type already registered.");
635 }
636 
637 void Dialect::addAttribute(TypeID typeID, AbstractAttribute &&attrInfo) {
638   auto &impl = context->getImpl();
639   assert(impl.multiThreadedExecutionContext == 0 &&
640          "Registering a new attribute kind while in a multi-threaded execution "
641          "context");
642   auto *newInfo =
643       new (impl.abstractDialectSymbolAllocator.Allocate<AbstractAttribute>())
644           AbstractAttribute(std::move(attrInfo));
645   if (!impl.registeredAttributes.insert({typeID, newInfo}).second)
646     llvm::report_fatal_error("Dialect Attribute already registered.");
647 }
648 
649 //===----------------------------------------------------------------------===//
650 // AbstractAttribute
651 //===----------------------------------------------------------------------===//
652 
653 /// Get the dialect that registered the attribute with the provided typeid.
654 const AbstractAttribute &AbstractAttribute::lookup(TypeID typeID,
655                                                    MLIRContext *context) {
656   auto &impl = context->getImpl();
657   auto it = impl.registeredAttributes.find(typeID);
658   if (it == impl.registeredAttributes.end())
659     llvm::report_fatal_error("Trying to create an Attribute that was not "
660                              "registered in this MLIRContext.");
661   return *it->second;
662 }
663 
664 //===----------------------------------------------------------------------===//
665 // AbstractOperation
666 //===----------------------------------------------------------------------===//
667 
668 ParseResult AbstractOperation::parseAssembly(OpAsmParser &parser,
669                                              OperationState &result) const {
670   return parseAssemblyFn(parser, result);
671 }
672 
673 /// Look up the specified operation in the operation set and return a pointer
674 /// to it if present. Otherwise, return a null pointer.
675 const AbstractOperation *AbstractOperation::lookup(StringRef opName,
676                                                    MLIRContext *context) {
677   auto &impl = context->getImpl();
678   auto it = impl.registeredOperations.find(opName);
679   if (it != impl.registeredOperations.end())
680     return &it->second;
681   return nullptr;
682 }
683 
684 void AbstractOperation::insert(
685     StringRef name, Dialect &dialect, TypeID typeID,
686     ParseAssemblyFn parseAssembly, PrintAssemblyFn printAssembly,
687     VerifyInvariantsFn verifyInvariants, FoldHookFn foldHook,
688     GetCanonicalizationPatternsFn getCanonicalizationPatterns,
689     detail::InterfaceMap &&interfaceMap, HasTraitFn hasTrait) {
690   AbstractOperation opInfo(
691       name, dialect, typeID, parseAssembly, printAssembly, verifyInvariants,
692       foldHook, getCanonicalizationPatterns, std::move(interfaceMap), hasTrait);
693 
694   auto &impl = dialect.getContext()->getImpl();
695   assert(impl.multiThreadedExecutionContext == 0 &&
696          "Registering a new operation kind while in a multi-threaded execution "
697          "context");
698   if (!impl.registeredOperations.insert({name, std::move(opInfo)}).second) {
699     llvm::errs() << "error: operation named '" << name
700                  << "' is already registered.\n";
701     abort();
702   }
703 }
704 
705 AbstractOperation::AbstractOperation(
706     StringRef name, Dialect &dialect, TypeID typeID,
707     ParseAssemblyFn parseAssembly, PrintAssemblyFn printAssembly,
708     VerifyInvariantsFn verifyInvariants, FoldHookFn foldHook,
709     GetCanonicalizationPatternsFn getCanonicalizationPatterns,
710     detail::InterfaceMap &&interfaceMap, HasTraitFn hasTrait)
711     : name(Identifier::get(name, dialect.getContext())), dialect(dialect),
712       typeID(typeID), interfaceMap(std::move(interfaceMap)),
713       foldHookFn(foldHook),
714       getCanonicalizationPatternsFn(getCanonicalizationPatterns),
715       hasTraitFn(hasTrait), parseAssemblyFn(parseAssembly),
716       printAssemblyFn(printAssembly), verifyInvariantsFn(verifyInvariants) {}
717 
718 //===----------------------------------------------------------------------===//
719 // AbstractType
720 //===----------------------------------------------------------------------===//
721 
722 const AbstractType &AbstractType::lookup(TypeID typeID, MLIRContext *context) {
723   auto &impl = context->getImpl();
724   auto it = impl.registeredTypes.find(typeID);
725   if (it == impl.registeredTypes.end())
726     llvm::report_fatal_error(
727         "Trying to create a Type that was not registered in this MLIRContext.");
728   return *it->second;
729 }
730 
731 //===----------------------------------------------------------------------===//
732 // Identifier uniquing
733 //===----------------------------------------------------------------------===//
734 
735 /// Return an identifier for the specified string.
736 Identifier Identifier::get(StringRef str, MLIRContext *context) {
737   // Check invariants after seeing if we already have something in the
738   // identifier table - if we already had it in the table, then it already
739   // passed invariant checks.
740   assert(!str.empty() && "Cannot create an empty identifier");
741   assert(str.find('\0') == StringRef::npos &&
742          "Cannot create an identifier with a nul character");
743 
744   auto getDialectOrContext = [&]() {
745     PointerUnion<Dialect *, MLIRContext *> dialectOrContext = context;
746     auto dialectNamePair = str.split('.');
747     if (!dialectNamePair.first.empty())
748       if (Dialect *dialect = context->getLoadedDialect(dialectNamePair.first))
749         dialectOrContext = dialect;
750     return dialectOrContext;
751   };
752 
753   auto &impl = context->getImpl();
754   if (!context->isMultithreadingEnabled()) {
755     auto insertedIt = impl.identifiers.insert({str, nullptr});
756     if (insertedIt.second)
757       insertedIt.first->second = getDialectOrContext();
758     return Identifier(&*insertedIt.first);
759   }
760 
761   // Check for an existing instance in the local cache.
762   auto *&localEntry = (*impl.localIdentifierCache)[str];
763   if (localEntry)
764     return Identifier(localEntry);
765 
766   // Check for an existing identifier in read-only mode.
767   {
768     llvm::sys::SmartScopedReader<true> contextLock(impl.identifierMutex);
769     auto it = impl.identifiers.find(str);
770     if (it != impl.identifiers.end()) {
771       localEntry = &*it;
772       return Identifier(localEntry);
773     }
774   }
775 
776   // Acquire a writer-lock so that we can safely create the new instance.
777   llvm::sys::SmartScopedWriter<true> contextLock(impl.identifierMutex);
778   auto it = impl.identifiers.insert({str, getDialectOrContext()}).first;
779   localEntry = &*it;
780   return Identifier(localEntry);
781 }
782 
783 Dialect *Identifier::getDialect() {
784   return entry->second.dyn_cast<Dialect *>();
785 }
786 
787 MLIRContext *Identifier::getContext() {
788   if (Dialect *dialect = getDialect())
789     return dialect->getContext();
790   return entry->second.get<MLIRContext *>();
791 }
792 
793 //===----------------------------------------------------------------------===//
794 // Type uniquing
795 //===----------------------------------------------------------------------===//
796 
797 /// Returns the storage uniquer used for constructing type storage instances.
798 /// This should not be used directly.
799 StorageUniquer &MLIRContext::getTypeUniquer() { return getImpl().typeUniquer; }
800 
801 BFloat16Type BFloat16Type::get(MLIRContext *context) {
802   return context->getImpl().bf16Ty;
803 }
804 Float16Type Float16Type::get(MLIRContext *context) {
805   return context->getImpl().f16Ty;
806 }
807 Float32Type Float32Type::get(MLIRContext *context) {
808   return context->getImpl().f32Ty;
809 }
810 Float64Type Float64Type::get(MLIRContext *context) {
811   return context->getImpl().f64Ty;
812 }
813 Float80Type Float80Type::get(MLIRContext *context) {
814   return context->getImpl().f80Ty;
815 }
816 Float128Type Float128Type::get(MLIRContext *context) {
817   return context->getImpl().f128Ty;
818 }
819 
820 /// Get an instance of the IndexType.
821 IndexType IndexType::get(MLIRContext *context) {
822   return context->getImpl().indexTy;
823 }
824 
825 /// Return an existing integer type instance if one is cached within the
826 /// context.
827 static IntegerType
828 getCachedIntegerType(unsigned width,
829                      IntegerType::SignednessSemantics signedness,
830                      MLIRContext *context) {
831   if (signedness != IntegerType::Signless)
832     return IntegerType();
833 
834   switch (width) {
835   case 1:
836     return context->getImpl().int1Ty;
837   case 8:
838     return context->getImpl().int8Ty;
839   case 16:
840     return context->getImpl().int16Ty;
841   case 32:
842     return context->getImpl().int32Ty;
843   case 64:
844     return context->getImpl().int64Ty;
845   case 128:
846     return context->getImpl().int128Ty;
847   default:
848     return IntegerType();
849   }
850 }
851 
852 IntegerType IntegerType::get(MLIRContext *context, unsigned width,
853                              IntegerType::SignednessSemantics signedness) {
854   if (auto cached = getCachedIntegerType(width, signedness, context))
855     return cached;
856   return Base::get(context, width, signedness);
857 }
858 
859 IntegerType IntegerType::getChecked(Location location, unsigned width,
860                                     SignednessSemantics signedness) {
861   if (auto cached =
862           getCachedIntegerType(width, signedness, location->getContext()))
863     return cached;
864   return Base::getChecked(location, width, signedness);
865 }
866 
867 /// Get an instance of the NoneType.
868 NoneType NoneType::get(MLIRContext *context) {
869   if (NoneType cachedInst = context->getImpl().noneType)
870     return cachedInst;
871   // Note: May happen when initializing the singleton attributes of the builtin
872   // dialect.
873   return Base::get(context);
874 }
875 
876 //===----------------------------------------------------------------------===//
877 // Attribute uniquing
878 //===----------------------------------------------------------------------===//
879 
880 /// Returns the storage uniquer used for constructing attribute storage
881 /// instances. This should not be used directly.
882 StorageUniquer &MLIRContext::getAttributeUniquer() {
883   return getImpl().attributeUniquer;
884 }
885 
886 /// Initialize the given attribute storage instance.
887 void AttributeUniquer::initializeAttributeStorage(AttributeStorage *storage,
888                                                   MLIRContext *ctx,
889                                                   TypeID attrID) {
890   storage->initialize(AbstractAttribute::lookup(attrID, ctx));
891 
892   // If the attribute did not provide a type, then default to NoneType.
893   if (!storage->getType())
894     storage->setType(NoneType::get(ctx));
895 }
896 
897 BoolAttr BoolAttr::get(MLIRContext *context, bool value) {
898   return value ? context->getImpl().trueAttr : context->getImpl().falseAttr;
899 }
900 
901 UnitAttr UnitAttr::get(MLIRContext *context) {
902   return context->getImpl().unitAttr;
903 }
904 
905 Location UnknownLoc::get(MLIRContext *context) {
906   return context->getImpl().unknownLocAttr;
907 }
908 
909 /// Return empty dictionary.
910 DictionaryAttr DictionaryAttr::getEmpty(MLIRContext *context) {
911   return context->getImpl().emptyDictionaryAttr;
912 }
913 
914 //===----------------------------------------------------------------------===//
915 // AffineMap uniquing
916 //===----------------------------------------------------------------------===//
917 
918 StorageUniquer &MLIRContext::getAffineUniquer() {
919   return getImpl().affineUniquer;
920 }
921 
922 AffineMap AffineMap::getImpl(unsigned dimCount, unsigned symbolCount,
923                              ArrayRef<AffineExpr> results,
924                              MLIRContext *context) {
925   auto &impl = context->getImpl();
926   auto key = std::make_tuple(dimCount, symbolCount, results);
927 
928   // Safely get or create an AffineMap instance.
929   return safeGetOrCreate(
930       impl.affineMaps, key, impl.affineMutex, impl.threadingIsEnabled, [&] {
931         auto *res = impl.affineAllocator.Allocate<detail::AffineMapStorage>();
932 
933         // Copy the results into the bump pointer.
934         results = copyArrayRefInto(impl.affineAllocator, results);
935 
936         // Initialize the memory using placement new.
937         new (res)
938             detail::AffineMapStorage{dimCount, symbolCount, results, context};
939         return AffineMap(res);
940       });
941 }
942 
943 AffineMap AffineMap::get(MLIRContext *context) {
944   return getImpl(/*dimCount=*/0, /*symbolCount=*/0, /*results=*/{}, context);
945 }
946 
947 AffineMap AffineMap::get(unsigned dimCount, unsigned symbolCount,
948                          MLIRContext *context) {
949   return getImpl(dimCount, symbolCount, /*results=*/{}, context);
950 }
951 
952 AffineMap AffineMap::get(unsigned dimCount, unsigned symbolCount,
953                          AffineExpr result) {
954   return getImpl(dimCount, symbolCount, {result}, result.getContext());
955 }
956 
957 AffineMap AffineMap::get(unsigned dimCount, unsigned symbolCount,
958                          ArrayRef<AffineExpr> results, MLIRContext *context) {
959   return getImpl(dimCount, symbolCount, results, context);
960 }
961 
962 //===----------------------------------------------------------------------===//
963 // Integer Sets: these are allocated into the bump pointer, and are immutable.
964 // Unlike AffineMap's, these are uniqued only if they are small.
965 //===----------------------------------------------------------------------===//
966 
967 IntegerSet IntegerSet::get(unsigned dimCount, unsigned symbolCount,
968                            ArrayRef<AffineExpr> constraints,
969                            ArrayRef<bool> eqFlags) {
970   // The number of constraints can't be zero.
971   assert(!constraints.empty());
972   assert(constraints.size() == eqFlags.size());
973 
974   auto &impl = constraints[0].getContext()->getImpl();
975 
976   // A utility function to construct a new IntegerSetStorage instance.
977   auto constructorFn = [&] {
978     auto *res = impl.affineAllocator.Allocate<detail::IntegerSetStorage>();
979 
980     // Copy the results and equality flags into the bump pointer.
981     constraints = copyArrayRefInto(impl.affineAllocator, constraints);
982     eqFlags = copyArrayRefInto(impl.affineAllocator, eqFlags);
983 
984     // Initialize the memory using placement new.
985     new (res)
986         detail::IntegerSetStorage{dimCount, symbolCount, constraints, eqFlags};
987     return IntegerSet(res);
988   };
989 
990   // If this instance is uniqued, then we handle it separately so that multiple
991   // threads may simultaneously access existing instances.
992   if (constraints.size() < IntegerSet::kUniquingThreshold) {
993     auto key = std::make_tuple(dimCount, symbolCount, constraints, eqFlags);
994     return safeGetOrCreate(impl.integerSets, key, impl.affineMutex,
995                            impl.threadingIsEnabled, constructorFn);
996   }
997 
998   // Otherwise, acquire a writer-lock so that we can safely create the new
999   // instance.
1000   ScopedWriterLock affineLock(impl.affineMutex, impl.threadingIsEnabled);
1001   return constructorFn();
1002 }
1003 
1004 //===----------------------------------------------------------------------===//
1005 // StorageUniquerSupport
1006 //===----------------------------------------------------------------------===//
1007 
1008 /// Utility method to generate a default location for use when checking the
1009 /// construction invariants of a storage object. This is defined out-of-line to
1010 /// avoid the need to include Location.h.
1011 const AttributeStorage *
1012 mlir::detail::generateUnknownStorageLocation(MLIRContext *ctx) {
1013   return reinterpret_cast<const AttributeStorage *>(
1014       ctx->getImpl().unknownLocAttr.getAsOpaquePointer());
1015 }
1016