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/Diagnostics.h"
20 #include "mlir/IR/Dialect.h"
21 #include "mlir/IR/Function.h"
22 #include "mlir/IR/Identifier.h"
23 #include "mlir/IR/IntegerSet.h"
24 #include "mlir/IR/Location.h"
25 #include "mlir/IR/Module.h"
26 #include "mlir/IR/Types.h"
27 #include "llvm/ADT/DenseMap.h"
28 #include "llvm/ADT/DenseSet.h"
29 #include "llvm/ADT/SetVector.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/RWMutex.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include <memory>
37 
38 using namespace mlir;
39 using namespace mlir::detail;
40 
41 using llvm::hash_combine;
42 using llvm::hash_combine_range;
43 
44 //===----------------------------------------------------------------------===//
45 // MLIRContext CommandLine Options
46 //===----------------------------------------------------------------------===//
47 
48 namespace {
49 /// This struct contains command line options that can be used to initialize
50 /// various bits of an MLIRContext. This uses a struct wrapper to avoid the need
51 /// for global command line options.
52 struct MLIRContextOptions {
53   llvm::cl::opt<bool> disableThreading{
54       "mlir-disable-threading",
55       llvm::cl::desc("Disabling multi-threading within MLIR")};
56 
57   llvm::cl::opt<bool> printOpOnDiagnostic{
58       "mlir-print-op-on-diagnostic",
59       llvm::cl::desc("When a diagnostic is emitted on an operation, also print "
60                      "the operation as an attached note"),
61       llvm::cl::init(true)};
62 
63   llvm::cl::opt<bool> printStackTraceOnDiagnostic{
64       "mlir-print-stacktrace-on-diagnostic",
65       llvm::cl::desc("When a diagnostic is emitted, also print the stack trace "
66                      "as an attached note")};
67 };
68 } // end anonymous namespace
69 
70 static llvm::ManagedStatic<MLIRContextOptions> clOptions;
71 
72 /// Register a set of useful command-line options that can be used to configure
73 /// various flags within the MLIRContext. These flags are used when constructing
74 /// an MLIR context for initialization.
75 void mlir::registerMLIRContextCLOptions() {
76   // Make sure that the options struct has been initialized.
77   *clOptions;
78 }
79 
80 //===----------------------------------------------------------------------===//
81 // Builtin Dialect
82 //===----------------------------------------------------------------------===//
83 
84 namespace {
85 /// A builtin dialect to define types/etc that are necessary for the validity of
86 /// the IR.
87 struct BuiltinDialect : public Dialect {
88   BuiltinDialect(MLIRContext *context) : Dialect(/*name=*/"", context) {
89     addAttributes<AffineMapAttr, ArrayAttr, BoolAttr, DenseIntOrFPElementsAttr,
90                   DenseStringElementsAttr, DictionaryAttr, FloatAttr,
91                   SymbolRefAttr, IntegerAttr, IntegerSetAttr, OpaqueAttr,
92                   OpaqueElementsAttr, SparseElementsAttr, StringAttr, TypeAttr,
93                   UnitAttr>();
94     addAttributes<CallSiteLoc, FileLineColLoc, FusedLoc, NameLoc, OpaqueLoc,
95                   UnknownLoc>();
96 
97     addTypes<ComplexType, FloatType, FunctionType, IndexType, IntegerType,
98              MemRefType, UnrankedMemRefType, NoneType, OpaqueType,
99              RankedTensorType, TupleType, UnrankedTensorType, VectorType>();
100 
101     // TODO: These operations should be moved to a different dialect when they
102     // have been fully decoupled from the core.
103     addOperations<FuncOp, ModuleOp, ModuleTerminatorOp>();
104   }
105 };
106 } // end anonymous namespace.
107 
108 //===----------------------------------------------------------------------===//
109 // Locking Utilities
110 //===----------------------------------------------------------------------===//
111 
112 namespace {
113 /// Utility reader lock that takes a runtime flag that specifies if we really
114 /// need to lock.
115 struct ScopedReaderLock {
116   ScopedReaderLock(llvm::sys::SmartRWMutex<true> &mutexParam, bool shouldLock)
117       : mutex(shouldLock ? &mutexParam : nullptr) {
118     if (mutex)
119       mutex->lock_shared();
120   }
121   ~ScopedReaderLock() {
122     if (mutex)
123       mutex->unlock_shared();
124   }
125   llvm::sys::SmartRWMutex<true> *mutex;
126 };
127 /// Utility writer lock that takes a runtime flag that specifies if we really
128 /// need to lock.
129 struct ScopedWriterLock {
130   ScopedWriterLock(llvm::sys::SmartRWMutex<true> &mutexParam, bool shouldLock)
131       : mutex(shouldLock ? &mutexParam : nullptr) {
132     if (mutex)
133       mutex->lock();
134   }
135   ~ScopedWriterLock() {
136     if (mutex)
137       mutex->unlock();
138   }
139   llvm::sys::SmartRWMutex<true> *mutex;
140 };
141 } // end anonymous namespace.
142 
143 //===----------------------------------------------------------------------===//
144 // AffineMap and IntegerSet hashing
145 //===----------------------------------------------------------------------===//
146 
147 /// A utility function to safely get or create a uniqued instance within the
148 /// given set container.
149 template <typename ValueT, typename DenseInfoT, typename KeyT,
150           typename ConstructorFn>
151 static ValueT safeGetOrCreate(DenseSet<ValueT, DenseInfoT> &container,
152                               KeyT &&key, llvm::sys::SmartRWMutex<true> &mutex,
153                               bool threadingIsEnabled,
154                               ConstructorFn &&constructorFn) {
155   // Check for an existing instance in read-only mode.
156   if (threadingIsEnabled) {
157     llvm::sys::SmartScopedReader<true> instanceLock(mutex);
158     auto it = container.find_as(key);
159     if (it != container.end())
160       return *it;
161   }
162 
163   // Acquire a writer-lock so that we can safely create the new instance.
164   ScopedWriterLock instanceLock(mutex, threadingIsEnabled);
165 
166   // Check for an existing instance again here, because another writer thread
167   // may have already created one. Otherwise, construct a new instance.
168   auto existing = container.insert_as(ValueT(), key);
169   if (existing.second)
170     return *existing.first = constructorFn();
171   return *existing.first;
172 }
173 
174 namespace {
175 struct AffineMapKeyInfo : DenseMapInfo<AffineMap> {
176   // Affine maps are uniqued based on their dim/symbol counts and affine
177   // expressions.
178   using KeyTy = std::tuple<unsigned, unsigned, ArrayRef<AffineExpr>>;
179   using DenseMapInfo<AffineMap>::isEqual;
180 
181   static unsigned getHashValue(const AffineMap &key) {
182     return getHashValue(
183         KeyTy(key.getNumDims(), key.getNumSymbols(), key.getResults()));
184   }
185 
186   static unsigned getHashValue(KeyTy key) {
187     return hash_combine(
188         std::get<0>(key), std::get<1>(key),
189         hash_combine_range(std::get<2>(key).begin(), std::get<2>(key).end()));
190   }
191 
192   static bool isEqual(const KeyTy &lhs, AffineMap rhs) {
193     if (rhs == getEmptyKey() || rhs == getTombstoneKey())
194       return false;
195     return lhs == std::make_tuple(rhs.getNumDims(), rhs.getNumSymbols(),
196                                   rhs.getResults());
197   }
198 };
199 
200 struct IntegerSetKeyInfo : DenseMapInfo<IntegerSet> {
201   // Integer sets are uniqued based on their dim/symbol counts, affine
202   // expressions appearing in the LHS of constraints, and eqFlags.
203   using KeyTy =
204       std::tuple<unsigned, unsigned, ArrayRef<AffineExpr>, ArrayRef<bool>>;
205   using DenseMapInfo<IntegerSet>::isEqual;
206 
207   static unsigned getHashValue(const IntegerSet &key) {
208     return getHashValue(KeyTy(key.getNumDims(), key.getNumSymbols(),
209                               key.getConstraints(), key.getEqFlags()));
210   }
211 
212   static unsigned getHashValue(KeyTy key) {
213     return hash_combine(
214         std::get<0>(key), std::get<1>(key),
215         hash_combine_range(std::get<2>(key).begin(), std::get<2>(key).end()),
216         hash_combine_range(std::get<3>(key).begin(), std::get<3>(key).end()));
217   }
218 
219   static bool isEqual(const KeyTy &lhs, IntegerSet rhs) {
220     if (rhs == getEmptyKey() || rhs == getTombstoneKey())
221       return false;
222     return lhs == std::make_tuple(rhs.getNumDims(), rhs.getNumSymbols(),
223                                   rhs.getConstraints(), rhs.getEqFlags());
224   }
225 };
226 } // end anonymous namespace.
227 
228 //===----------------------------------------------------------------------===//
229 // MLIRContextImpl
230 //===----------------------------------------------------------------------===//
231 
232 namespace mlir {
233 /// This is the implementation of the MLIRContext class, using the pImpl idiom.
234 /// This class is completely private to this file, so everything is public.
235 class MLIRContextImpl {
236 public:
237   //===--------------------------------------------------------------------===//
238   // Identifier uniquing
239   //===--------------------------------------------------------------------===//
240 
241   // Identifier allocator and mutex for thread safety.
242   llvm::BumpPtrAllocator identifierAllocator;
243   llvm::sys::SmartRWMutex<true> identifierMutex;
244 
245   //===--------------------------------------------------------------------===//
246   // Diagnostics
247   //===--------------------------------------------------------------------===//
248   DiagnosticEngine diagEngine;
249 
250   //===--------------------------------------------------------------------===//
251   // Options
252   //===--------------------------------------------------------------------===//
253 
254   /// In most cases, creating operation in unregistered dialect is not desired
255   /// and indicate a misconfiguration of the compiler. This option enables to
256   /// detect such use cases
257   bool allowUnregisteredDialects = false;
258 
259   /// Enable support for multi-threading within MLIR.
260   bool threadingIsEnabled = true;
261 
262   /// If the operation should be attached to diagnostics printed via the
263   /// Operation::emit methods.
264   bool printOpOnDiagnostic = true;
265 
266   /// If the current stack trace should be attached when emitting diagnostics.
267   bool printStackTraceOnDiagnostic = false;
268 
269   //===--------------------------------------------------------------------===//
270   // Other
271   //===--------------------------------------------------------------------===//
272 
273   /// A general purpose mutex to lock access to parts of the context that do not
274   /// have a more specific mutex, e.g. registry operations.
275   llvm::sys::SmartRWMutex<true> contextMutex;
276 
277   /// This is a list of dialects that are created referring to this context.
278   /// The MLIRContext owns the objects.
279   std::vector<std::unique_ptr<Dialect>> dialects;
280 
281   /// This is a mapping from operation name to AbstractOperation for registered
282   /// operations.
283   llvm::StringMap<AbstractOperation> registeredOperations;
284 
285   /// This is a mapping from type id to Dialect for registered attributes and
286   /// types.
287   DenseMap<TypeID, Dialect *> registeredDialectSymbols;
288 
289   /// These are identifiers uniqued into this MLIRContext.
290   llvm::StringSet<llvm::BumpPtrAllocator &> identifiers;
291 
292   //===--------------------------------------------------------------------===//
293   // Affine uniquing
294   //===--------------------------------------------------------------------===//
295 
296   // Affine allocator and mutex for thread safety.
297   llvm::BumpPtrAllocator affineAllocator;
298   llvm::sys::SmartRWMutex<true> affineMutex;
299 
300   // Affine map uniquing.
301   using AffineMapSet = DenseSet<AffineMap, AffineMapKeyInfo>;
302   AffineMapSet affineMaps;
303 
304   // Integer set uniquing.
305   using IntegerSets = DenseSet<IntegerSet, IntegerSetKeyInfo>;
306   IntegerSets integerSets;
307 
308   // Affine expression uniquing.
309   StorageUniquer affineUniquer;
310 
311   //===--------------------------------------------------------------------===//
312   // Type uniquing
313   //===--------------------------------------------------------------------===//
314   StorageUniquer typeUniquer;
315 
316   /// Cached Type Instances.
317   FloatType bf16Ty, f16Ty, f32Ty, f64Ty;
318   IndexType indexTy;
319   IntegerType int1Ty, int8Ty, int16Ty, int32Ty, int64Ty, int128Ty;
320   NoneType noneType;
321 
322   //===--------------------------------------------------------------------===//
323   // Attribute uniquing
324   //===--------------------------------------------------------------------===//
325   StorageUniquer attributeUniquer;
326 
327   /// Cached Attribute Instances.
328   BoolAttr falseAttr, trueAttr;
329   UnitAttr unitAttr;
330   UnknownLoc unknownLocAttr;
331 
332 public:
333   MLIRContextImpl() : identifiers(identifierAllocator) {}
334 };
335 } // end namespace mlir
336 
337 MLIRContext::MLIRContext() : impl(new MLIRContextImpl()) {
338   // Initialize values based on the command line flags if they were provided.
339   if (clOptions.isConstructed()) {
340     disableMultithreading(clOptions->disableThreading);
341     printOpOnDiagnostic(clOptions->printOpOnDiagnostic);
342     printStackTraceOnDiagnostic(clOptions->printStackTraceOnDiagnostic);
343   }
344 
345   // Register dialects with this context.
346   new BuiltinDialect(this);
347   registerAllDialects(this);
348 
349   // Initialize several common attributes and types to avoid the need to lock
350   // the context when accessing them.
351 
352   //// Types.
353   /// Floating-point Types.
354   impl->bf16Ty = TypeUniquer::get<FloatType>(this, StandardTypes::BF16);
355   impl->f16Ty = TypeUniquer::get<FloatType>(this, StandardTypes::F16);
356   impl->f32Ty = TypeUniquer::get<FloatType>(this, StandardTypes::F32);
357   impl->f64Ty = TypeUniquer::get<FloatType>(this, StandardTypes::F64);
358   /// Index Type.
359   impl->indexTy = TypeUniquer::get<IndexType>(this, StandardTypes::Index);
360   /// Integer Types.
361   impl->int1Ty = TypeUniquer::get<IntegerType>(this, StandardTypes::Integer, 1,
362                                                IntegerType::Signless);
363   impl->int8Ty = TypeUniquer::get<IntegerType>(this, StandardTypes::Integer, 8,
364                                                IntegerType::Signless);
365   impl->int16Ty = TypeUniquer::get<IntegerType>(this, StandardTypes::Integer,
366                                                 16, IntegerType::Signless);
367   impl->int32Ty = TypeUniquer::get<IntegerType>(this, StandardTypes::Integer,
368                                                 32, IntegerType::Signless);
369   impl->int64Ty = TypeUniquer::get<IntegerType>(this, StandardTypes::Integer,
370                                                 64, IntegerType::Signless);
371   impl->int128Ty = TypeUniquer::get<IntegerType>(this, StandardTypes::Integer,
372                                                  128, IntegerType::Signless);
373   /// None Type.
374   impl->noneType = TypeUniquer::get<NoneType>(this, StandardTypes::None);
375 
376   //// Attributes.
377   //// Note: These must be registered after the types as they may generate one
378   //// of the above types internally.
379   /// Bool Attributes.
380   // Note: The context is also used within the BoolAttrStorage.
381   impl->falseAttr = AttributeUniquer::get<BoolAttr>(
382       this, StandardAttributes::Bool, this, false);
383   impl->trueAttr = AttributeUniquer::get<BoolAttr>(
384       this, StandardAttributes::Bool, this, true);
385   /// Unit Attribute.
386   impl->unitAttr =
387       AttributeUniquer::get<UnitAttr>(this, StandardAttributes::Unit);
388   /// Unknown Location Attribute.
389   impl->unknownLocAttr = AttributeUniquer::get<UnknownLoc>(
390       this, StandardAttributes::UnknownLocation);
391 }
392 
393 MLIRContext::~MLIRContext() {}
394 
395 /// Copy the specified array of elements into memory managed by the provided
396 /// bump pointer allocator.  This assumes the elements are all PODs.
397 template <typename T>
398 static ArrayRef<T> copyArrayRefInto(llvm::BumpPtrAllocator &allocator,
399                                     ArrayRef<T> elements) {
400   auto result = allocator.Allocate<T>(elements.size());
401   std::uninitialized_copy(elements.begin(), elements.end(), result);
402   return ArrayRef<T>(result, elements.size());
403 }
404 
405 //===----------------------------------------------------------------------===//
406 // Diagnostic Handlers
407 //===----------------------------------------------------------------------===//
408 
409 /// Returns the diagnostic engine for this context.
410 DiagnosticEngine &MLIRContext::getDiagEngine() { return getImpl().diagEngine; }
411 
412 //===----------------------------------------------------------------------===//
413 // Dialect and Operation Registration
414 //===----------------------------------------------------------------------===//
415 
416 /// Return information about all registered IR dialects.
417 std::vector<Dialect *> MLIRContext::getRegisteredDialects() {
418   // Lock access to the context registry.
419   ScopedReaderLock registryLock(impl->contextMutex, impl->threadingIsEnabled);
420   std::vector<Dialect *> result;
421   result.reserve(impl->dialects.size());
422   for (auto &dialect : impl->dialects)
423     result.push_back(dialect.get());
424   return result;
425 }
426 
427 /// Get a registered IR dialect with the given namespace. If none is found,
428 /// then return nullptr.
429 Dialect *MLIRContext::getRegisteredDialect(StringRef name) {
430   // Lock access to the context registry.
431   ScopedReaderLock registryLock(impl->contextMutex, impl->threadingIsEnabled);
432 
433   // Dialects are sorted by name, so we can use binary search for lookup.
434   auto it = llvm::lower_bound(
435       impl->dialects, name,
436       [](const auto &lhs, StringRef rhs) { return lhs->getNamespace() < rhs; });
437   return (it != impl->dialects.end() && (*it)->getNamespace() == name)
438              ? (*it).get()
439              : nullptr;
440 }
441 
442 /// Register this dialect object with the specified context.  The context
443 /// takes ownership of the heap allocated dialect.
444 void Dialect::registerDialect(MLIRContext *context) {
445   auto &impl = context->getImpl();
446   std::unique_ptr<Dialect> dialect(this);
447 
448   // Lock access to the context registry.
449   ScopedWriterLock registryLock(impl.contextMutex, impl.threadingIsEnabled);
450 
451   // Get the correct insertion position sorted by namespace.
452   auto insertPt = llvm::lower_bound(
453       impl.dialects, dialect, [](const auto &lhs, const auto &rhs) {
454         return lhs->getNamespace() < rhs->getNamespace();
455       });
456 
457   // Abort if dialect with namespace has already been registered.
458   if (insertPt != impl.dialects.end() &&
459       (*insertPt)->getNamespace() == getNamespace()) {
460     llvm::report_fatal_error("a dialect with namespace '" + getNamespace() +
461                              "' has already been registered");
462   }
463   impl.dialects.insert(insertPt, std::move(dialect));
464 }
465 
466 bool MLIRContext::allowsUnregisteredDialects() {
467   return impl->allowUnregisteredDialects;
468 }
469 
470 void MLIRContext::allowUnregisteredDialects(bool allowing) {
471   impl->allowUnregisteredDialects = allowing;
472 }
473 
474 /// Return true if multi-threading is disabled by the context.
475 bool MLIRContext::isMultithreadingEnabled() {
476   return impl->threadingIsEnabled && llvm::llvm_is_multithreaded();
477 }
478 
479 /// Set the flag specifying if multi-threading is disabled by the context.
480 void MLIRContext::disableMultithreading(bool disable) {
481   impl->threadingIsEnabled = !disable;
482 
483   // Update the threading mode for each of the uniquers.
484   impl->affineUniquer.disableMultithreading(disable);
485   impl->attributeUniquer.disableMultithreading(disable);
486   impl->typeUniquer.disableMultithreading(disable);
487 }
488 
489 /// Return true if we should attach the operation to diagnostics emitted via
490 /// Operation::emit.
491 bool MLIRContext::shouldPrintOpOnDiagnostic() {
492   return impl->printOpOnDiagnostic;
493 }
494 
495 /// Set the flag specifying if we should attach the operation to diagnostics
496 /// emitted via Operation::emit.
497 void MLIRContext::printOpOnDiagnostic(bool enable) {
498   impl->printOpOnDiagnostic = enable;
499 }
500 
501 /// Return true if we should attach the current stacktrace to diagnostics when
502 /// emitted.
503 bool MLIRContext::shouldPrintStackTraceOnDiagnostic() {
504   return impl->printStackTraceOnDiagnostic;
505 }
506 
507 /// Set the flag specifying if we should attach the current stacktrace when
508 /// emitting diagnostics.
509 void MLIRContext::printStackTraceOnDiagnostic(bool enable) {
510   impl->printStackTraceOnDiagnostic = enable;
511 }
512 
513 /// Return information about all registered operations.  This isn't very
514 /// efficient, typically you should ask the operations about their properties
515 /// directly.
516 std::vector<AbstractOperation *> MLIRContext::getRegisteredOperations() {
517   std::vector<std::pair<StringRef, AbstractOperation *>> opsToSort;
518 
519   { // Lock access to the context registry.
520     ScopedReaderLock registryLock(impl->contextMutex, impl->threadingIsEnabled);
521 
522     // We just have the operations in a non-deterministic hash table order. Dump
523     // into a temporary array, then sort it by operation name to get a stable
524     // ordering.
525     llvm::StringMap<AbstractOperation> &registeredOps =
526         impl->registeredOperations;
527 
528     opsToSort.reserve(registeredOps.size());
529     for (auto &elt : registeredOps)
530       opsToSort.push_back({elt.first(), &elt.second});
531   }
532 
533   llvm::array_pod_sort(opsToSort.begin(), opsToSort.end());
534 
535   std::vector<AbstractOperation *> result;
536   result.reserve(opsToSort.size());
537   for (auto &elt : opsToSort)
538     result.push_back(elt.second);
539   return result;
540 }
541 
542 void Dialect::addOperation(AbstractOperation opInfo) {
543   assert((getNamespace().empty() ||
544           opInfo.name.split('.').first == getNamespace()) &&
545          "op name doesn't start with dialect namespace");
546   assert(&opInfo.dialect == this && "Dialect object mismatch");
547   auto &impl = context->getImpl();
548 
549   // Lock access to the context registry.
550   ScopedWriterLock registryLock(impl.contextMutex, impl.threadingIsEnabled);
551   if (!impl.registeredOperations.insert({opInfo.name, opInfo}).second) {
552     llvm::errs() << "error: operation named '" << opInfo.name
553                  << "' is already registered.\n";
554     abort();
555   }
556 }
557 
558 /// Register a dialect-specific symbol(e.g. type) with the current context.
559 void Dialect::addSymbol(TypeID typeID) {
560   auto &impl = context->getImpl();
561 
562   // Lock access to the context registry.
563   ScopedWriterLock registryLock(impl.contextMutex, impl.threadingIsEnabled);
564   if (!impl.registeredDialectSymbols.insert({typeID, this}).second) {
565     llvm::errs() << "error: dialect symbol already registered.\n";
566     abort();
567   }
568 }
569 
570 /// Look up the specified operation in the operation set and return a pointer
571 /// to it if present.  Otherwise, return a null pointer.
572 const AbstractOperation *AbstractOperation::lookup(StringRef opName,
573                                                    MLIRContext *context) {
574   auto &impl = context->getImpl();
575 
576   // Lock access to the context registry.
577   ScopedReaderLock registryLock(impl.contextMutex, impl.threadingIsEnabled);
578   auto it = impl.registeredOperations.find(opName);
579   if (it != impl.registeredOperations.end())
580     return &it->second;
581   return nullptr;
582 }
583 
584 //===----------------------------------------------------------------------===//
585 // Identifier uniquing
586 //===----------------------------------------------------------------------===//
587 
588 /// Return an identifier for the specified string.
589 Identifier Identifier::get(StringRef str, MLIRContext *context) {
590   auto &impl = context->getImpl();
591 
592   // Check for an existing identifier in read-only mode.
593   if (context->isMultithreadingEnabled()) {
594     llvm::sys::SmartScopedReader<true> contextLock(impl.identifierMutex);
595     auto it = impl.identifiers.find(str);
596     if (it != impl.identifiers.end())
597       return Identifier(&*it);
598   }
599 
600   // Check invariants after seeing if we already have something in the
601   // identifier table - if we already had it in the table, then it already
602   // passed invariant checks.
603   assert(!str.empty() && "Cannot create an empty identifier");
604   assert(str.find('\0') == StringRef::npos &&
605          "Cannot create an identifier with a nul character");
606 
607   // Acquire a writer-lock so that we can safely create the new instance.
608   ScopedWriterLock contextLock(impl.identifierMutex, impl.threadingIsEnabled);
609   auto it = impl.identifiers.insert(str).first;
610   return Identifier(&*it);
611 }
612 
613 //===----------------------------------------------------------------------===//
614 // Type uniquing
615 //===----------------------------------------------------------------------===//
616 
617 static Dialect &lookupDialectForSymbol(MLIRContext *ctx, TypeID typeID) {
618   auto &impl = ctx->getImpl();
619   auto it = impl.registeredDialectSymbols.find(typeID);
620   assert(it != impl.registeredDialectSymbols.end() &&
621          "symbol is not registered.");
622   return *it->second;
623 }
624 
625 /// Returns the storage uniquer used for constructing type storage instances.
626 /// This should not be used directly.
627 StorageUniquer &MLIRContext::getTypeUniquer() { return getImpl().typeUniquer; }
628 
629 /// Get the dialect that registered the type with the provided typeid.
630 Dialect &TypeUniquer::lookupDialectForType(MLIRContext *ctx, TypeID typeID) {
631   return lookupDialectForSymbol(ctx, typeID);
632 }
633 
634 FloatType FloatType::get(StandardTypes::Kind kind, MLIRContext *context) {
635   assert(kindof(kind) && "Not a FP kind.");
636   switch (kind) {
637   case StandardTypes::BF16:
638     return context->getImpl().bf16Ty;
639   case StandardTypes::F16:
640     return context->getImpl().f16Ty;
641   case StandardTypes::F32:
642     return context->getImpl().f32Ty;
643   case StandardTypes::F64:
644     return context->getImpl().f64Ty;
645   default:
646     llvm_unreachable("unexpected floating-point kind");
647   }
648 }
649 
650 /// Get an instance of the IndexType.
651 IndexType IndexType::get(MLIRContext *context) {
652   return context->getImpl().indexTy;
653 }
654 
655 /// Return an existing integer type instance if one is cached within the
656 /// context.
657 static IntegerType
658 getCachedIntegerType(unsigned width,
659                      IntegerType::SignednessSemantics signedness,
660                      MLIRContext *context) {
661   if (signedness != IntegerType::Signless)
662     return IntegerType();
663 
664   switch (width) {
665   case 1:
666     return context->getImpl().int1Ty;
667   case 8:
668     return context->getImpl().int8Ty;
669   case 16:
670     return context->getImpl().int16Ty;
671   case 32:
672     return context->getImpl().int32Ty;
673   case 64:
674     return context->getImpl().int64Ty;
675   case 128:
676     return context->getImpl().int128Ty;
677   default:
678     return IntegerType();
679   }
680 }
681 
682 IntegerType IntegerType::get(unsigned width, MLIRContext *context) {
683   return get(width, IntegerType::Signless, context);
684 }
685 
686 IntegerType IntegerType::get(unsigned width,
687                              IntegerType::SignednessSemantics signedness,
688                              MLIRContext *context) {
689   if (auto cached = getCachedIntegerType(width, signedness, context))
690     return cached;
691   return Base::get(context, StandardTypes::Integer, width, signedness);
692 }
693 
694 IntegerType IntegerType::getChecked(unsigned width, Location location) {
695   return getChecked(width, IntegerType::Signless, location);
696 }
697 
698 IntegerType IntegerType::getChecked(unsigned width,
699                                     SignednessSemantics signedness,
700                                     Location location) {
701   if (auto cached =
702           getCachedIntegerType(width, signedness, location->getContext()))
703     return cached;
704   return Base::getChecked(location, StandardTypes::Integer, width, signedness);
705 }
706 
707 /// Get an instance of the NoneType.
708 NoneType NoneType::get(MLIRContext *context) {
709   return context->getImpl().noneType;
710 }
711 
712 //===----------------------------------------------------------------------===//
713 // Attribute uniquing
714 //===----------------------------------------------------------------------===//
715 
716 /// Returns the storage uniquer used for constructing attribute storage
717 /// instances. This should not be used directly.
718 StorageUniquer &MLIRContext::getAttributeUniquer() {
719   return getImpl().attributeUniquer;
720 }
721 
722 /// Initialize the given attribute storage instance.
723 void AttributeUniquer::initializeAttributeStorage(AttributeStorage *storage,
724                                                   MLIRContext *ctx,
725                                                   TypeID attrID) {
726   storage->initializeDialect(lookupDialectForSymbol(ctx, attrID));
727 
728   // If the attribute did not provide a type, then default to NoneType.
729   if (!storage->getType())
730     storage->setType(NoneType::get(ctx));
731 }
732 
733 BoolAttr BoolAttr::get(bool value, MLIRContext *context) {
734   return value ? context->getImpl().trueAttr : context->getImpl().falseAttr;
735 }
736 
737 UnitAttr UnitAttr::get(MLIRContext *context) {
738   return context->getImpl().unitAttr;
739 }
740 
741 Location UnknownLoc::get(MLIRContext *context) {
742   return context->getImpl().unknownLocAttr;
743 }
744 
745 //===----------------------------------------------------------------------===//
746 // AffineMap uniquing
747 //===----------------------------------------------------------------------===//
748 
749 StorageUniquer &MLIRContext::getAffineUniquer() {
750   return getImpl().affineUniquer;
751 }
752 
753 AffineMap AffineMap::getImpl(unsigned dimCount, unsigned symbolCount,
754                              ArrayRef<AffineExpr> results,
755                              MLIRContext *context) {
756   auto &impl = context->getImpl();
757   auto key = std::make_tuple(dimCount, symbolCount, results);
758 
759   // Safely get or create an AffineMap instance.
760   return safeGetOrCreate(
761       impl.affineMaps, key, impl.affineMutex, impl.threadingIsEnabled, [&] {
762         auto *res = impl.affineAllocator.Allocate<detail::AffineMapStorage>();
763 
764         // Copy the results into the bump pointer.
765         results = copyArrayRefInto(impl.affineAllocator, results);
766 
767         // Initialize the memory using placement new.
768         new (res)
769             detail::AffineMapStorage{dimCount, symbolCount, results, context};
770         return AffineMap(res);
771       });
772 }
773 
774 AffineMap AffineMap::get(MLIRContext *context) {
775   return getImpl(/*dimCount=*/0, /*symbolCount=*/0, /*results=*/{}, context);
776 }
777 
778 AffineMap AffineMap::get(unsigned dimCount, unsigned symbolCount,
779                          MLIRContext *context) {
780   return getImpl(dimCount, symbolCount, /*results=*/{}, context);
781 }
782 
783 AffineMap AffineMap::get(unsigned dimCount, unsigned symbolCount,
784                          AffineExpr result) {
785   return getImpl(dimCount, symbolCount, {result}, result.getContext());
786 }
787 
788 AffineMap AffineMap::get(unsigned dimCount, unsigned symbolCount,
789                          ArrayRef<AffineExpr> results, MLIRContext *context) {
790   return getImpl(dimCount, symbolCount, results, context);
791 }
792 
793 //===----------------------------------------------------------------------===//
794 // Integer Sets: these are allocated into the bump pointer, and are immutable.
795 // Unlike AffineMap's, these are uniqued only if they are small.
796 //===----------------------------------------------------------------------===//
797 
798 IntegerSet IntegerSet::get(unsigned dimCount, unsigned symbolCount,
799                            ArrayRef<AffineExpr> constraints,
800                            ArrayRef<bool> eqFlags) {
801   // The number of constraints can't be zero.
802   assert(!constraints.empty());
803   assert(constraints.size() == eqFlags.size());
804 
805   auto &impl = constraints[0].getContext()->getImpl();
806 
807   // A utility function to construct a new IntegerSetStorage instance.
808   auto constructorFn = [&] {
809     auto *res = impl.affineAllocator.Allocate<detail::IntegerSetStorage>();
810 
811     // Copy the results and equality flags into the bump pointer.
812     constraints = copyArrayRefInto(impl.affineAllocator, constraints);
813     eqFlags = copyArrayRefInto(impl.affineAllocator, eqFlags);
814 
815     // Initialize the memory using placement new.
816     new (res)
817         detail::IntegerSetStorage{dimCount, symbolCount, constraints, eqFlags};
818     return IntegerSet(res);
819   };
820 
821   // If this instance is uniqued, then we handle it separately so that multiple
822   // threads may simultaneously access existing instances.
823   if (constraints.size() < IntegerSet::kUniquingThreshold) {
824     auto key = std::make_tuple(dimCount, symbolCount, constraints, eqFlags);
825     return safeGetOrCreate(impl.integerSets, key, impl.affineMutex,
826                            impl.threadingIsEnabled, constructorFn);
827   }
828 
829   // Otherwise, acquire a writer-lock so that we can safely create the new
830   // instance.
831   ScopedWriterLock affineLock(impl.affineMutex, impl.threadingIsEnabled);
832   return constructorFn();
833 }
834 
835 //===----------------------------------------------------------------------===//
836 // StorageUniquerSupport
837 //===----------------------------------------------------------------------===//
838 
839 /// Utility method to generate a default location for use when checking the
840 /// construction invariants of a storage object. This is defined out-of-line to
841 /// avoid the need to include Location.h.
842 const AttributeStorage *
843 mlir::detail::generateUnknownStorageLocation(MLIRContext *ctx) {
844   return reinterpret_cast<const AttributeStorage *>(
845       ctx->getImpl().unknownLocAttr.getAsOpaquePointer());
846 }
847