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