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