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/DebugAction.h"
28 #include "mlir/Support/ThreadLocalCache.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/DenseSet.h"
31 #include "llvm/ADT/SetVector.h"
32 #include "llvm/ADT/StringSet.h"
33 #include "llvm/ADT/Twine.h"
34 #include "llvm/Support/Allocator.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/RWMutex.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   /// This is a list of dialects that are created referring to this context.
265   /// The MLIRContext owns the objects.
266   DenseMap<StringRef, std::unique_ptr<Dialect>> loadedDialects;
267   DialectRegistry dialectsRegistry;
268 
269   /// This is a mapping from operation name to AbstractOperation for registered
270   /// operations.
271   llvm::StringMap<AbstractOperation> registeredOperations;
272 
273   /// Identifiers are uniqued by string value and use the internal string set
274   /// for storage.
275   llvm::StringMap<PointerUnion<Dialect *, MLIRContext *>,
276                   llvm::BumpPtrAllocator &>
277       identifiers;
278   /// A thread local cache of identifiers to reduce lock contention.
279   ThreadLocalCache<llvm::StringMap<
280       llvm::StringMapEntry<PointerUnion<Dialect *, MLIRContext *>> *>>
281       localIdentifierCache;
282 
283   /// An allocator used for AbstractAttribute and AbstractType objects.
284   llvm::BumpPtrAllocator abstractDialectSymbolAllocator;
285 
286   //===--------------------------------------------------------------------===//
287   // Affine uniquing
288   //===--------------------------------------------------------------------===//
289 
290   // Affine allocator and mutex for thread safety.
291   llvm::BumpPtrAllocator affineAllocator;
292   llvm::sys::SmartRWMutex<true> affineMutex;
293 
294   // Affine map uniquing.
295   using AffineMapSet = DenseSet<AffineMap, AffineMapKeyInfo>;
296   AffineMapSet affineMaps;
297 
298   // Integer set uniquing.
299   using IntegerSets = DenseSet<IntegerSet, IntegerSetKeyInfo>;
300   IntegerSets integerSets;
301 
302   // Affine expression uniquing.
303   StorageUniquer affineUniquer;
304 
305   //===--------------------------------------------------------------------===//
306   // Type uniquing
307   //===--------------------------------------------------------------------===//
308 
309   DenseMap<TypeID, const AbstractType *> registeredTypes;
310   StorageUniquer typeUniquer;
311 
312   /// Cached Type Instances.
313   BFloat16Type bf16Ty;
314   Float16Type f16Ty;
315   Float32Type f32Ty;
316   Float64Type f64Ty;
317   Float80Type f80Ty;
318   Float128Type f128Ty;
319   IndexType indexTy;
320   IntegerType int1Ty, int8Ty, int16Ty, int32Ty, int64Ty, int128Ty;
321   NoneType noneType;
322 
323   //===--------------------------------------------------------------------===//
324   // Attribute uniquing
325   //===--------------------------------------------------------------------===//
326 
327   DenseMap<TypeID, const AbstractAttribute *> registeredAttributes;
328   StorageUniquer attributeUniquer;
329 
330   /// Cached Attribute Instances.
331   BoolAttr falseAttr, trueAttr;
332   UnitAttr unitAttr;
333   UnknownLoc unknownLocAttr;
334   DictionaryAttr emptyDictionaryAttr;
335 
336 public:
337   MLIRContextImpl() : identifiers(identifierAllocator) {}
338   ~MLIRContextImpl() {
339     for (auto typeMapping : registeredTypes)
340       typeMapping.second->~AbstractType();
341     for (auto attrMapping : registeredAttributes)
342       attrMapping.second->~AbstractAttribute();
343   }
344 };
345 } // end namespace mlir
346 
347 MLIRContext::MLIRContext() : MLIRContext(DialectRegistry()) {}
348 
349 MLIRContext::MLIRContext(const DialectRegistry &registry)
350     : impl(new MLIRContextImpl) {
351   // Initialize values based on the command line flags if they were provided.
352   if (clOptions.isConstructed()) {
353     disableMultithreading(clOptions->disableThreading);
354     printOpOnDiagnostic(clOptions->printOpOnDiagnostic);
355     printStackTraceOnDiagnostic(clOptions->printStackTraceOnDiagnostic);
356   }
357 
358   // Ensure the builtin dialect is always pre-loaded.
359   getOrLoadDialect<BuiltinDialect>();
360 
361   // Pre-populate the registry.
362   registry.appendTo(impl->dialectsRegistry);
363 
364   // Initialize several common attributes and types to avoid the need to lock
365   // the context when accessing them.
366 
367   //// Types.
368   /// Floating-point Types.
369   impl->bf16Ty = TypeUniquer::get<BFloat16Type>(this);
370   impl->f16Ty = TypeUniquer::get<Float16Type>(this);
371   impl->f32Ty = TypeUniquer::get<Float32Type>(this);
372   impl->f64Ty = TypeUniquer::get<Float64Type>(this);
373   impl->f80Ty = TypeUniquer::get<Float80Type>(this);
374   impl->f128Ty = TypeUniquer::get<Float128Type>(this);
375   /// Index Type.
376   impl->indexTy = TypeUniquer::get<IndexType>(this);
377   /// Integer Types.
378   impl->int1Ty = TypeUniquer::get<IntegerType>(this, 1, IntegerType::Signless);
379   impl->int8Ty = TypeUniquer::get<IntegerType>(this, 8, IntegerType::Signless);
380   impl->int16Ty =
381       TypeUniquer::get<IntegerType>(this, 16, IntegerType::Signless);
382   impl->int32Ty =
383       TypeUniquer::get<IntegerType>(this, 32, IntegerType::Signless);
384   impl->int64Ty =
385       TypeUniquer::get<IntegerType>(this, 64, IntegerType::Signless);
386   impl->int128Ty =
387       TypeUniquer::get<IntegerType>(this, 128, IntegerType::Signless);
388   /// None Type.
389   impl->noneType = TypeUniquer::get<NoneType>(this);
390 
391   //// Attributes.
392   //// Note: These must be registered after the types as they may generate one
393   //// of the above types internally.
394   /// Bool Attributes.
395   impl->falseAttr = AttributeUniquer::get<IntegerAttr>(
396                         this, impl->int1Ty, APInt(/*numBits=*/1, false))
397                         .cast<BoolAttr>();
398   impl->trueAttr = AttributeUniquer::get<IntegerAttr>(
399                        this, impl->int1Ty, APInt(/*numBits=*/1, true))
400                        .cast<BoolAttr>();
401   /// Unit Attribute.
402   impl->unitAttr = AttributeUniquer::get<UnitAttr>(this);
403   /// Unknown Location Attribute.
404   impl->unknownLocAttr = AttributeUniquer::get<UnknownLoc>(this);
405   /// The empty dictionary attribute.
406   impl->emptyDictionaryAttr = DictionaryAttr::getEmptyUnchecked(this);
407 
408   // Register the affine storage objects with the uniquer.
409   impl->affineUniquer
410       .registerParametricStorageType<AffineBinaryOpExprStorage>();
411   impl->affineUniquer
412       .registerParametricStorageType<AffineConstantExprStorage>();
413   impl->affineUniquer.registerParametricStorageType<AffineDimExprStorage>();
414 }
415 
416 MLIRContext::~MLIRContext() {}
417 
418 /// Copy the specified array of elements into memory managed by the provided
419 /// bump pointer allocator.  This assumes the elements are all PODs.
420 template <typename T>
421 static ArrayRef<T> copyArrayRefInto(llvm::BumpPtrAllocator &allocator,
422                                     ArrayRef<T> elements) {
423   auto result = allocator.Allocate<T>(elements.size());
424   std::uninitialized_copy(elements.begin(), elements.end(), result);
425   return ArrayRef<T>(result, elements.size());
426 }
427 
428 //===----------------------------------------------------------------------===//
429 // Debugging
430 //===----------------------------------------------------------------------===//
431 
432 DebugActionManager &MLIRContext::getDebugActionManager() {
433   return getImpl().debugActionManager;
434 }
435 
436 //===----------------------------------------------------------------------===//
437 // Diagnostic Handlers
438 //===----------------------------------------------------------------------===//
439 
440 /// Returns the diagnostic engine for this context.
441 DiagnosticEngine &MLIRContext::getDiagEngine() { return getImpl().diagEngine; }
442 
443 //===----------------------------------------------------------------------===//
444 // Dialect and Operation Registration
445 //===----------------------------------------------------------------------===//
446 
447 void MLIRContext::appendDialectRegistry(const DialectRegistry &registry) {
448   registry.appendTo(impl->dialectsRegistry);
449 
450   // For the already loaded dialects, register the interfaces immediately.
451   for (const auto &kvp : impl->loadedDialects)
452     registry.registerDelayedInterfaces(kvp.second.get());
453 }
454 
455 const DialectRegistry &MLIRContext::getDialectRegistry() {
456   return impl->dialectsRegistry;
457 }
458 
459 /// Return information about all registered IR dialects.
460 std::vector<Dialect *> MLIRContext::getLoadedDialects() {
461   std::vector<Dialect *> result;
462   result.reserve(impl->loadedDialects.size());
463   for (auto &dialect : impl->loadedDialects)
464     result.push_back(dialect.second.get());
465   llvm::array_pod_sort(result.begin(), result.end(),
466                        [](Dialect *const *lhs, Dialect *const *rhs) -> int {
467                          return (*lhs)->getNamespace() < (*rhs)->getNamespace();
468                        });
469   return result;
470 }
471 std::vector<StringRef> MLIRContext::getAvailableDialects() {
472   std::vector<StringRef> result;
473   for (auto dialect : impl->dialectsRegistry.getDialectNames())
474     result.push_back(dialect);
475   return result;
476 }
477 
478 /// Get a registered IR dialect with the given namespace. If none is found,
479 /// then return nullptr.
480 Dialect *MLIRContext::getLoadedDialect(StringRef name) {
481   // Dialects are sorted by name, so we can use binary search for lookup.
482   auto it = impl->loadedDialects.find(name);
483   return (it != impl->loadedDialects.end()) ? it->second.get() : nullptr;
484 }
485 
486 Dialect *MLIRContext::getOrLoadDialect(StringRef name) {
487   Dialect *dialect = getLoadedDialect(name);
488   if (dialect)
489     return dialect;
490   DialectAllocatorFunctionRef allocator =
491       impl->dialectsRegistry.getDialectAllocator(name);
492   return allocator ? allocator(this) : nullptr;
493 }
494 
495 /// Get a dialect for the provided namespace and TypeID: abort the program if a
496 /// dialect exist for this namespace with different TypeID. Returns a pointer to
497 /// the dialect owned by the context.
498 Dialect *
499 MLIRContext::getOrLoadDialect(StringRef dialectNamespace, TypeID dialectID,
500                               function_ref<std::unique_ptr<Dialect>()> ctor) {
501   auto &impl = getImpl();
502   // Get the correct insertion position sorted by namespace.
503   std::unique_ptr<Dialect> &dialect = impl.loadedDialects[dialectNamespace];
504 
505   if (!dialect) {
506     LLVM_DEBUG(llvm::dbgs()
507                << "Load new dialect in Context " << dialectNamespace << "\n");
508 #ifndef NDEBUG
509     if (impl.multiThreadedExecutionContext != 0)
510       llvm::report_fatal_error(
511           "Loading a dialect (" + dialectNamespace +
512           ") while in a multi-threaded execution context (maybe "
513           "the PassManager): this can indicate a "
514           "missing `dependentDialects` in a pass for example.");
515 #endif
516     dialect = ctor();
517     assert(dialect && "dialect ctor failed");
518 
519     // Refresh all the identifiers dialect field, this catches cases where a
520     // dialect may be loaded after identifier prefixed with this dialect name
521     // were already created.
522     llvm::SmallString<32> dialectPrefix(dialectNamespace);
523     dialectPrefix.push_back('.');
524     for (auto &identifierEntry : impl.identifiers)
525       if (identifierEntry.second.is<MLIRContext *>() &&
526           identifierEntry.first().startswith(dialectPrefix))
527         identifierEntry.second = dialect.get();
528 
529     // Actually register the interfaces with delayed registration.
530     impl.dialectsRegistry.registerDelayedInterfaces(dialect.get());
531     return dialect.get();
532   }
533 
534   // Abort if dialect with namespace has already been registered.
535   if (dialect->getTypeID() != dialectID)
536     llvm::report_fatal_error("a dialect with namespace '" + dialectNamespace +
537                              "' has already been registered");
538 
539   return dialect.get();
540 }
541 
542 void MLIRContext::loadAllAvailableDialects() {
543   for (StringRef name : getAvailableDialects())
544     getOrLoadDialect(name);
545 }
546 
547 llvm::hash_code MLIRContext::getRegistryHash() {
548   llvm::hash_code hash(0);
549   // Factor in number of loaded dialects, attributes, operations, types.
550   hash = llvm::hash_combine(hash, impl->loadedDialects.size());
551   hash = llvm::hash_combine(hash, impl->registeredAttributes.size());
552   hash = llvm::hash_combine(hash, impl->registeredOperations.size());
553   hash = llvm::hash_combine(hash, impl->registeredTypes.size());
554   return hash;
555 }
556 
557 bool MLIRContext::allowsUnregisteredDialects() {
558   return impl->allowUnregisteredDialects;
559 }
560 
561 void MLIRContext::allowUnregisteredDialects(bool allowing) {
562   impl->allowUnregisteredDialects = allowing;
563 }
564 
565 /// Return true if multi-threading is disabled by the context.
566 bool MLIRContext::isMultithreadingEnabled() {
567   return impl->threadingIsEnabled && llvm::llvm_is_multithreaded();
568 }
569 
570 /// Set the flag specifying if multi-threading is disabled by the context.
571 void MLIRContext::disableMultithreading(bool disable) {
572   impl->threadingIsEnabled = !disable;
573 
574   // Update the threading mode for each of the uniquers.
575   impl->affineUniquer.disableMultithreading(disable);
576   impl->attributeUniquer.disableMultithreading(disable);
577   impl->typeUniquer.disableMultithreading(disable);
578 }
579 
580 void MLIRContext::enterMultiThreadedExecution() {
581 #ifndef NDEBUG
582   ++impl->multiThreadedExecutionContext;
583 #endif
584 }
585 void MLIRContext::exitMultiThreadedExecution() {
586 #ifndef NDEBUG
587   --impl->multiThreadedExecutionContext;
588 #endif
589 }
590 
591 /// Return true if we should attach the operation to diagnostics emitted via
592 /// Operation::emit.
593 bool MLIRContext::shouldPrintOpOnDiagnostic() {
594   return impl->printOpOnDiagnostic;
595 }
596 
597 /// Set the flag specifying if we should attach the operation to diagnostics
598 /// emitted via Operation::emit.
599 void MLIRContext::printOpOnDiagnostic(bool enable) {
600   impl->printOpOnDiagnostic = enable;
601 }
602 
603 /// Return true if we should attach the current stacktrace to diagnostics when
604 /// emitted.
605 bool MLIRContext::shouldPrintStackTraceOnDiagnostic() {
606   return impl->printStackTraceOnDiagnostic;
607 }
608 
609 /// Set the flag specifying if we should attach the current stacktrace when
610 /// emitting diagnostics.
611 void MLIRContext::printStackTraceOnDiagnostic(bool enable) {
612   impl->printStackTraceOnDiagnostic = enable;
613 }
614 
615 /// Return information about all registered operations.  This isn't very
616 /// efficient, typically you should ask the operations about their properties
617 /// directly.
618 std::vector<AbstractOperation *> MLIRContext::getRegisteredOperations() {
619   // We just have the operations in a non-deterministic hash table order. Dump
620   // into a temporary array, then sort it by operation name to get a stable
621   // ordering.
622   llvm::StringMap<AbstractOperation> &registeredOps =
623       impl->registeredOperations;
624 
625   std::vector<AbstractOperation *> result;
626   result.reserve(registeredOps.size());
627   for (auto &elt : registeredOps)
628     result.push_back(&elt.second);
629   llvm::array_pod_sort(
630       result.begin(), result.end(),
631       [](AbstractOperation *const *lhs, AbstractOperation *const *rhs) {
632         return (*lhs)->name.compare((*rhs)->name);
633       });
634 
635   return result;
636 }
637 
638 bool MLIRContext::isOperationRegistered(StringRef name) {
639   return impl->registeredOperations.count(name);
640 }
641 
642 void Dialect::addType(TypeID typeID, AbstractType &&typeInfo) {
643   auto &impl = context->getImpl();
644   assert(impl.multiThreadedExecutionContext == 0 &&
645          "Registering a new type kind while in a multi-threaded execution "
646          "context");
647   auto *newInfo =
648       new (impl.abstractDialectSymbolAllocator.Allocate<AbstractType>())
649           AbstractType(std::move(typeInfo));
650   if (!impl.registeredTypes.insert({typeID, newInfo}).second)
651     llvm::report_fatal_error("Dialect Type already registered.");
652 }
653 
654 void Dialect::addAttribute(TypeID typeID, AbstractAttribute &&attrInfo) {
655   auto &impl = context->getImpl();
656   assert(impl.multiThreadedExecutionContext == 0 &&
657          "Registering a new attribute kind while in a multi-threaded execution "
658          "context");
659   auto *newInfo =
660       new (impl.abstractDialectSymbolAllocator.Allocate<AbstractAttribute>())
661           AbstractAttribute(std::move(attrInfo));
662   if (!impl.registeredAttributes.insert({typeID, newInfo}).second)
663     llvm::report_fatal_error("Dialect Attribute already registered.");
664 }
665 
666 //===----------------------------------------------------------------------===//
667 // AbstractAttribute
668 //===----------------------------------------------------------------------===//
669 
670 /// Get the dialect that registered the attribute with the provided typeid.
671 const AbstractAttribute &AbstractAttribute::lookup(TypeID typeID,
672                                                    MLIRContext *context) {
673   auto &impl = context->getImpl();
674   auto it = impl.registeredAttributes.find(typeID);
675   if (it == impl.registeredAttributes.end())
676     llvm::report_fatal_error("Trying to create an Attribute that was not "
677                              "registered in this MLIRContext.");
678   return *it->second;
679 }
680 
681 //===----------------------------------------------------------------------===//
682 // AbstractOperation
683 //===----------------------------------------------------------------------===//
684 
685 ParseResult AbstractOperation::parseAssembly(OpAsmParser &parser,
686                                              OperationState &result) const {
687   return parseAssemblyFn(parser, result);
688 }
689 
690 /// Look up the specified operation in the operation set and return a pointer
691 /// to it if present. Otherwise, return a null pointer.
692 const AbstractOperation *AbstractOperation::lookup(StringRef opName,
693                                                    MLIRContext *context) {
694   auto &impl = context->getImpl();
695   auto it = impl.registeredOperations.find(opName);
696   if (it != impl.registeredOperations.end())
697     return &it->second;
698   return nullptr;
699 }
700 
701 void AbstractOperation::insert(
702     StringRef name, Dialect &dialect, TypeID typeID,
703     ParseAssemblyFn parseAssembly, PrintAssemblyFn printAssembly,
704     VerifyInvariantsFn verifyInvariants, FoldHookFn foldHook,
705     GetCanonicalizationPatternsFn getCanonicalizationPatterns,
706     detail::InterfaceMap &&interfaceMap, HasTraitFn hasTrait) {
707   AbstractOperation opInfo(
708       name, dialect, typeID, parseAssembly, printAssembly, verifyInvariants,
709       foldHook, getCanonicalizationPatterns, std::move(interfaceMap), hasTrait);
710 
711   auto &impl = dialect.getContext()->getImpl();
712   assert(impl.multiThreadedExecutionContext == 0 &&
713          "Registering a new operation kind while in a multi-threaded execution "
714          "context");
715   if (!impl.registeredOperations.insert({name, std::move(opInfo)}).second) {
716     llvm::errs() << "error: operation named '" << name
717                  << "' is already registered.\n";
718     abort();
719   }
720 }
721 
722 AbstractOperation::AbstractOperation(
723     StringRef name, Dialect &dialect, TypeID typeID,
724     ParseAssemblyFn parseAssembly, PrintAssemblyFn printAssembly,
725     VerifyInvariantsFn verifyInvariants, FoldHookFn foldHook,
726     GetCanonicalizationPatternsFn getCanonicalizationPatterns,
727     detail::InterfaceMap &&interfaceMap, HasTraitFn hasTrait)
728     : name(Identifier::get(name, dialect.getContext())), dialect(dialect),
729       typeID(typeID), interfaceMap(std::move(interfaceMap)),
730       foldHookFn(foldHook),
731       getCanonicalizationPatternsFn(getCanonicalizationPatterns),
732       hasTraitFn(hasTrait), parseAssemblyFn(parseAssembly),
733       printAssemblyFn(printAssembly), verifyInvariantsFn(verifyInvariants) {}
734 
735 //===----------------------------------------------------------------------===//
736 // AbstractType
737 //===----------------------------------------------------------------------===//
738 
739 const AbstractType &AbstractType::lookup(TypeID typeID, MLIRContext *context) {
740   auto &impl = context->getImpl();
741   auto it = impl.registeredTypes.find(typeID);
742   if (it == impl.registeredTypes.end())
743     llvm::report_fatal_error(
744         "Trying to create a Type that was not registered in this MLIRContext.");
745   return *it->second;
746 }
747 
748 //===----------------------------------------------------------------------===//
749 // Identifier uniquing
750 //===----------------------------------------------------------------------===//
751 
752 /// Return an identifier for the specified string.
753 Identifier Identifier::get(StringRef str, MLIRContext *context) {
754   // Check invariants after seeing if we already have something in the
755   // identifier table - if we already had it in the table, then it already
756   // passed invariant checks.
757   assert(!str.empty() && "Cannot create an empty identifier");
758   assert(str.find('\0') == StringRef::npos &&
759          "Cannot create an identifier with a nul character");
760 
761   auto getDialectOrContext = [&]() {
762     PointerUnion<Dialect *, MLIRContext *> dialectOrContext = context;
763     auto dialectNamePair = str.split('.');
764     if (!dialectNamePair.first.empty())
765       if (Dialect *dialect = context->getLoadedDialect(dialectNamePair.first))
766         dialectOrContext = dialect;
767     return dialectOrContext;
768   };
769 
770   auto &impl = context->getImpl();
771   if (!context->isMultithreadingEnabled()) {
772     auto insertedIt = impl.identifiers.insert({str, nullptr});
773     if (insertedIt.second)
774       insertedIt.first->second = getDialectOrContext();
775     return Identifier(&*insertedIt.first);
776   }
777 
778   // Check for an existing instance in the local cache.
779   auto *&localEntry = (*impl.localIdentifierCache)[str];
780   if (localEntry)
781     return Identifier(localEntry);
782 
783   // Check for an existing identifier in read-only mode.
784   {
785     llvm::sys::SmartScopedReader<true> contextLock(impl.identifierMutex);
786     auto it = impl.identifiers.find(str);
787     if (it != impl.identifiers.end()) {
788       localEntry = &*it;
789       return Identifier(localEntry);
790     }
791   }
792 
793   // Acquire a writer-lock so that we can safely create the new instance.
794   llvm::sys::SmartScopedWriter<true> contextLock(impl.identifierMutex);
795   auto it = impl.identifiers.insert({str, getDialectOrContext()}).first;
796   localEntry = &*it;
797   return Identifier(localEntry);
798 }
799 
800 Dialect *Identifier::getDialect() {
801   return entry->second.dyn_cast<Dialect *>();
802 }
803 
804 MLIRContext *Identifier::getContext() {
805   if (Dialect *dialect = getDialect())
806     return dialect->getContext();
807   return entry->second.get<MLIRContext *>();
808 }
809 
810 //===----------------------------------------------------------------------===//
811 // Type uniquing
812 //===----------------------------------------------------------------------===//
813 
814 /// Returns the storage uniquer used for constructing type storage instances.
815 /// This should not be used directly.
816 StorageUniquer &MLIRContext::getTypeUniquer() { return getImpl().typeUniquer; }
817 
818 BFloat16Type BFloat16Type::get(MLIRContext *context) {
819   return context->getImpl().bf16Ty;
820 }
821 Float16Type Float16Type::get(MLIRContext *context) {
822   return context->getImpl().f16Ty;
823 }
824 Float32Type Float32Type::get(MLIRContext *context) {
825   return context->getImpl().f32Ty;
826 }
827 Float64Type Float64Type::get(MLIRContext *context) {
828   return context->getImpl().f64Ty;
829 }
830 Float80Type Float80Type::get(MLIRContext *context) {
831   return context->getImpl().f80Ty;
832 }
833 Float128Type Float128Type::get(MLIRContext *context) {
834   return context->getImpl().f128Ty;
835 }
836 
837 /// Get an instance of the IndexType.
838 IndexType IndexType::get(MLIRContext *context) {
839   return context->getImpl().indexTy;
840 }
841 
842 /// Return an existing integer type instance if one is cached within the
843 /// context.
844 static IntegerType
845 getCachedIntegerType(unsigned width,
846                      IntegerType::SignednessSemantics signedness,
847                      MLIRContext *context) {
848   if (signedness != IntegerType::Signless)
849     return IntegerType();
850 
851   switch (width) {
852   case 1:
853     return context->getImpl().int1Ty;
854   case 8:
855     return context->getImpl().int8Ty;
856   case 16:
857     return context->getImpl().int16Ty;
858   case 32:
859     return context->getImpl().int32Ty;
860   case 64:
861     return context->getImpl().int64Ty;
862   case 128:
863     return context->getImpl().int128Ty;
864   default:
865     return IntegerType();
866   }
867 }
868 
869 IntegerType IntegerType::get(MLIRContext *context, unsigned width,
870                              IntegerType::SignednessSemantics signedness) {
871   if (auto cached = getCachedIntegerType(width, signedness, context))
872     return cached;
873   return Base::get(context, width, signedness);
874 }
875 
876 IntegerType
877 IntegerType::getChecked(function_ref<InFlightDiagnostic()> emitError,
878                         MLIRContext *context, unsigned width,
879                         SignednessSemantics signedness) {
880   if (auto cached = getCachedIntegerType(width, signedness, context))
881     return cached;
882   return Base::getChecked(emitError, context, width, signedness);
883 }
884 
885 /// Get an instance of the NoneType.
886 NoneType NoneType::get(MLIRContext *context) {
887   if (NoneType cachedInst = context->getImpl().noneType)
888     return cachedInst;
889   // Note: May happen when initializing the singleton attributes of the builtin
890   // dialect.
891   return Base::get(context);
892 }
893 
894 //===----------------------------------------------------------------------===//
895 // Attribute uniquing
896 //===----------------------------------------------------------------------===//
897 
898 /// Returns the storage uniquer used for constructing attribute storage
899 /// instances. This should not be used directly.
900 StorageUniquer &MLIRContext::getAttributeUniquer() {
901   return getImpl().attributeUniquer;
902 }
903 
904 /// Initialize the given attribute storage instance.
905 void AttributeUniquer::initializeAttributeStorage(AttributeStorage *storage,
906                                                   MLIRContext *ctx,
907                                                   TypeID attrID) {
908   storage->initialize(AbstractAttribute::lookup(attrID, ctx));
909 
910   // If the attribute did not provide a type, then default to NoneType.
911   if (!storage->getType())
912     storage->setType(NoneType::get(ctx));
913 }
914 
915 BoolAttr BoolAttr::get(MLIRContext *context, bool value) {
916   return value ? context->getImpl().trueAttr : context->getImpl().falseAttr;
917 }
918 
919 UnitAttr UnitAttr::get(MLIRContext *context) {
920   return context->getImpl().unitAttr;
921 }
922 
923 Location UnknownLoc::get(MLIRContext *context) {
924   return context->getImpl().unknownLocAttr;
925 }
926 
927 /// Return empty dictionary.
928 DictionaryAttr DictionaryAttr::getEmpty(MLIRContext *context) {
929   return context->getImpl().emptyDictionaryAttr;
930 }
931 
932 //===----------------------------------------------------------------------===//
933 // AffineMap uniquing
934 //===----------------------------------------------------------------------===//
935 
936 StorageUniquer &MLIRContext::getAffineUniquer() {
937   return getImpl().affineUniquer;
938 }
939 
940 AffineMap AffineMap::getImpl(unsigned dimCount, unsigned symbolCount,
941                              ArrayRef<AffineExpr> results,
942                              MLIRContext *context) {
943   auto &impl = context->getImpl();
944   auto key = std::make_tuple(dimCount, symbolCount, results);
945 
946   // Safely get or create an AffineMap instance.
947   return safeGetOrCreate(
948       impl.affineMaps, key, impl.affineMutex, impl.threadingIsEnabled, [&] {
949         auto *res = impl.affineAllocator.Allocate<detail::AffineMapStorage>();
950 
951         // Copy the results into the bump pointer.
952         results = copyArrayRefInto(impl.affineAllocator, results);
953 
954         // Initialize the memory using placement new.
955         new (res)
956             detail::AffineMapStorage{dimCount, symbolCount, results, context};
957         return AffineMap(res);
958       });
959 }
960 
961 AffineMap AffineMap::get(MLIRContext *context) {
962   return getImpl(/*dimCount=*/0, /*symbolCount=*/0, /*results=*/{}, context);
963 }
964 
965 AffineMap AffineMap::get(unsigned dimCount, unsigned symbolCount,
966                          MLIRContext *context) {
967   return getImpl(dimCount, symbolCount, /*results=*/{}, context);
968 }
969 
970 AffineMap AffineMap::get(unsigned dimCount, unsigned symbolCount,
971                          AffineExpr result) {
972   return getImpl(dimCount, symbolCount, {result}, result.getContext());
973 }
974 
975 AffineMap AffineMap::get(unsigned dimCount, unsigned symbolCount,
976                          ArrayRef<AffineExpr> results, MLIRContext *context) {
977   return getImpl(dimCount, symbolCount, results, context);
978 }
979 
980 //===----------------------------------------------------------------------===//
981 // Integer Sets: these are allocated into the bump pointer, and are immutable.
982 // Unlike AffineMap's, these are uniqued only if they are small.
983 //===----------------------------------------------------------------------===//
984 
985 IntegerSet IntegerSet::get(unsigned dimCount, unsigned symbolCount,
986                            ArrayRef<AffineExpr> constraints,
987                            ArrayRef<bool> eqFlags) {
988   // The number of constraints can't be zero.
989   assert(!constraints.empty());
990   assert(constraints.size() == eqFlags.size());
991 
992   auto &impl = constraints[0].getContext()->getImpl();
993 
994   // A utility function to construct a new IntegerSetStorage instance.
995   auto constructorFn = [&] {
996     auto *res = impl.affineAllocator.Allocate<detail::IntegerSetStorage>();
997 
998     // Copy the results and equality flags into the bump pointer.
999     constraints = copyArrayRefInto(impl.affineAllocator, constraints);
1000     eqFlags = copyArrayRefInto(impl.affineAllocator, eqFlags);
1001 
1002     // Initialize the memory using placement new.
1003     new (res)
1004         detail::IntegerSetStorage{dimCount, symbolCount, constraints, eqFlags};
1005     return IntegerSet(res);
1006   };
1007 
1008   // If this instance is uniqued, then we handle it separately so that multiple
1009   // threads may simultaneously access existing instances.
1010   if (constraints.size() < IntegerSet::kUniquingThreshold) {
1011     auto key = std::make_tuple(dimCount, symbolCount, constraints, eqFlags);
1012     return safeGetOrCreate(impl.integerSets, key, impl.affineMutex,
1013                            impl.threadingIsEnabled, constructorFn);
1014   }
1015 
1016   // Otherwise, acquire a writer-lock so that we can safely create the new
1017   // instance.
1018   ScopedWriterLock affineLock(impl.affineMutex, impl.threadingIsEnabled);
1019   return constructorFn();
1020 }
1021 
1022 //===----------------------------------------------------------------------===//
1023 // StorageUniquerSupport
1024 //===----------------------------------------------------------------------===//
1025 
1026 /// Utility method to generate a callback that can be used to generate a
1027 /// diagnostic when checking the construction invariants of a storage object.
1028 /// This is defined out-of-line to avoid the need to include Location.h.
1029 llvm::unique_function<InFlightDiagnostic()>
1030 mlir::detail::getDefaultDiagnosticEmitFn(MLIRContext *ctx) {
1031   return [ctx] { return emitError(UnknownLoc::get(ctx)); };
1032 }
1033 llvm::unique_function<InFlightDiagnostic()>
1034 mlir::detail::getDefaultDiagnosticEmitFn(const Location &loc) {
1035   return [=] { return emitError(loc); };
1036 }
1037