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