1 //===- ModuleTranslation.cpp - MLIR to LLVM conversion --------------------===// 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 // This file implements the translation between an MLIR LLVM dialect module and 10 // the corresponding LLVMIR module. It only handles core LLVM IR operations. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "mlir/Target/LLVMIR/ModuleTranslation.h" 15 16 #include "AttrKindDetail.h" 17 #include "DebugTranslation.h" 18 #include "LoopAnnotationTranslation.h" 19 #include "mlir/Analysis/TopologicalSortUtils.h" 20 #include "mlir/Dialect/DLTI/DLTI.h" 21 #include "mlir/Dialect/LLVMIR/LLVMDialect.h" 22 #include "mlir/Dialect/LLVMIR/LLVMInterfaces.h" 23 #include "mlir/Dialect/LLVMIR/Transforms/DIExpressionLegalization.h" 24 #include "mlir/Dialect/LLVMIR/Transforms/LegalizeForExport.h" 25 #include "mlir/Dialect/OpenMP/OpenMPDialect.h" 26 #include "mlir/Dialect/OpenMP/OpenMPInterfaces.h" 27 #include "mlir/IR/AttrTypeSubElements.h" 28 #include "mlir/IR/Attributes.h" 29 #include "mlir/IR/BuiltinOps.h" 30 #include "mlir/IR/BuiltinTypes.h" 31 #include "mlir/IR/DialectResourceBlobManager.h" 32 #include "mlir/IR/RegionGraphTraits.h" 33 #include "mlir/Support/LLVM.h" 34 #include "mlir/Target/LLVMIR/LLVMTranslationInterface.h" 35 #include "mlir/Target/LLVMIR/TypeToLLVM.h" 36 37 #include "llvm/ADT/PostOrderIterator.h" 38 #include "llvm/ADT/SetVector.h" 39 #include "llvm/ADT/StringExtras.h" 40 #include "llvm/ADT/TypeSwitch.h" 41 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h" 42 #include "llvm/IR/BasicBlock.h" 43 #include "llvm/IR/CFG.h" 44 #include "llvm/IR/Constants.h" 45 #include "llvm/IR/DerivedTypes.h" 46 #include "llvm/IR/IRBuilder.h" 47 #include "llvm/IR/InlineAsm.h" 48 #include "llvm/IR/IntrinsicsNVPTX.h" 49 #include "llvm/IR/LLVMContext.h" 50 #include "llvm/IR/MDBuilder.h" 51 #include "llvm/IR/Module.h" 52 #include "llvm/IR/Verifier.h" 53 #include "llvm/Support/Debug.h" 54 #include "llvm/Support/raw_ostream.h" 55 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 56 #include "llvm/Transforms/Utils/Cloning.h" 57 #include "llvm/Transforms/Utils/ModuleUtils.h" 58 #include <optional> 59 60 #define DEBUG_TYPE "llvm-dialect-to-llvm-ir" 61 62 using namespace mlir; 63 using namespace mlir::LLVM; 64 using namespace mlir::LLVM::detail; 65 66 extern llvm::cl::opt<bool> UseNewDbgInfoFormat; 67 68 #include "mlir/Dialect/LLVMIR/LLVMConversionEnumsToLLVM.inc" 69 70 namespace { 71 /// A customized inserter for LLVM's IRBuilder that captures all LLVM IR 72 /// instructions that are created for future reference. 73 /// 74 /// This is intended to be used with the `CollectionScope` RAII object: 75 /// 76 /// llvm::IRBuilder<..., InstructionCapturingInserter> builder; 77 /// { 78 /// InstructionCapturingInserter::CollectionScope scope(builder); 79 /// // Call IRBuilder methods as usual. 80 /// 81 /// // This will return a list of all instructions created by the builder, 82 /// // in order of creation. 83 /// builder.getInserter().getCapturedInstructions(); 84 /// } 85 /// // This will return an empty list. 86 /// builder.getInserter().getCapturedInstructions(); 87 /// 88 /// The capturing functionality is _disabled_ by default for performance 89 /// consideration. It needs to be explicitly enabled, which is achieved by 90 /// creating a `CollectionScope`. 91 class InstructionCapturingInserter : public llvm::IRBuilderCallbackInserter { 92 public: 93 /// Constructs the inserter. 94 InstructionCapturingInserter() 95 : llvm::IRBuilderCallbackInserter([this](llvm::Instruction *instruction) { 96 if (LLVM_LIKELY(enabled)) 97 capturedInstructions.push_back(instruction); 98 }) {} 99 100 /// Returns the list of LLVM IR instructions captured since the last cleanup. 101 ArrayRef<llvm::Instruction *> getCapturedInstructions() const { 102 return capturedInstructions; 103 } 104 105 /// Clears the list of captured LLVM IR instructions. 106 void clearCapturedInstructions() { capturedInstructions.clear(); } 107 108 /// RAII object enabling the capture of created LLVM IR instructions. 109 class CollectionScope { 110 public: 111 /// Creates the scope for the given inserter. 112 CollectionScope(llvm::IRBuilderBase &irBuilder, bool isBuilderCapturing); 113 114 /// Ends the scope. 115 ~CollectionScope(); 116 117 ArrayRef<llvm::Instruction *> getCapturedInstructions() { 118 if (!inserter) 119 return {}; 120 return inserter->getCapturedInstructions(); 121 } 122 123 private: 124 /// Back reference to the inserter. 125 InstructionCapturingInserter *inserter = nullptr; 126 127 /// List of instructions in the inserter prior to this scope. 128 SmallVector<llvm::Instruction *> previouslyCollectedInstructions; 129 130 /// Whether the inserter was enabled prior to this scope. 131 bool wasEnabled; 132 }; 133 134 /// Enable or disable the capturing mechanism. 135 void setEnabled(bool enabled = true) { this->enabled = enabled; } 136 137 private: 138 /// List of captured instructions. 139 SmallVector<llvm::Instruction *> capturedInstructions; 140 141 /// Whether the collection is enabled. 142 bool enabled = false; 143 }; 144 145 using CapturingIRBuilder = 146 llvm::IRBuilder<llvm::ConstantFolder, InstructionCapturingInserter>; 147 } // namespace 148 149 InstructionCapturingInserter::CollectionScope::CollectionScope( 150 llvm::IRBuilderBase &irBuilder, bool isBuilderCapturing) { 151 152 if (!isBuilderCapturing) 153 return; 154 155 auto &capturingIRBuilder = static_cast<CapturingIRBuilder &>(irBuilder); 156 inserter = &capturingIRBuilder.getInserter(); 157 wasEnabled = inserter->enabled; 158 if (wasEnabled) 159 previouslyCollectedInstructions.swap(inserter->capturedInstructions); 160 inserter->setEnabled(true); 161 } 162 163 InstructionCapturingInserter::CollectionScope::~CollectionScope() { 164 if (!inserter) 165 return; 166 167 previouslyCollectedInstructions.swap(inserter->capturedInstructions); 168 // If collection was enabled (likely in another, surrounding scope), keep 169 // the instructions collected in this scope. 170 if (wasEnabled) { 171 llvm::append_range(inserter->capturedInstructions, 172 previouslyCollectedInstructions); 173 } 174 inserter->setEnabled(wasEnabled); 175 } 176 177 /// Translates the given data layout spec attribute to the LLVM IR data layout. 178 /// Only integer, float, pointer and endianness entries are currently supported. 179 static FailureOr<llvm::DataLayout> 180 translateDataLayout(DataLayoutSpecInterface attribute, 181 const DataLayout &dataLayout, 182 std::optional<Location> loc = std::nullopt) { 183 if (!loc) 184 loc = UnknownLoc::get(attribute.getContext()); 185 186 // Translate the endianness attribute. 187 std::string llvmDataLayout; 188 llvm::raw_string_ostream layoutStream(llvmDataLayout); 189 for (DataLayoutEntryInterface entry : attribute.getEntries()) { 190 auto key = llvm::dyn_cast_if_present<StringAttr>(entry.getKey()); 191 if (!key) 192 continue; 193 if (key.getValue() == DLTIDialect::kDataLayoutEndiannessKey) { 194 auto value = cast<StringAttr>(entry.getValue()); 195 bool isLittleEndian = 196 value.getValue() == DLTIDialect::kDataLayoutEndiannessLittle; 197 layoutStream << "-" << (isLittleEndian ? "e" : "E"); 198 continue; 199 } 200 if (key.getValue() == DLTIDialect::kDataLayoutProgramMemorySpaceKey) { 201 auto value = cast<IntegerAttr>(entry.getValue()); 202 uint64_t space = value.getValue().getZExtValue(); 203 // Skip the default address space. 204 if (space == 0) 205 continue; 206 layoutStream << "-P" << space; 207 continue; 208 } 209 if (key.getValue() == DLTIDialect::kDataLayoutGlobalMemorySpaceKey) { 210 auto value = cast<IntegerAttr>(entry.getValue()); 211 uint64_t space = value.getValue().getZExtValue(); 212 // Skip the default address space. 213 if (space == 0) 214 continue; 215 layoutStream << "-G" << space; 216 continue; 217 } 218 if (key.getValue() == DLTIDialect::kDataLayoutAllocaMemorySpaceKey) { 219 auto value = cast<IntegerAttr>(entry.getValue()); 220 uint64_t space = value.getValue().getZExtValue(); 221 // Skip the default address space. 222 if (space == 0) 223 continue; 224 layoutStream << "-A" << space; 225 continue; 226 } 227 if (key.getValue() == DLTIDialect::kDataLayoutStackAlignmentKey) { 228 auto value = cast<IntegerAttr>(entry.getValue()); 229 uint64_t alignment = value.getValue().getZExtValue(); 230 // Skip the default stack alignment. 231 if (alignment == 0) 232 continue; 233 layoutStream << "-S" << alignment; 234 continue; 235 } 236 emitError(*loc) << "unsupported data layout key " << key; 237 return failure(); 238 } 239 240 // Go through the list of entries to check which types are explicitly 241 // specified in entries. Where possible, data layout queries are used instead 242 // of directly inspecting the entries. 243 for (DataLayoutEntryInterface entry : attribute.getEntries()) { 244 auto type = llvm::dyn_cast_if_present<Type>(entry.getKey()); 245 if (!type) 246 continue; 247 // Data layout for the index type is irrelevant at this point. 248 if (isa<IndexType>(type)) 249 continue; 250 layoutStream << "-"; 251 LogicalResult result = 252 llvm::TypeSwitch<Type, LogicalResult>(type) 253 .Case<IntegerType, Float16Type, Float32Type, Float64Type, 254 Float80Type, Float128Type>([&](Type type) -> LogicalResult { 255 if (auto intType = dyn_cast<IntegerType>(type)) { 256 if (intType.getSignedness() != IntegerType::Signless) 257 return emitError(*loc) 258 << "unsupported data layout for non-signless integer " 259 << intType; 260 layoutStream << "i"; 261 } else { 262 layoutStream << "f"; 263 } 264 uint64_t size = dataLayout.getTypeSizeInBits(type); 265 uint64_t abi = dataLayout.getTypeABIAlignment(type) * 8u; 266 uint64_t preferred = 267 dataLayout.getTypePreferredAlignment(type) * 8u; 268 layoutStream << size << ":" << abi; 269 if (abi != preferred) 270 layoutStream << ":" << preferred; 271 return success(); 272 }) 273 .Case([&](LLVMPointerType type) { 274 layoutStream << "p" << type.getAddressSpace() << ":"; 275 uint64_t size = dataLayout.getTypeSizeInBits(type); 276 uint64_t abi = dataLayout.getTypeABIAlignment(type) * 8u; 277 uint64_t preferred = 278 dataLayout.getTypePreferredAlignment(type) * 8u; 279 uint64_t index = *dataLayout.getTypeIndexBitwidth(type); 280 layoutStream << size << ":" << abi << ":" << preferred << ":" 281 << index; 282 return success(); 283 }) 284 .Default([loc](Type type) { 285 return emitError(*loc) 286 << "unsupported type in data layout: " << type; 287 }); 288 if (failed(result)) 289 return failure(); 290 } 291 StringRef layoutSpec(llvmDataLayout); 292 if (layoutSpec.starts_with("-")) 293 layoutSpec = layoutSpec.drop_front(); 294 295 return llvm::DataLayout(layoutSpec); 296 } 297 298 /// Builds a constant of a sequential LLVM type `type`, potentially containing 299 /// other sequential types recursively, from the individual constant values 300 /// provided in `constants`. `shape` contains the number of elements in nested 301 /// sequential types. Reports errors at `loc` and returns nullptr on error. 302 static llvm::Constant * 303 buildSequentialConstant(ArrayRef<llvm::Constant *> &constants, 304 ArrayRef<int64_t> shape, llvm::Type *type, 305 Location loc) { 306 if (shape.empty()) { 307 llvm::Constant *result = constants.front(); 308 constants = constants.drop_front(); 309 return result; 310 } 311 312 llvm::Type *elementType; 313 if (auto *arrayTy = dyn_cast<llvm::ArrayType>(type)) { 314 elementType = arrayTy->getElementType(); 315 } else if (auto *vectorTy = dyn_cast<llvm::VectorType>(type)) { 316 elementType = vectorTy->getElementType(); 317 } else { 318 emitError(loc) << "expected sequential LLVM types wrapping a scalar"; 319 return nullptr; 320 } 321 322 SmallVector<llvm::Constant *, 8> nested; 323 nested.reserve(shape.front()); 324 for (int64_t i = 0; i < shape.front(); ++i) { 325 nested.push_back(buildSequentialConstant(constants, shape.drop_front(), 326 elementType, loc)); 327 if (!nested.back()) 328 return nullptr; 329 } 330 331 if (shape.size() == 1 && type->isVectorTy()) 332 return llvm::ConstantVector::get(nested); 333 return llvm::ConstantArray::get( 334 llvm::ArrayType::get(elementType, shape.front()), nested); 335 } 336 337 /// Returns the first non-sequential type nested in sequential types. 338 static llvm::Type *getInnermostElementType(llvm::Type *type) { 339 do { 340 if (auto *arrayTy = dyn_cast<llvm::ArrayType>(type)) { 341 type = arrayTy->getElementType(); 342 } else if (auto *vectorTy = dyn_cast<llvm::VectorType>(type)) { 343 type = vectorTy->getElementType(); 344 } else { 345 return type; 346 } 347 } while (true); 348 } 349 350 /// Convert a dense elements attribute to an LLVM IR constant using its raw data 351 /// storage if possible. This supports elements attributes of tensor or vector 352 /// type and avoids constructing separate objects for individual values of the 353 /// innermost dimension. Constants for other dimensions are still constructed 354 /// recursively. Returns null if constructing from raw data is not supported for 355 /// this type, e.g., element type is not a power-of-two-sized primitive. Reports 356 /// other errors at `loc`. 357 static llvm::Constant * 358 convertDenseElementsAttr(Location loc, DenseElementsAttr denseElementsAttr, 359 llvm::Type *llvmType, 360 const ModuleTranslation &moduleTranslation) { 361 if (!denseElementsAttr) 362 return nullptr; 363 364 llvm::Type *innermostLLVMType = getInnermostElementType(llvmType); 365 if (!llvm::ConstantDataSequential::isElementTypeCompatible(innermostLLVMType)) 366 return nullptr; 367 368 ShapedType type = denseElementsAttr.getType(); 369 if (type.getNumElements() == 0) 370 return nullptr; 371 372 // Check that the raw data size matches what is expected for the scalar size. 373 // TODO: in theory, we could repack the data here to keep constructing from 374 // raw data. 375 // TODO: we may also need to consider endianness when cross-compiling to an 376 // architecture where it is different. 377 int64_t elementByteSize = denseElementsAttr.getRawData().size() / 378 denseElementsAttr.getNumElements(); 379 if (8 * elementByteSize != innermostLLVMType->getScalarSizeInBits()) 380 return nullptr; 381 382 // Compute the shape of all dimensions but the innermost. Note that the 383 // innermost dimension may be that of the vector element type. 384 bool hasVectorElementType = isa<VectorType>(type.getElementType()); 385 int64_t numAggregates = 386 denseElementsAttr.getNumElements() / 387 (hasVectorElementType ? 1 388 : denseElementsAttr.getType().getShape().back()); 389 ArrayRef<int64_t> outerShape = type.getShape(); 390 if (!hasVectorElementType) 391 outerShape = outerShape.drop_back(); 392 393 // Handle the case of vector splat, LLVM has special support for it. 394 if (denseElementsAttr.isSplat() && 395 (isa<VectorType>(type) || hasVectorElementType)) { 396 llvm::Constant *splatValue = LLVM::detail::getLLVMConstant( 397 innermostLLVMType, denseElementsAttr.getSplatValue<Attribute>(), loc, 398 moduleTranslation); 399 llvm::Constant *splatVector = 400 llvm::ConstantDataVector::getSplat(0, splatValue); 401 SmallVector<llvm::Constant *> constants(numAggregates, splatVector); 402 ArrayRef<llvm::Constant *> constantsRef = constants; 403 return buildSequentialConstant(constantsRef, outerShape, llvmType, loc); 404 } 405 if (denseElementsAttr.isSplat()) 406 return nullptr; 407 408 // In case of non-splat, create a constructor for the innermost constant from 409 // a piece of raw data. 410 std::function<llvm::Constant *(StringRef)> buildCstData; 411 if (isa<TensorType>(type)) { 412 auto vectorElementType = dyn_cast<VectorType>(type.getElementType()); 413 if (vectorElementType && vectorElementType.getRank() == 1) { 414 buildCstData = [&](StringRef data) { 415 return llvm::ConstantDataVector::getRaw( 416 data, vectorElementType.getShape().back(), innermostLLVMType); 417 }; 418 } else if (!vectorElementType) { 419 buildCstData = [&](StringRef data) { 420 return llvm::ConstantDataArray::getRaw(data, type.getShape().back(), 421 innermostLLVMType); 422 }; 423 } 424 } else if (isa<VectorType>(type)) { 425 buildCstData = [&](StringRef data) { 426 return llvm::ConstantDataVector::getRaw(data, type.getShape().back(), 427 innermostLLVMType); 428 }; 429 } 430 if (!buildCstData) 431 return nullptr; 432 433 // Create innermost constants and defer to the default constant creation 434 // mechanism for other dimensions. 435 SmallVector<llvm::Constant *> constants; 436 int64_t aggregateSize = denseElementsAttr.getType().getShape().back() * 437 (innermostLLVMType->getScalarSizeInBits() / 8); 438 constants.reserve(numAggregates); 439 for (unsigned i = 0; i < numAggregates; ++i) { 440 StringRef data(denseElementsAttr.getRawData().data() + i * aggregateSize, 441 aggregateSize); 442 constants.push_back(buildCstData(data)); 443 } 444 445 ArrayRef<llvm::Constant *> constantsRef = constants; 446 return buildSequentialConstant(constantsRef, outerShape, llvmType, loc); 447 } 448 449 /// Convert a dense resource elements attribute to an LLVM IR constant using its 450 /// raw data storage if possible. This supports elements attributes of tensor or 451 /// vector type and avoids constructing separate objects for individual values 452 /// of the innermost dimension. Constants for other dimensions are still 453 /// constructed recursively. Returns nullptr on failure and emits errors at 454 /// `loc`. 455 static llvm::Constant *convertDenseResourceElementsAttr( 456 Location loc, DenseResourceElementsAttr denseResourceAttr, 457 llvm::Type *llvmType, const ModuleTranslation &moduleTranslation) { 458 assert(denseResourceAttr && "expected non-null attribute"); 459 460 llvm::Type *innermostLLVMType = getInnermostElementType(llvmType); 461 if (!llvm::ConstantDataSequential::isElementTypeCompatible( 462 innermostLLVMType)) { 463 emitError(loc, "no known conversion for innermost element type"); 464 return nullptr; 465 } 466 467 ShapedType type = denseResourceAttr.getType(); 468 assert(type.getNumElements() > 0 && "Expected non-empty elements attribute"); 469 470 AsmResourceBlob *blob = denseResourceAttr.getRawHandle().getBlob(); 471 if (!blob) { 472 emitError(loc, "resource does not exist"); 473 return nullptr; 474 } 475 476 ArrayRef<char> rawData = blob->getData(); 477 478 // Check that the raw data size matches what is expected for the scalar size. 479 // TODO: in theory, we could repack the data here to keep constructing from 480 // raw data. 481 // TODO: we may also need to consider endianness when cross-compiling to an 482 // architecture where it is different. 483 int64_t numElements = denseResourceAttr.getType().getNumElements(); 484 int64_t elementByteSize = rawData.size() / numElements; 485 if (8 * elementByteSize != innermostLLVMType->getScalarSizeInBits()) { 486 emitError(loc, "raw data size does not match element type size"); 487 return nullptr; 488 } 489 490 // Compute the shape of all dimensions but the innermost. Note that the 491 // innermost dimension may be that of the vector element type. 492 bool hasVectorElementType = isa<VectorType>(type.getElementType()); 493 int64_t numAggregates = 494 numElements / (hasVectorElementType 495 ? 1 496 : denseResourceAttr.getType().getShape().back()); 497 ArrayRef<int64_t> outerShape = type.getShape(); 498 if (!hasVectorElementType) 499 outerShape = outerShape.drop_back(); 500 501 // Create a constructor for the innermost constant from a piece of raw data. 502 std::function<llvm::Constant *(StringRef)> buildCstData; 503 if (isa<TensorType>(type)) { 504 auto vectorElementType = dyn_cast<VectorType>(type.getElementType()); 505 if (vectorElementType && vectorElementType.getRank() == 1) { 506 buildCstData = [&](StringRef data) { 507 return llvm::ConstantDataVector::getRaw( 508 data, vectorElementType.getShape().back(), innermostLLVMType); 509 }; 510 } else if (!vectorElementType) { 511 buildCstData = [&](StringRef data) { 512 return llvm::ConstantDataArray::getRaw(data, type.getShape().back(), 513 innermostLLVMType); 514 }; 515 } 516 } else if (isa<VectorType>(type)) { 517 buildCstData = [&](StringRef data) { 518 return llvm::ConstantDataVector::getRaw(data, type.getShape().back(), 519 innermostLLVMType); 520 }; 521 } 522 if (!buildCstData) { 523 emitError(loc, "unsupported dense_resource type"); 524 return nullptr; 525 } 526 527 // Create innermost constants and defer to the default constant creation 528 // mechanism for other dimensions. 529 SmallVector<llvm::Constant *> constants; 530 int64_t aggregateSize = denseResourceAttr.getType().getShape().back() * 531 (innermostLLVMType->getScalarSizeInBits() / 8); 532 constants.reserve(numAggregates); 533 for (unsigned i = 0; i < numAggregates; ++i) { 534 StringRef data(rawData.data() + i * aggregateSize, aggregateSize); 535 constants.push_back(buildCstData(data)); 536 } 537 538 ArrayRef<llvm::Constant *> constantsRef = constants; 539 return buildSequentialConstant(constantsRef, outerShape, llvmType, loc); 540 } 541 542 /// Create an LLVM IR constant of `llvmType` from the MLIR attribute `attr`. 543 /// This currently supports integer, floating point, splat and dense element 544 /// attributes and combinations thereof. Also, an array attribute with two 545 /// elements is supported to represent a complex constant. In case of error, 546 /// report it to `loc` and return nullptr. 547 llvm::Constant *mlir::LLVM::detail::getLLVMConstant( 548 llvm::Type *llvmType, Attribute attr, Location loc, 549 const ModuleTranslation &moduleTranslation) { 550 if (!attr) 551 return llvm::UndefValue::get(llvmType); 552 if (auto *structType = dyn_cast<::llvm::StructType>(llvmType)) { 553 auto arrayAttr = dyn_cast<ArrayAttr>(attr); 554 if (!arrayAttr) { 555 emitError(loc, "expected an array attribute for a struct constant"); 556 return nullptr; 557 } 558 SmallVector<llvm::Constant *> structElements; 559 structElements.reserve(structType->getNumElements()); 560 for (auto [elemType, elemAttr] : 561 zip_equal(structType->elements(), arrayAttr)) { 562 llvm::Constant *element = 563 getLLVMConstant(elemType, elemAttr, loc, moduleTranslation); 564 if (!element) 565 return nullptr; 566 structElements.push_back(element); 567 } 568 return llvm::ConstantStruct::get(structType, structElements); 569 } 570 // For integer types, we allow a mismatch in sizes as the index type in 571 // MLIR might have a different size than the index type in the LLVM module. 572 if (auto intAttr = dyn_cast<IntegerAttr>(attr)) 573 return llvm::ConstantInt::get( 574 llvmType, 575 intAttr.getValue().sextOrTrunc(llvmType->getIntegerBitWidth())); 576 if (auto floatAttr = dyn_cast<FloatAttr>(attr)) { 577 const llvm::fltSemantics &sem = floatAttr.getValue().getSemantics(); 578 // Special case for 8-bit floats, which are represented by integers due to 579 // the lack of native fp8 types in LLVM at the moment. Additionally, handle 580 // targets (like AMDGPU) that don't implement bfloat and convert all bfloats 581 // to i16. 582 unsigned floatWidth = APFloat::getSizeInBits(sem); 583 if (llvmType->isIntegerTy(floatWidth)) 584 return llvm::ConstantInt::get(llvmType, 585 floatAttr.getValue().bitcastToAPInt()); 586 if (llvmType != 587 llvm::Type::getFloatingPointTy(llvmType->getContext(), 588 floatAttr.getValue().getSemantics())) { 589 emitError(loc, "FloatAttr does not match expected type of the constant"); 590 return nullptr; 591 } 592 return llvm::ConstantFP::get(llvmType, floatAttr.getValue()); 593 } 594 if (auto funcAttr = dyn_cast<FlatSymbolRefAttr>(attr)) 595 return llvm::ConstantExpr::getBitCast( 596 moduleTranslation.lookupFunction(funcAttr.getValue()), llvmType); 597 if (auto splatAttr = dyn_cast<SplatElementsAttr>(attr)) { 598 llvm::Type *elementType; 599 uint64_t numElements; 600 bool isScalable = false; 601 if (auto *arrayTy = dyn_cast<llvm::ArrayType>(llvmType)) { 602 elementType = arrayTy->getElementType(); 603 numElements = arrayTy->getNumElements(); 604 } else if (auto *fVectorTy = dyn_cast<llvm::FixedVectorType>(llvmType)) { 605 elementType = fVectorTy->getElementType(); 606 numElements = fVectorTy->getNumElements(); 607 } else if (auto *sVectorTy = dyn_cast<llvm::ScalableVectorType>(llvmType)) { 608 elementType = sVectorTy->getElementType(); 609 numElements = sVectorTy->getMinNumElements(); 610 isScalable = true; 611 } else { 612 llvm_unreachable("unrecognized constant vector type"); 613 } 614 // Splat value is a scalar. Extract it only if the element type is not 615 // another sequence type. The recursion terminates because each step removes 616 // one outer sequential type. 617 bool elementTypeSequential = 618 isa<llvm::ArrayType, llvm::VectorType>(elementType); 619 llvm::Constant *child = getLLVMConstant( 620 elementType, 621 elementTypeSequential ? splatAttr 622 : splatAttr.getSplatValue<Attribute>(), 623 loc, moduleTranslation); 624 if (!child) 625 return nullptr; 626 if (llvmType->isVectorTy()) 627 return llvm::ConstantVector::getSplat( 628 llvm::ElementCount::get(numElements, /*Scalable=*/isScalable), child); 629 if (llvmType->isArrayTy()) { 630 auto *arrayType = llvm::ArrayType::get(elementType, numElements); 631 if (child->isZeroValue()) { 632 return llvm::ConstantAggregateZero::get(arrayType); 633 } else { 634 if (llvm::ConstantDataSequential::isElementTypeCompatible( 635 elementType)) { 636 // TODO: Handle all compatible types. This code only handles integer. 637 if (isa<llvm::IntegerType>(elementType)) { 638 if (llvm::ConstantInt *ci = dyn_cast<llvm::ConstantInt>(child)) { 639 if (ci->getBitWidth() == 8) { 640 SmallVector<int8_t> constants(numElements, ci->getZExtValue()); 641 return llvm::ConstantDataArray::get(elementType->getContext(), 642 constants); 643 } 644 if (ci->getBitWidth() == 16) { 645 SmallVector<int16_t> constants(numElements, ci->getZExtValue()); 646 return llvm::ConstantDataArray::get(elementType->getContext(), 647 constants); 648 } 649 if (ci->getBitWidth() == 32) { 650 SmallVector<int32_t> constants(numElements, ci->getZExtValue()); 651 return llvm::ConstantDataArray::get(elementType->getContext(), 652 constants); 653 } 654 if (ci->getBitWidth() == 64) { 655 SmallVector<int64_t> constants(numElements, ci->getZExtValue()); 656 return llvm::ConstantDataArray::get(elementType->getContext(), 657 constants); 658 } 659 } 660 } 661 } 662 // std::vector is used here to accomodate large number of elements that 663 // exceed SmallVector capacity. 664 std::vector<llvm::Constant *> constants(numElements, child); 665 return llvm::ConstantArray::get(arrayType, constants); 666 } 667 } 668 } 669 670 // Try using raw elements data if possible. 671 if (llvm::Constant *result = 672 convertDenseElementsAttr(loc, dyn_cast<DenseElementsAttr>(attr), 673 llvmType, moduleTranslation)) { 674 return result; 675 } 676 677 if (auto denseResourceAttr = dyn_cast<DenseResourceElementsAttr>(attr)) { 678 return convertDenseResourceElementsAttr(loc, denseResourceAttr, llvmType, 679 moduleTranslation); 680 } 681 682 // Fall back to element-by-element construction otherwise. 683 if (auto elementsAttr = dyn_cast<ElementsAttr>(attr)) { 684 assert(elementsAttr.getShapedType().hasStaticShape()); 685 assert(!elementsAttr.getShapedType().getShape().empty() && 686 "unexpected empty elements attribute shape"); 687 688 SmallVector<llvm::Constant *, 8> constants; 689 constants.reserve(elementsAttr.getNumElements()); 690 llvm::Type *innermostType = getInnermostElementType(llvmType); 691 for (auto n : elementsAttr.getValues<Attribute>()) { 692 constants.push_back( 693 getLLVMConstant(innermostType, n, loc, moduleTranslation)); 694 if (!constants.back()) 695 return nullptr; 696 } 697 ArrayRef<llvm::Constant *> constantsRef = constants; 698 llvm::Constant *result = buildSequentialConstant( 699 constantsRef, elementsAttr.getShapedType().getShape(), llvmType, loc); 700 assert(constantsRef.empty() && "did not consume all elemental constants"); 701 return result; 702 } 703 704 if (auto stringAttr = dyn_cast<StringAttr>(attr)) { 705 return llvm::ConstantDataArray::get( 706 moduleTranslation.getLLVMContext(), 707 ArrayRef<char>{stringAttr.getValue().data(), 708 stringAttr.getValue().size()}); 709 } 710 emitError(loc, "unsupported constant value"); 711 return nullptr; 712 } 713 714 ModuleTranslation::ModuleTranslation(Operation *module, 715 std::unique_ptr<llvm::Module> llvmModule) 716 : mlirModule(module), llvmModule(std::move(llvmModule)), 717 debugTranslation( 718 std::make_unique<DebugTranslation>(module, *this->llvmModule)), 719 loopAnnotationTranslation(std::make_unique<LoopAnnotationTranslation>( 720 *this, *this->llvmModule)), 721 typeTranslator(this->llvmModule->getContext()), 722 iface(module->getContext()) { 723 assert(satisfiesLLVMModule(mlirModule) && 724 "mlirModule should honor LLVM's module semantics."); 725 } 726 727 ModuleTranslation::~ModuleTranslation() { 728 if (ompBuilder) 729 ompBuilder->finalize(); 730 } 731 732 void ModuleTranslation::forgetMapping(Region ®ion) { 733 SmallVector<Region *> toProcess; 734 toProcess.push_back(®ion); 735 while (!toProcess.empty()) { 736 Region *current = toProcess.pop_back_val(); 737 for (Block &block : *current) { 738 blockMapping.erase(&block); 739 for (Value arg : block.getArguments()) 740 valueMapping.erase(arg); 741 for (Operation &op : block) { 742 for (Value value : op.getResults()) 743 valueMapping.erase(value); 744 if (op.hasSuccessors()) 745 branchMapping.erase(&op); 746 if (isa<LLVM::GlobalOp>(op)) 747 globalsMapping.erase(&op); 748 if (isa<LLVM::CallOp>(op)) 749 callMapping.erase(&op); 750 llvm::append_range( 751 toProcess, 752 llvm::map_range(op.getRegions(), [](Region &r) { return &r; })); 753 } 754 } 755 } 756 } 757 758 /// Get the SSA value passed to the current block from the terminator operation 759 /// of its predecessor. 760 static Value getPHISourceValue(Block *current, Block *pred, 761 unsigned numArguments, unsigned index) { 762 Operation &terminator = *pred->getTerminator(); 763 if (isa<LLVM::BrOp>(terminator)) 764 return terminator.getOperand(index); 765 766 #ifndef NDEBUG 767 llvm::SmallPtrSet<Block *, 4> seenSuccessors; 768 for (unsigned i = 0, e = terminator.getNumSuccessors(); i < e; ++i) { 769 Block *successor = terminator.getSuccessor(i); 770 auto branch = cast<BranchOpInterface>(terminator); 771 SuccessorOperands successorOperands = branch.getSuccessorOperands(i); 772 assert( 773 (!seenSuccessors.contains(successor) || successorOperands.empty()) && 774 "successors with arguments in LLVM branches must be different blocks"); 775 seenSuccessors.insert(successor); 776 } 777 #endif 778 779 // For instructions that branch based on a condition value, we need to take 780 // the operands for the branch that was taken. 781 if (auto condBranchOp = dyn_cast<LLVM::CondBrOp>(terminator)) { 782 // For conditional branches, we take the operands from either the "true" or 783 // the "false" branch. 784 return condBranchOp.getSuccessor(0) == current 785 ? condBranchOp.getTrueDestOperands()[index] 786 : condBranchOp.getFalseDestOperands()[index]; 787 } 788 789 if (auto switchOp = dyn_cast<LLVM::SwitchOp>(terminator)) { 790 // For switches, we take the operands from either the default case, or from 791 // the case branch that was taken. 792 if (switchOp.getDefaultDestination() == current) 793 return switchOp.getDefaultOperands()[index]; 794 for (const auto &i : llvm::enumerate(switchOp.getCaseDestinations())) 795 if (i.value() == current) 796 return switchOp.getCaseOperands(i.index())[index]; 797 } 798 799 if (auto invokeOp = dyn_cast<LLVM::InvokeOp>(terminator)) { 800 return invokeOp.getNormalDest() == current 801 ? invokeOp.getNormalDestOperands()[index] 802 : invokeOp.getUnwindDestOperands()[index]; 803 } 804 805 llvm_unreachable( 806 "only branch, switch or invoke operations can be terminators " 807 "of a block that has successors"); 808 } 809 810 /// Connect the PHI nodes to the results of preceding blocks. 811 void mlir::LLVM::detail::connectPHINodes(Region ®ion, 812 const ModuleTranslation &state) { 813 // Skip the first block, it cannot be branched to and its arguments correspond 814 // to the arguments of the LLVM function. 815 for (Block &bb : llvm::drop_begin(region)) { 816 llvm::BasicBlock *llvmBB = state.lookupBlock(&bb); 817 auto phis = llvmBB->phis(); 818 auto numArguments = bb.getNumArguments(); 819 assert(numArguments == std::distance(phis.begin(), phis.end())); 820 for (auto [index, phiNode] : llvm::enumerate(phis)) { 821 for (auto *pred : bb.getPredecessors()) { 822 // Find the LLVM IR block that contains the converted terminator 823 // instruction and use it in the PHI node. Note that this block is not 824 // necessarily the same as state.lookupBlock(pred), some operations 825 // (in particular, OpenMP operations using OpenMPIRBuilder) may have 826 // split the blocks. 827 llvm::Instruction *terminator = 828 state.lookupBranch(pred->getTerminator()); 829 assert(terminator && "missing the mapping for a terminator"); 830 phiNode.addIncoming(state.lookupValue(getPHISourceValue( 831 &bb, pred, numArguments, index)), 832 terminator->getParent()); 833 } 834 } 835 } 836 } 837 838 llvm::CallInst *mlir::LLVM::detail::createIntrinsicCall( 839 llvm::IRBuilderBase &builder, llvm::Intrinsic::ID intrinsic, 840 ArrayRef<llvm::Value *> args, ArrayRef<llvm::Type *> tys) { 841 llvm::Module *module = builder.GetInsertBlock()->getModule(); 842 llvm::Function *fn = llvm::Intrinsic::getDeclaration(module, intrinsic, tys); 843 return builder.CreateCall(fn, args); 844 } 845 846 llvm::CallInst *mlir::LLVM::detail::createIntrinsicCall( 847 llvm::IRBuilderBase &builder, ModuleTranslation &moduleTranslation, 848 Operation *intrOp, llvm::Intrinsic::ID intrinsic, unsigned numResults, 849 ArrayRef<unsigned> overloadedResults, ArrayRef<unsigned> overloadedOperands, 850 ArrayRef<unsigned> immArgPositions, 851 ArrayRef<StringLiteral> immArgAttrNames) { 852 assert(immArgPositions.size() == immArgAttrNames.size() && 853 "LLVM `immArgPositions` and MLIR `immArgAttrNames` should have equal " 854 "length"); 855 856 // Map operands and attributes to LLVM values. 857 auto operands = moduleTranslation.lookupValues(intrOp->getOperands()); 858 SmallVector<llvm::Value *> args(immArgPositions.size() + operands.size()); 859 for (auto [immArgPos, immArgName] : 860 llvm::zip(immArgPositions, immArgAttrNames)) { 861 auto attr = llvm::cast<TypedAttr>(intrOp->getAttr(immArgName)); 862 assert(attr.getType().isIntOrFloat() && "expected int or float immarg"); 863 auto *type = moduleTranslation.convertType(attr.getType()); 864 args[immArgPos] = LLVM::detail::getLLVMConstant( 865 type, attr, intrOp->getLoc(), moduleTranslation); 866 } 867 unsigned opArg = 0; 868 for (auto &arg : args) { 869 if (!arg) 870 arg = operands[opArg++]; 871 } 872 873 // Resolve overloaded intrinsic declaration. 874 SmallVector<llvm::Type *> overloadedTypes; 875 for (unsigned overloadedResultIdx : overloadedResults) { 876 if (numResults > 1) { 877 // More than one result is mapped to an LLVM struct. 878 overloadedTypes.push_back(moduleTranslation.convertType( 879 llvm::cast<LLVM::LLVMStructType>(intrOp->getResult(0).getType()) 880 .getBody()[overloadedResultIdx])); 881 } else { 882 overloadedTypes.push_back( 883 moduleTranslation.convertType(intrOp->getResult(0).getType())); 884 } 885 } 886 for (unsigned overloadedOperandIdx : overloadedOperands) 887 overloadedTypes.push_back(args[overloadedOperandIdx]->getType()); 888 llvm::Module *module = builder.GetInsertBlock()->getModule(); 889 llvm::Function *llvmIntr = 890 llvm::Intrinsic::getDeclaration(module, intrinsic, overloadedTypes); 891 892 return builder.CreateCall(llvmIntr, args); 893 } 894 895 /// Given a single MLIR operation, create the corresponding LLVM IR operation 896 /// using the `builder`. 897 LogicalResult ModuleTranslation::convertOperation(Operation &op, 898 llvm::IRBuilderBase &builder, 899 bool recordInsertions) { 900 const LLVMTranslationDialectInterface *opIface = iface.getInterfaceFor(&op); 901 if (!opIface) 902 return op.emitError("cannot be converted to LLVM IR: missing " 903 "`LLVMTranslationDialectInterface` registration for " 904 "dialect for op: ") 905 << op.getName(); 906 907 InstructionCapturingInserter::CollectionScope scope(builder, 908 recordInsertions); 909 if (failed(opIface->convertOperation(&op, builder, *this))) 910 return op.emitError("LLVM Translation failed for operation: ") 911 << op.getName(); 912 913 return convertDialectAttributes(&op, scope.getCapturedInstructions()); 914 } 915 916 /// Convert block to LLVM IR. Unless `ignoreArguments` is set, emit PHI nodes 917 /// to define values corresponding to the MLIR block arguments. These nodes 918 /// are not connected to the source basic blocks, which may not exist yet. Uses 919 /// `builder` to construct the LLVM IR. Expects the LLVM IR basic block to have 920 /// been created for `bb` and included in the block mapping. Inserts new 921 /// instructions at the end of the block and leaves `builder` in a state 922 /// suitable for further insertion into the end of the block. 923 LogicalResult ModuleTranslation::convertBlockImpl(Block &bb, 924 bool ignoreArguments, 925 llvm::IRBuilderBase &builder, 926 bool recordInsertions) { 927 builder.SetInsertPoint(lookupBlock(&bb)); 928 auto *subprogram = builder.GetInsertBlock()->getParent()->getSubprogram(); 929 930 // Before traversing operations, make block arguments available through 931 // value remapping and PHI nodes, but do not add incoming edges for the PHI 932 // nodes just yet: those values may be defined by this or following blocks. 933 // This step is omitted if "ignoreArguments" is set. The arguments of the 934 // first block have been already made available through the remapping of 935 // LLVM function arguments. 936 if (!ignoreArguments) { 937 auto predecessors = bb.getPredecessors(); 938 unsigned numPredecessors = 939 std::distance(predecessors.begin(), predecessors.end()); 940 for (auto arg : bb.getArguments()) { 941 auto wrappedType = arg.getType(); 942 if (!isCompatibleType(wrappedType)) 943 return emitError(bb.front().getLoc(), 944 "block argument does not have an LLVM type"); 945 builder.SetCurrentDebugLocation( 946 debugTranslation->translateLoc(arg.getLoc(), subprogram)); 947 llvm::Type *type = convertType(wrappedType); 948 llvm::PHINode *phi = builder.CreatePHI(type, numPredecessors); 949 mapValue(arg, phi); 950 } 951 } 952 953 // Traverse operations. 954 for (auto &op : bb) { 955 // Set the current debug location within the builder. 956 builder.SetCurrentDebugLocation( 957 debugTranslation->translateLoc(op.getLoc(), subprogram)); 958 959 if (failed(convertOperation(op, builder, recordInsertions))) 960 return failure(); 961 962 // Set the branch weight metadata on the translated instruction. 963 if (auto iface = dyn_cast<BranchWeightOpInterface>(op)) 964 setBranchWeightsMetadata(iface); 965 } 966 967 return success(); 968 } 969 970 /// A helper method to get the single Block in an operation honoring LLVM's 971 /// module requirements. 972 static Block &getModuleBody(Operation *module) { 973 return module->getRegion(0).front(); 974 } 975 976 /// A helper method to decide if a constant must not be set as a global variable 977 /// initializer. For an external linkage variable, the variable with an 978 /// initializer is considered externally visible and defined in this module, the 979 /// variable without an initializer is externally available and is defined 980 /// elsewhere. 981 static bool shouldDropGlobalInitializer(llvm::GlobalValue::LinkageTypes linkage, 982 llvm::Constant *cst) { 983 return (linkage == llvm::GlobalVariable::ExternalLinkage && !cst) || 984 linkage == llvm::GlobalVariable::ExternalWeakLinkage; 985 } 986 987 /// Sets the runtime preemption specifier of `gv` to dso_local if 988 /// `dsoLocalRequested` is true, otherwise it is left unchanged. 989 static void addRuntimePreemptionSpecifier(bool dsoLocalRequested, 990 llvm::GlobalValue *gv) { 991 if (dsoLocalRequested) 992 gv->setDSOLocal(true); 993 } 994 995 /// Create named global variables that correspond to llvm.mlir.global 996 /// definitions. Convert llvm.global_ctors and global_dtors ops. 997 LogicalResult ModuleTranslation::convertGlobals() { 998 // Mapping from compile unit to its respective set of global variables. 999 DenseMap<llvm::DICompileUnit *, SmallVector<llvm::Metadata *>> allGVars; 1000 1001 for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) { 1002 llvm::Type *type = convertType(op.getType()); 1003 llvm::Constant *cst = nullptr; 1004 if (op.getValueOrNull()) { 1005 // String attributes are treated separately because they cannot appear as 1006 // in-function constants and are thus not supported by getLLVMConstant. 1007 if (auto strAttr = dyn_cast_or_null<StringAttr>(op.getValueOrNull())) { 1008 cst = llvm::ConstantDataArray::getString( 1009 llvmModule->getContext(), strAttr.getValue(), /*AddNull=*/false); 1010 type = cst->getType(); 1011 } else if (!(cst = getLLVMConstant(type, op.getValueOrNull(), op.getLoc(), 1012 *this))) { 1013 return failure(); 1014 } 1015 } 1016 1017 auto linkage = convertLinkageToLLVM(op.getLinkage()); 1018 1019 // LLVM IR requires constant with linkage other than external or weak 1020 // external to have initializers. If MLIR does not provide an initializer, 1021 // default to undef. 1022 bool dropInitializer = shouldDropGlobalInitializer(linkage, cst); 1023 if (!dropInitializer && !cst) 1024 cst = llvm::UndefValue::get(type); 1025 else if (dropInitializer && cst) 1026 cst = nullptr; 1027 1028 auto *var = new llvm::GlobalVariable( 1029 *llvmModule, type, op.getConstant(), linkage, cst, op.getSymName(), 1030 /*InsertBefore=*/nullptr, 1031 op.getThreadLocal_() ? llvm::GlobalValue::GeneralDynamicTLSModel 1032 : llvm::GlobalValue::NotThreadLocal, 1033 op.getAddrSpace(), op.getExternallyInitialized()); 1034 1035 if (std::optional<mlir::SymbolRefAttr> comdat = op.getComdat()) { 1036 auto selectorOp = cast<ComdatSelectorOp>( 1037 SymbolTable::lookupNearestSymbolFrom(op, *comdat)); 1038 var->setComdat(comdatMapping.lookup(selectorOp)); 1039 } 1040 1041 if (op.getUnnamedAddr().has_value()) 1042 var->setUnnamedAddr(convertUnnamedAddrToLLVM(*op.getUnnamedAddr())); 1043 1044 if (op.getSection().has_value()) 1045 var->setSection(*op.getSection()); 1046 1047 addRuntimePreemptionSpecifier(op.getDsoLocal(), var); 1048 1049 std::optional<uint64_t> alignment = op.getAlignment(); 1050 if (alignment.has_value()) 1051 var->setAlignment(llvm::MaybeAlign(alignment.value())); 1052 1053 var->setVisibility(convertVisibilityToLLVM(op.getVisibility_())); 1054 1055 globalsMapping.try_emplace(op, var); 1056 1057 // Add debug information if present. 1058 if (op.getDbgExpr()) { 1059 llvm::DIGlobalVariableExpression *diGlobalExpr = 1060 debugTranslation->translateGlobalVariableExpression(op.getDbgExpr()); 1061 llvm::DIGlobalVariable *diGlobalVar = diGlobalExpr->getVariable(); 1062 var->addDebugInfo(diGlobalExpr); 1063 1064 // There is no `globals` field in DICompileUnitAttr which can be directly 1065 // assigned to DICompileUnit. We have to build the list by looking at the 1066 // dbgExpr of all the GlobalOps. The scope of the variable is used to get 1067 // the DICompileUnit in which to add it. But for the languages that 1068 // support modules, the scope hierarchy can be 1069 // variable -> module -> compile unit 1070 // If a variable scope points to the module then we use the scope of the 1071 // module to get the compile unit. 1072 // Global variables are also used for things like static local variables 1073 // in C and local variables with the save attribute in Fortran. The scope 1074 // of the variable is the parent function. We use the compile unit of the 1075 // parent function in this case. 1076 llvm::DIScope *scope = diGlobalVar->getScope(); 1077 if (auto *mod = dyn_cast_if_present<llvm::DIModule>(scope)) 1078 scope = mod->getScope(); 1079 else if (auto *sp = dyn_cast_if_present<llvm::DISubprogram>(scope)) 1080 scope = sp->getUnit(); 1081 1082 // Get the compile unit (scope) of the the global variable. 1083 if (llvm::DICompileUnit *compileUnit = 1084 dyn_cast_if_present<llvm::DICompileUnit>(scope)) { 1085 // Update the compile unit with this incoming global variable expression 1086 // during the finalizing step later. 1087 allGVars[compileUnit].push_back(diGlobalExpr); 1088 } 1089 } 1090 } 1091 1092 // Convert global variable bodies. This is done after all global variables 1093 // have been created in LLVM IR because a global body may refer to another 1094 // global or itself. So all global variables need to be mapped first. 1095 for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) { 1096 if (Block *initializer = op.getInitializerBlock()) { 1097 llvm::IRBuilder<> builder(llvmModule->getContext()); 1098 1099 [[maybe_unused]] int numConstantsHit = 0; 1100 [[maybe_unused]] int numConstantsErased = 0; 1101 DenseMap<llvm::ConstantAggregate *, int> constantAggregateUseMap; 1102 1103 for (auto &op : initializer->without_terminator()) { 1104 if (failed(convertOperation(op, builder))) 1105 return emitError(op.getLoc(), "fail to convert global initializer"); 1106 auto *cst = dyn_cast<llvm::Constant>(lookupValue(op.getResult(0))); 1107 if (!cst) 1108 return emitError(op.getLoc(), "unemittable constant value"); 1109 1110 // When emitting an LLVM constant, a new constant is created and the old 1111 // constant may become dangling and take space. We should remove the 1112 // dangling constants to avoid memory explosion especially for constant 1113 // arrays whose number of elements is large. 1114 // Because multiple operations may refer to the same constant, we need 1115 // to count the number of uses of each constant array and remove it only 1116 // when the count becomes zero. 1117 if (auto *agg = dyn_cast<llvm::ConstantAggregate>(cst)) { 1118 numConstantsHit++; 1119 Value result = op.getResult(0); 1120 int numUsers = std::distance(result.use_begin(), result.use_end()); 1121 auto [iterator, inserted] = 1122 constantAggregateUseMap.try_emplace(agg, numUsers); 1123 if (!inserted) { 1124 // Key already exists, update the value 1125 iterator->second += numUsers; 1126 } 1127 } 1128 // Scan the operands of the operation to decrement the use count of 1129 // constants. Erase the constant if the use count becomes zero. 1130 for (Value v : op.getOperands()) { 1131 auto cst = dyn_cast<llvm::ConstantAggregate>(lookupValue(v)); 1132 if (!cst) 1133 continue; 1134 auto iter = constantAggregateUseMap.find(cst); 1135 assert(iter != constantAggregateUseMap.end() && "constant not found"); 1136 iter->second--; 1137 if (iter->second == 0) { 1138 // NOTE: cannot call removeDeadConstantUsers() here because it 1139 // may remove the constant which has uses not be converted yet. 1140 if (cst->user_empty()) { 1141 cst->destroyConstant(); 1142 numConstantsErased++; 1143 } 1144 constantAggregateUseMap.erase(iter); 1145 } 1146 } 1147 } 1148 1149 ReturnOp ret = cast<ReturnOp>(initializer->getTerminator()); 1150 llvm::Constant *cst = 1151 cast<llvm::Constant>(lookupValue(ret.getOperand(0))); 1152 auto *global = cast<llvm::GlobalVariable>(lookupGlobal(op)); 1153 if (!shouldDropGlobalInitializer(global->getLinkage(), cst)) 1154 global->setInitializer(cst); 1155 1156 // Try to remove the dangling constants again after all operations are 1157 // converted. 1158 for (auto it : constantAggregateUseMap) { 1159 auto cst = it.first; 1160 cst->removeDeadConstantUsers(); 1161 if (cst->user_empty()) { 1162 cst->destroyConstant(); 1163 numConstantsErased++; 1164 } 1165 } 1166 1167 LLVM_DEBUG(llvm::dbgs() 1168 << "Convert initializer for " << op.getName() << "\n"; 1169 llvm::dbgs() << numConstantsHit << " new constants hit\n"; 1170 llvm::dbgs() 1171 << numConstantsErased << " dangling constants erased\n";); 1172 } 1173 } 1174 1175 // Convert llvm.mlir.global_ctors and dtors. 1176 for (Operation &op : getModuleBody(mlirModule)) { 1177 auto ctorOp = dyn_cast<GlobalCtorsOp>(op); 1178 auto dtorOp = dyn_cast<GlobalDtorsOp>(op); 1179 if (!ctorOp && !dtorOp) 1180 continue; 1181 auto range = ctorOp ? llvm::zip(ctorOp.getCtors(), ctorOp.getPriorities()) 1182 : llvm::zip(dtorOp.getDtors(), dtorOp.getPriorities()); 1183 auto appendGlobalFn = 1184 ctorOp ? llvm::appendToGlobalCtors : llvm::appendToGlobalDtors; 1185 for (auto symbolAndPriority : range) { 1186 llvm::Function *f = lookupFunction( 1187 cast<FlatSymbolRefAttr>(std::get<0>(symbolAndPriority)).getValue()); 1188 appendGlobalFn(*llvmModule, f, 1189 cast<IntegerAttr>(std::get<1>(symbolAndPriority)).getInt(), 1190 /*Data=*/nullptr); 1191 } 1192 } 1193 1194 for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) 1195 if (failed(convertDialectAttributes(op, {}))) 1196 return failure(); 1197 1198 // Finally, update the compile units their respective sets of global variables 1199 // created earlier. 1200 for (const auto &[compileUnit, globals] : allGVars) { 1201 compileUnit->replaceGlobalVariables( 1202 llvm::MDTuple::get(getLLVMContext(), globals)); 1203 } 1204 1205 return success(); 1206 } 1207 1208 /// Attempts to add an attribute identified by `key`, optionally with the given 1209 /// `value` to LLVM function `llvmFunc`. Reports errors at `loc` if any. If the 1210 /// attribute has a kind known to LLVM IR, create the attribute of this kind, 1211 /// otherwise keep it as a string attribute. Performs additional checks for 1212 /// attributes known to have or not have a value in order to avoid assertions 1213 /// inside LLVM upon construction. 1214 static LogicalResult checkedAddLLVMFnAttribute(Location loc, 1215 llvm::Function *llvmFunc, 1216 StringRef key, 1217 StringRef value = StringRef()) { 1218 auto kind = llvm::Attribute::getAttrKindFromName(key); 1219 if (kind == llvm::Attribute::None) { 1220 llvmFunc->addFnAttr(key, value); 1221 return success(); 1222 } 1223 1224 if (llvm::Attribute::isIntAttrKind(kind)) { 1225 if (value.empty()) 1226 return emitError(loc) << "LLVM attribute '" << key << "' expects a value"; 1227 1228 int64_t result; 1229 if (!value.getAsInteger(/*Radix=*/0, result)) 1230 llvmFunc->addFnAttr( 1231 llvm::Attribute::get(llvmFunc->getContext(), kind, result)); 1232 else 1233 llvmFunc->addFnAttr(key, value); 1234 return success(); 1235 } 1236 1237 if (!value.empty()) 1238 return emitError(loc) << "LLVM attribute '" << key 1239 << "' does not expect a value, found '" << value 1240 << "'"; 1241 1242 llvmFunc->addFnAttr(kind); 1243 return success(); 1244 } 1245 1246 /// Return a representation of `value` as metadata. 1247 static llvm::Metadata *convertIntegerToMetadata(llvm::LLVMContext &context, 1248 const llvm::APInt &value) { 1249 llvm::Constant *constant = llvm::ConstantInt::get(context, value); 1250 return llvm::ConstantAsMetadata::get(constant); 1251 } 1252 1253 /// Return a representation of `value` as an MDNode. 1254 static llvm::MDNode *convertIntegerToMDNode(llvm::LLVMContext &context, 1255 const llvm::APInt &value) { 1256 return llvm::MDNode::get(context, convertIntegerToMetadata(context, value)); 1257 } 1258 1259 /// Return an MDNode encoding `vec_type_hint` metadata. 1260 static llvm::MDNode *convertVecTypeHintToMDNode(llvm::LLVMContext &context, 1261 llvm::Type *type, 1262 bool isSigned) { 1263 llvm::Metadata *typeMD = 1264 llvm::ConstantAsMetadata::get(llvm::UndefValue::get(type)); 1265 llvm::Metadata *isSignedMD = 1266 convertIntegerToMetadata(context, llvm::APInt(32, isSigned ? 1 : 0)); 1267 return llvm::MDNode::get(context, {typeMD, isSignedMD}); 1268 } 1269 1270 /// Return an MDNode with a tuple given by the values in `values`. 1271 static llvm::MDNode *convertIntegerArrayToMDNode(llvm::LLVMContext &context, 1272 ArrayRef<int32_t> values) { 1273 SmallVector<llvm::Metadata *> mdValues; 1274 llvm::transform( 1275 values, std::back_inserter(mdValues), [&context](int32_t value) { 1276 return convertIntegerToMetadata(context, llvm::APInt(32, value)); 1277 }); 1278 return llvm::MDNode::get(context, mdValues); 1279 } 1280 1281 /// Attaches the attributes listed in the given array attribute to `llvmFunc`. 1282 /// Reports error to `loc` if any and returns immediately. Expects `attributes` 1283 /// to be an array attribute containing either string attributes, treated as 1284 /// value-less LLVM attributes, or array attributes containing two string 1285 /// attributes, with the first string being the name of the corresponding LLVM 1286 /// attribute and the second string beings its value. Note that even integer 1287 /// attributes are expected to have their values expressed as strings. 1288 static LogicalResult 1289 forwardPassthroughAttributes(Location loc, std::optional<ArrayAttr> attributes, 1290 llvm::Function *llvmFunc) { 1291 if (!attributes) 1292 return success(); 1293 1294 for (Attribute attr : *attributes) { 1295 if (auto stringAttr = dyn_cast<StringAttr>(attr)) { 1296 if (failed( 1297 checkedAddLLVMFnAttribute(loc, llvmFunc, stringAttr.getValue()))) 1298 return failure(); 1299 continue; 1300 } 1301 1302 auto arrayAttr = dyn_cast<ArrayAttr>(attr); 1303 if (!arrayAttr || arrayAttr.size() != 2) 1304 return emitError(loc) 1305 << "expected 'passthrough' to contain string or array attributes"; 1306 1307 auto keyAttr = dyn_cast<StringAttr>(arrayAttr[0]); 1308 auto valueAttr = dyn_cast<StringAttr>(arrayAttr[1]); 1309 if (!keyAttr || !valueAttr) 1310 return emitError(loc) 1311 << "expected arrays within 'passthrough' to contain two strings"; 1312 1313 if (failed(checkedAddLLVMFnAttribute(loc, llvmFunc, keyAttr.getValue(), 1314 valueAttr.getValue()))) 1315 return failure(); 1316 } 1317 return success(); 1318 } 1319 1320 LogicalResult ModuleTranslation::convertOneFunction(LLVMFuncOp func) { 1321 // Clear the block, branch value mappings, they are only relevant within one 1322 // function. 1323 blockMapping.clear(); 1324 valueMapping.clear(); 1325 branchMapping.clear(); 1326 llvm::Function *llvmFunc = lookupFunction(func.getName()); 1327 1328 // Add function arguments to the value remapping table. 1329 for (auto [mlirArg, llvmArg] : 1330 llvm::zip(func.getArguments(), llvmFunc->args())) 1331 mapValue(mlirArg, &llvmArg); 1332 1333 // Check the personality and set it. 1334 if (func.getPersonality()) { 1335 llvm::Type *ty = llvm::PointerType::getUnqual(llvmFunc->getContext()); 1336 if (llvm::Constant *pfunc = getLLVMConstant(ty, func.getPersonalityAttr(), 1337 func.getLoc(), *this)) 1338 llvmFunc->setPersonalityFn(pfunc); 1339 } 1340 1341 if (std::optional<StringRef> section = func.getSection()) 1342 llvmFunc->setSection(*section); 1343 1344 if (func.getArmStreaming()) 1345 llvmFunc->addFnAttr("aarch64_pstate_sm_enabled"); 1346 else if (func.getArmLocallyStreaming()) 1347 llvmFunc->addFnAttr("aarch64_pstate_sm_body"); 1348 else if (func.getArmStreamingCompatible()) 1349 llvmFunc->addFnAttr("aarch64_pstate_sm_compatible"); 1350 1351 if (func.getArmNewZa()) 1352 llvmFunc->addFnAttr("aarch64_new_za"); 1353 else if (func.getArmInZa()) 1354 llvmFunc->addFnAttr("aarch64_in_za"); 1355 else if (func.getArmOutZa()) 1356 llvmFunc->addFnAttr("aarch64_out_za"); 1357 else if (func.getArmInoutZa()) 1358 llvmFunc->addFnAttr("aarch64_inout_za"); 1359 else if (func.getArmPreservesZa()) 1360 llvmFunc->addFnAttr("aarch64_preserves_za"); 1361 1362 if (auto targetCpu = func.getTargetCpu()) 1363 llvmFunc->addFnAttr("target-cpu", *targetCpu); 1364 1365 if (auto tuneCpu = func.getTuneCpu()) 1366 llvmFunc->addFnAttr("tune-cpu", *tuneCpu); 1367 1368 if (auto targetFeatures = func.getTargetFeatures()) 1369 llvmFunc->addFnAttr("target-features", targetFeatures->getFeaturesString()); 1370 1371 if (auto attr = func.getVscaleRange()) 1372 llvmFunc->addFnAttr(llvm::Attribute::getWithVScaleRangeArgs( 1373 getLLVMContext(), attr->getMinRange().getInt(), 1374 attr->getMaxRange().getInt())); 1375 1376 if (auto unsafeFpMath = func.getUnsafeFpMath()) 1377 llvmFunc->addFnAttr("unsafe-fp-math", llvm::toStringRef(*unsafeFpMath)); 1378 1379 if (auto noInfsFpMath = func.getNoInfsFpMath()) 1380 llvmFunc->addFnAttr("no-infs-fp-math", llvm::toStringRef(*noInfsFpMath)); 1381 1382 if (auto noNansFpMath = func.getNoNansFpMath()) 1383 llvmFunc->addFnAttr("no-nans-fp-math", llvm::toStringRef(*noNansFpMath)); 1384 1385 if (auto approxFuncFpMath = func.getApproxFuncFpMath()) 1386 llvmFunc->addFnAttr("approx-func-fp-math", 1387 llvm::toStringRef(*approxFuncFpMath)); 1388 1389 if (auto noSignedZerosFpMath = func.getNoSignedZerosFpMath()) 1390 llvmFunc->addFnAttr("no-signed-zeros-fp-math", 1391 llvm::toStringRef(*noSignedZerosFpMath)); 1392 1393 if (auto denormalFpMath = func.getDenormalFpMath()) 1394 llvmFunc->addFnAttr("denormal-fp-math", *denormalFpMath); 1395 1396 if (auto denormalFpMathF32 = func.getDenormalFpMathF32()) 1397 llvmFunc->addFnAttr("denormal-fp-math-f32", *denormalFpMathF32); 1398 1399 if (auto fpContract = func.getFpContract()) 1400 llvmFunc->addFnAttr("fp-contract", *fpContract); 1401 1402 // Add function attribute frame-pointer, if found. 1403 if (FramePointerKindAttr attr = func.getFramePointerAttr()) 1404 llvmFunc->addFnAttr("frame-pointer", 1405 LLVM::framePointerKind::stringifyFramePointerKind( 1406 (attr.getFramePointerKind()))); 1407 1408 // First, create all blocks so we can jump to them. 1409 llvm::LLVMContext &llvmContext = llvmFunc->getContext(); 1410 for (auto &bb : func) { 1411 auto *llvmBB = llvm::BasicBlock::Create(llvmContext); 1412 llvmBB->insertInto(llvmFunc); 1413 mapBlock(&bb, llvmBB); 1414 } 1415 1416 // Then, convert blocks one by one in topological order to ensure defs are 1417 // converted before uses. 1418 auto blocks = getBlocksSortedByDominance(func.getBody()); 1419 for (Block *bb : blocks) { 1420 CapturingIRBuilder builder(llvmContext); 1421 if (failed(convertBlockImpl(*bb, bb->isEntryBlock(), builder, 1422 /*recordInsertions=*/true))) 1423 return failure(); 1424 } 1425 1426 // After all blocks have been traversed and values mapped, connect the PHI 1427 // nodes to the results of preceding blocks. 1428 detail::connectPHINodes(func.getBody(), *this); 1429 1430 // Finally, convert dialect attributes attached to the function. 1431 return convertDialectAttributes(func, {}); 1432 } 1433 1434 LogicalResult ModuleTranslation::convertDialectAttributes( 1435 Operation *op, ArrayRef<llvm::Instruction *> instructions) { 1436 for (NamedAttribute attribute : op->getDialectAttrs()) 1437 if (failed(iface.amendOperation(op, instructions, attribute, *this))) 1438 return failure(); 1439 return success(); 1440 } 1441 1442 /// Converts memory effect attributes from `func` and attaches them to 1443 /// `llvmFunc`. 1444 static void convertFunctionMemoryAttributes(LLVMFuncOp func, 1445 llvm::Function *llvmFunc) { 1446 if (!func.getMemoryEffects()) 1447 return; 1448 1449 MemoryEffectsAttr memEffects = func.getMemoryEffectsAttr(); 1450 1451 // Add memory effects incrementally. 1452 llvm::MemoryEffects newMemEffects = 1453 llvm::MemoryEffects(llvm::MemoryEffects::Location::ArgMem, 1454 convertModRefInfoToLLVM(memEffects.getArgMem())); 1455 newMemEffects |= llvm::MemoryEffects( 1456 llvm::MemoryEffects::Location::InaccessibleMem, 1457 convertModRefInfoToLLVM(memEffects.getInaccessibleMem())); 1458 newMemEffects |= 1459 llvm::MemoryEffects(llvm::MemoryEffects::Location::Other, 1460 convertModRefInfoToLLVM(memEffects.getOther())); 1461 llvmFunc->setMemoryEffects(newMemEffects); 1462 } 1463 1464 /// Converts function attributes from `func` and attaches them to `llvmFunc`. 1465 static void convertFunctionAttributes(LLVMFuncOp func, 1466 llvm::Function *llvmFunc) { 1467 if (func.getNoInlineAttr()) 1468 llvmFunc->addFnAttr(llvm::Attribute::NoInline); 1469 if (func.getAlwaysInlineAttr()) 1470 llvmFunc->addFnAttr(llvm::Attribute::AlwaysInline); 1471 if (func.getOptimizeNoneAttr()) 1472 llvmFunc->addFnAttr(llvm::Attribute::OptimizeNone); 1473 if (func.getConvergentAttr()) 1474 llvmFunc->addFnAttr(llvm::Attribute::Convergent); 1475 if (func.getNoUnwindAttr()) 1476 llvmFunc->addFnAttr(llvm::Attribute::NoUnwind); 1477 if (func.getWillReturnAttr()) 1478 llvmFunc->addFnAttr(llvm::Attribute::WillReturn); 1479 convertFunctionMemoryAttributes(func, llvmFunc); 1480 } 1481 1482 /// Converts function attributes from `func` and attaches them to `llvmFunc`. 1483 static void convertFunctionKernelAttributes(LLVMFuncOp func, 1484 llvm::Function *llvmFunc, 1485 ModuleTranslation &translation) { 1486 llvm::LLVMContext &llvmContext = llvmFunc->getContext(); 1487 1488 if (VecTypeHintAttr vecTypeHint = func.getVecTypeHintAttr()) { 1489 Type type = vecTypeHint.getHint().getValue(); 1490 llvm::Type *llvmType = translation.convertType(type); 1491 bool isSigned = vecTypeHint.getIsSigned(); 1492 llvmFunc->setMetadata( 1493 func.getVecTypeHintAttrName(), 1494 convertVecTypeHintToMDNode(llvmContext, llvmType, isSigned)); 1495 } 1496 1497 if (std::optional<ArrayRef<int32_t>> workGroupSizeHint = 1498 func.getWorkGroupSizeHint()) { 1499 llvmFunc->setMetadata( 1500 func.getWorkGroupSizeHintAttrName(), 1501 convertIntegerArrayToMDNode(llvmContext, *workGroupSizeHint)); 1502 } 1503 1504 if (std::optional<ArrayRef<int32_t>> reqdWorkGroupSize = 1505 func.getReqdWorkGroupSize()) { 1506 llvmFunc->setMetadata( 1507 func.getReqdWorkGroupSizeAttrName(), 1508 convertIntegerArrayToMDNode(llvmContext, *reqdWorkGroupSize)); 1509 } 1510 1511 if (std::optional<uint32_t> intelReqdSubGroupSize = 1512 func.getIntelReqdSubGroupSize()) { 1513 llvmFunc->setMetadata( 1514 func.getIntelReqdSubGroupSizeAttrName(), 1515 convertIntegerToMDNode(llvmContext, 1516 llvm::APInt(32, *intelReqdSubGroupSize))); 1517 } 1518 } 1519 1520 FailureOr<llvm::AttrBuilder> 1521 ModuleTranslation::convertParameterAttrs(LLVMFuncOp func, int argIdx, 1522 DictionaryAttr paramAttrs) { 1523 llvm::AttrBuilder attrBuilder(llvmModule->getContext()); 1524 auto attrNameToKindMapping = getAttrNameToKindMapping(); 1525 1526 for (auto namedAttr : paramAttrs) { 1527 auto it = attrNameToKindMapping.find(namedAttr.getName()); 1528 if (it != attrNameToKindMapping.end()) { 1529 llvm::Attribute::AttrKind llvmKind = it->second; 1530 1531 llvm::TypeSwitch<Attribute>(namedAttr.getValue()) 1532 .Case<TypeAttr>([&](auto typeAttr) { 1533 attrBuilder.addTypeAttr(llvmKind, convertType(typeAttr.getValue())); 1534 }) 1535 .Case<IntegerAttr>([&](auto intAttr) { 1536 attrBuilder.addRawIntAttr(llvmKind, intAttr.getInt()); 1537 }) 1538 .Case<UnitAttr>([&](auto) { attrBuilder.addAttribute(llvmKind); }); 1539 } else if (namedAttr.getNameDialect()) { 1540 if (failed(iface.convertParameterAttr(func, argIdx, namedAttr, *this))) 1541 return failure(); 1542 } 1543 } 1544 1545 return attrBuilder; 1546 } 1547 1548 LogicalResult ModuleTranslation::convertFunctionSignatures() { 1549 // Declare all functions first because there may be function calls that form a 1550 // call graph with cycles, or global initializers that reference functions. 1551 for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) { 1552 llvm::FunctionCallee llvmFuncCst = llvmModule->getOrInsertFunction( 1553 function.getName(), 1554 cast<llvm::FunctionType>(convertType(function.getFunctionType()))); 1555 llvm::Function *llvmFunc = cast<llvm::Function>(llvmFuncCst.getCallee()); 1556 llvmFunc->setLinkage(convertLinkageToLLVM(function.getLinkage())); 1557 llvmFunc->setCallingConv(convertCConvToLLVM(function.getCConv())); 1558 mapFunction(function.getName(), llvmFunc); 1559 addRuntimePreemptionSpecifier(function.getDsoLocal(), llvmFunc); 1560 1561 // Convert function attributes. 1562 convertFunctionAttributes(function, llvmFunc); 1563 1564 // Convert function kernel attributes to metadata. 1565 convertFunctionKernelAttributes(function, llvmFunc, *this); 1566 1567 // Convert function_entry_count attribute to metadata. 1568 if (std::optional<uint64_t> entryCount = function.getFunctionEntryCount()) 1569 llvmFunc->setEntryCount(entryCount.value()); 1570 1571 // Convert result attributes. 1572 if (ArrayAttr allResultAttrs = function.getAllResultAttrs()) { 1573 DictionaryAttr resultAttrs = cast<DictionaryAttr>(allResultAttrs[0]); 1574 FailureOr<llvm::AttrBuilder> attrBuilder = 1575 convertParameterAttrs(function, -1, resultAttrs); 1576 if (failed(attrBuilder)) 1577 return failure(); 1578 llvmFunc->addRetAttrs(*attrBuilder); 1579 } 1580 1581 // Convert argument attributes. 1582 for (auto [argIdx, llvmArg] : llvm::enumerate(llvmFunc->args())) { 1583 if (DictionaryAttr argAttrs = function.getArgAttrDict(argIdx)) { 1584 FailureOr<llvm::AttrBuilder> attrBuilder = 1585 convertParameterAttrs(function, argIdx, argAttrs); 1586 if (failed(attrBuilder)) 1587 return failure(); 1588 llvmArg.addAttrs(*attrBuilder); 1589 } 1590 } 1591 1592 // Forward the pass-through attributes to LLVM. 1593 if (failed(forwardPassthroughAttributes( 1594 function.getLoc(), function.getPassthrough(), llvmFunc))) 1595 return failure(); 1596 1597 // Convert visibility attribute. 1598 llvmFunc->setVisibility(convertVisibilityToLLVM(function.getVisibility_())); 1599 1600 // Convert the comdat attribute. 1601 if (std::optional<mlir::SymbolRefAttr> comdat = function.getComdat()) { 1602 auto selectorOp = cast<ComdatSelectorOp>( 1603 SymbolTable::lookupNearestSymbolFrom(function, *comdat)); 1604 llvmFunc->setComdat(comdatMapping.lookup(selectorOp)); 1605 } 1606 1607 if (auto gc = function.getGarbageCollector()) 1608 llvmFunc->setGC(gc->str()); 1609 1610 if (auto unnamedAddr = function.getUnnamedAddr()) 1611 llvmFunc->setUnnamedAddr(convertUnnamedAddrToLLVM(*unnamedAddr)); 1612 1613 if (auto alignment = function.getAlignment()) 1614 llvmFunc->setAlignment(llvm::MaybeAlign(*alignment)); 1615 1616 // Translate the debug information for this function. 1617 debugTranslation->translate(function, *llvmFunc); 1618 } 1619 1620 return success(); 1621 } 1622 1623 LogicalResult ModuleTranslation::convertFunctions() { 1624 // Convert functions. 1625 for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) { 1626 // Do not convert external functions, but do process dialect attributes 1627 // attached to them. 1628 if (function.isExternal()) { 1629 if (failed(convertDialectAttributes(function, {}))) 1630 return failure(); 1631 continue; 1632 } 1633 1634 if (failed(convertOneFunction(function))) 1635 return failure(); 1636 } 1637 1638 return success(); 1639 } 1640 1641 LogicalResult ModuleTranslation::convertComdats() { 1642 for (auto comdatOp : getModuleBody(mlirModule).getOps<ComdatOp>()) { 1643 for (auto selectorOp : comdatOp.getOps<ComdatSelectorOp>()) { 1644 llvm::Module *module = getLLVMModule(); 1645 if (module->getComdatSymbolTable().contains(selectorOp.getSymName())) 1646 return emitError(selectorOp.getLoc()) 1647 << "comdat selection symbols must be unique even in different " 1648 "comdat regions"; 1649 llvm::Comdat *comdat = module->getOrInsertComdat(selectorOp.getSymName()); 1650 comdat->setSelectionKind(convertComdatToLLVM(selectorOp.getComdat())); 1651 comdatMapping.try_emplace(selectorOp, comdat); 1652 } 1653 } 1654 return success(); 1655 } 1656 1657 void ModuleTranslation::setAccessGroupsMetadata(AccessGroupOpInterface op, 1658 llvm::Instruction *inst) { 1659 if (llvm::MDNode *node = loopAnnotationTranslation->getAccessGroups(op)) 1660 inst->setMetadata(llvm::LLVMContext::MD_access_group, node); 1661 } 1662 1663 llvm::MDNode * 1664 ModuleTranslation::getOrCreateAliasScope(AliasScopeAttr aliasScopeAttr) { 1665 auto [scopeIt, scopeInserted] = 1666 aliasScopeMetadataMapping.try_emplace(aliasScopeAttr, nullptr); 1667 if (!scopeInserted) 1668 return scopeIt->second; 1669 llvm::LLVMContext &ctx = llvmModule->getContext(); 1670 auto dummy = llvm::MDNode::getTemporary(ctx, std::nullopt); 1671 // Convert the domain metadata node if necessary. 1672 auto [domainIt, insertedDomain] = aliasDomainMetadataMapping.try_emplace( 1673 aliasScopeAttr.getDomain(), nullptr); 1674 if (insertedDomain) { 1675 llvm::SmallVector<llvm::Metadata *, 2> operands; 1676 // Placeholder for self-reference. 1677 operands.push_back(dummy.get()); 1678 if (StringAttr description = aliasScopeAttr.getDomain().getDescription()) 1679 operands.push_back(llvm::MDString::get(ctx, description)); 1680 domainIt->second = llvm::MDNode::get(ctx, operands); 1681 // Self-reference for uniqueness. 1682 domainIt->second->replaceOperandWith(0, domainIt->second); 1683 } 1684 // Convert the scope metadata node. 1685 assert(domainIt->second && "Scope's domain should already be valid"); 1686 llvm::SmallVector<llvm::Metadata *, 3> operands; 1687 // Placeholder for self-reference. 1688 operands.push_back(dummy.get()); 1689 operands.push_back(domainIt->second); 1690 if (StringAttr description = aliasScopeAttr.getDescription()) 1691 operands.push_back(llvm::MDString::get(ctx, description)); 1692 scopeIt->second = llvm::MDNode::get(ctx, operands); 1693 // Self-reference for uniqueness. 1694 scopeIt->second->replaceOperandWith(0, scopeIt->second); 1695 return scopeIt->second; 1696 } 1697 1698 llvm::MDNode *ModuleTranslation::getOrCreateAliasScopes( 1699 ArrayRef<AliasScopeAttr> aliasScopeAttrs) { 1700 SmallVector<llvm::Metadata *> nodes; 1701 nodes.reserve(aliasScopeAttrs.size()); 1702 for (AliasScopeAttr aliasScopeAttr : aliasScopeAttrs) 1703 nodes.push_back(getOrCreateAliasScope(aliasScopeAttr)); 1704 return llvm::MDNode::get(getLLVMContext(), nodes); 1705 } 1706 1707 void ModuleTranslation::setAliasScopeMetadata(AliasAnalysisOpInterface op, 1708 llvm::Instruction *inst) { 1709 auto populateScopeMetadata = [&](ArrayAttr aliasScopeAttrs, unsigned kind) { 1710 if (!aliasScopeAttrs || aliasScopeAttrs.empty()) 1711 return; 1712 llvm::MDNode *node = getOrCreateAliasScopes( 1713 llvm::to_vector(aliasScopeAttrs.getAsRange<AliasScopeAttr>())); 1714 inst->setMetadata(kind, node); 1715 }; 1716 1717 populateScopeMetadata(op.getAliasScopesOrNull(), 1718 llvm::LLVMContext::MD_alias_scope); 1719 populateScopeMetadata(op.getNoAliasScopesOrNull(), 1720 llvm::LLVMContext::MD_noalias); 1721 } 1722 1723 llvm::MDNode *ModuleTranslation::getTBAANode(TBAATagAttr tbaaAttr) const { 1724 return tbaaMetadataMapping.lookup(tbaaAttr); 1725 } 1726 1727 void ModuleTranslation::setTBAAMetadata(AliasAnalysisOpInterface op, 1728 llvm::Instruction *inst) { 1729 ArrayAttr tagRefs = op.getTBAATagsOrNull(); 1730 if (!tagRefs || tagRefs.empty()) 1731 return; 1732 1733 // LLVM IR currently does not support attaching more than one TBAA access tag 1734 // to a memory accessing instruction. It may be useful to support this in 1735 // future, but for the time being just ignore the metadata if MLIR operation 1736 // has multiple access tags. 1737 if (tagRefs.size() > 1) { 1738 op.emitWarning() << "TBAA access tags were not translated, because LLVM " 1739 "IR only supports a single tag per instruction"; 1740 return; 1741 } 1742 1743 llvm::MDNode *node = getTBAANode(cast<TBAATagAttr>(tagRefs[0])); 1744 inst->setMetadata(llvm::LLVMContext::MD_tbaa, node); 1745 } 1746 1747 void ModuleTranslation::setBranchWeightsMetadata(BranchWeightOpInterface op) { 1748 DenseI32ArrayAttr weightsAttr = op.getBranchWeightsOrNull(); 1749 if (!weightsAttr) 1750 return; 1751 1752 llvm::Instruction *inst = isa<CallOp>(op) ? lookupCall(op) : lookupBranch(op); 1753 assert(inst && "expected the operation to have a mapping to an instruction"); 1754 SmallVector<uint32_t> weights(weightsAttr.asArrayRef()); 1755 inst->setMetadata( 1756 llvm::LLVMContext::MD_prof, 1757 llvm::MDBuilder(getLLVMContext()).createBranchWeights(weights)); 1758 } 1759 1760 LogicalResult ModuleTranslation::createTBAAMetadata() { 1761 llvm::LLVMContext &ctx = llvmModule->getContext(); 1762 llvm::IntegerType *offsetTy = llvm::IntegerType::get(ctx, 64); 1763 1764 // Walk the entire module and create all metadata nodes for the TBAA 1765 // attributes. The code below relies on two invariants of the 1766 // `AttrTypeWalker`: 1767 // 1. Attributes are visited in post-order: Since the attributes create a DAG, 1768 // this ensures that any lookups into `tbaaMetadataMapping` for child 1769 // attributes succeed. 1770 // 2. Attributes are only ever visited once: This way we don't leak any 1771 // LLVM metadata instances. 1772 AttrTypeWalker walker; 1773 walker.addWalk([&](TBAARootAttr root) { 1774 tbaaMetadataMapping.insert( 1775 {root, llvm::MDNode::get(ctx, llvm::MDString::get(ctx, root.getId()))}); 1776 }); 1777 1778 walker.addWalk([&](TBAATypeDescriptorAttr descriptor) { 1779 SmallVector<llvm::Metadata *> operands; 1780 operands.push_back(llvm::MDString::get(ctx, descriptor.getId())); 1781 for (TBAAMemberAttr member : descriptor.getMembers()) { 1782 operands.push_back(tbaaMetadataMapping.lookup(member.getTypeDesc())); 1783 operands.push_back(llvm::ConstantAsMetadata::get( 1784 llvm::ConstantInt::get(offsetTy, member.getOffset()))); 1785 } 1786 1787 tbaaMetadataMapping.insert({descriptor, llvm::MDNode::get(ctx, operands)}); 1788 }); 1789 1790 walker.addWalk([&](TBAATagAttr tag) { 1791 SmallVector<llvm::Metadata *> operands; 1792 1793 operands.push_back(tbaaMetadataMapping.lookup(tag.getBaseType())); 1794 operands.push_back(tbaaMetadataMapping.lookup(tag.getAccessType())); 1795 1796 operands.push_back(llvm::ConstantAsMetadata::get( 1797 llvm::ConstantInt::get(offsetTy, tag.getOffset()))); 1798 if (tag.getConstant()) 1799 operands.push_back( 1800 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(offsetTy, 1))); 1801 1802 tbaaMetadataMapping.insert({tag, llvm::MDNode::get(ctx, operands)}); 1803 }); 1804 1805 mlirModule->walk([&](AliasAnalysisOpInterface analysisOpInterface) { 1806 if (auto attr = analysisOpInterface.getTBAATagsOrNull()) 1807 walker.walk(attr); 1808 }); 1809 1810 return success(); 1811 } 1812 1813 LogicalResult ModuleTranslation::createIdentMetadata() { 1814 if (auto attr = mlirModule->getAttrOfType<StringAttr>( 1815 LLVMDialect::getIdentAttrName())) { 1816 StringRef ident = attr; 1817 llvm::LLVMContext &ctx = llvmModule->getContext(); 1818 llvm::NamedMDNode *namedMd = 1819 llvmModule->getOrInsertNamedMetadata(LLVMDialect::getIdentAttrName()); 1820 llvm::MDNode *md = llvm::MDNode::get(ctx, llvm::MDString::get(ctx, ident)); 1821 namedMd->addOperand(md); 1822 } 1823 1824 return success(); 1825 } 1826 1827 void ModuleTranslation::setLoopMetadata(Operation *op, 1828 llvm::Instruction *inst) { 1829 LoopAnnotationAttr attr = 1830 TypeSwitch<Operation *, LoopAnnotationAttr>(op) 1831 .Case<LLVM::BrOp, LLVM::CondBrOp>( 1832 [](auto branchOp) { return branchOp.getLoopAnnotationAttr(); }); 1833 if (!attr) 1834 return; 1835 llvm::MDNode *loopMD = 1836 loopAnnotationTranslation->translateLoopAnnotation(attr, op); 1837 inst->setMetadata(llvm::LLVMContext::MD_loop, loopMD); 1838 } 1839 1840 llvm::Type *ModuleTranslation::convertType(Type type) { 1841 return typeTranslator.translateType(type); 1842 } 1843 1844 /// A helper to look up remapped operands in the value remapping table. 1845 SmallVector<llvm::Value *> ModuleTranslation::lookupValues(ValueRange values) { 1846 SmallVector<llvm::Value *> remapped; 1847 remapped.reserve(values.size()); 1848 for (Value v : values) 1849 remapped.push_back(lookupValue(v)); 1850 return remapped; 1851 } 1852 1853 llvm::OpenMPIRBuilder *ModuleTranslation::getOpenMPBuilder() { 1854 if (!ompBuilder) { 1855 ompBuilder = std::make_unique<llvm::OpenMPIRBuilder>(*llvmModule); 1856 ompBuilder->initialize(); 1857 1858 // Flags represented as top-level OpenMP dialect attributes are set in 1859 // `OpenMPDialectLLVMIRTranslationInterface::amendOperation()`. Here we set 1860 // the default configuration. 1861 ompBuilder->setConfig(llvm::OpenMPIRBuilderConfig( 1862 /* IsTargetDevice = */ false, /* IsGPU = */ false, 1863 /* OpenMPOffloadMandatory = */ false, 1864 /* HasRequiresReverseOffload = */ false, 1865 /* HasRequiresUnifiedAddress = */ false, 1866 /* HasRequiresUnifiedSharedMemory = */ false, 1867 /* HasRequiresDynamicAllocators = */ false)); 1868 } 1869 return ompBuilder.get(); 1870 } 1871 1872 llvm::DILocation *ModuleTranslation::translateLoc(Location loc, 1873 llvm::DILocalScope *scope) { 1874 return debugTranslation->translateLoc(loc, scope); 1875 } 1876 1877 llvm::DIExpression * 1878 ModuleTranslation::translateExpression(LLVM::DIExpressionAttr attr) { 1879 return debugTranslation->translateExpression(attr); 1880 } 1881 1882 llvm::DIGlobalVariableExpression * 1883 ModuleTranslation::translateGlobalVariableExpression( 1884 LLVM::DIGlobalVariableExpressionAttr attr) { 1885 return debugTranslation->translateGlobalVariableExpression(attr); 1886 } 1887 1888 llvm::Metadata *ModuleTranslation::translateDebugInfo(LLVM::DINodeAttr attr) { 1889 return debugTranslation->translate(attr); 1890 } 1891 1892 llvm::RoundingMode 1893 ModuleTranslation::translateRoundingMode(LLVM::RoundingMode rounding) { 1894 return convertRoundingModeToLLVM(rounding); 1895 } 1896 1897 llvm::fp::ExceptionBehavior ModuleTranslation::translateFPExceptionBehavior( 1898 LLVM::FPExceptionBehavior exceptionBehavior) { 1899 return convertFPExceptionBehaviorToLLVM(exceptionBehavior); 1900 } 1901 1902 llvm::NamedMDNode * 1903 ModuleTranslation::getOrInsertNamedModuleMetadata(StringRef name) { 1904 return llvmModule->getOrInsertNamedMetadata(name); 1905 } 1906 1907 void ModuleTranslation::StackFrame::anchor() {} 1908 1909 static std::unique_ptr<llvm::Module> 1910 prepareLLVMModule(Operation *m, llvm::LLVMContext &llvmContext, 1911 StringRef name) { 1912 m->getContext()->getOrLoadDialect<LLVM::LLVMDialect>(); 1913 auto llvmModule = std::make_unique<llvm::Module>(name, llvmContext); 1914 // ModuleTranslation can currently only construct modules in the old debug 1915 // info format, so set the flag accordingly. 1916 llvmModule->setNewDbgInfoFormatFlag(false); 1917 if (auto dataLayoutAttr = 1918 m->getDiscardableAttr(LLVM::LLVMDialect::getDataLayoutAttrName())) { 1919 llvmModule->setDataLayout(cast<StringAttr>(dataLayoutAttr).getValue()); 1920 } else { 1921 FailureOr<llvm::DataLayout> llvmDataLayout(llvm::DataLayout("")); 1922 if (auto iface = dyn_cast<DataLayoutOpInterface>(m)) { 1923 if (DataLayoutSpecInterface spec = iface.getDataLayoutSpec()) { 1924 llvmDataLayout = 1925 translateDataLayout(spec, DataLayout(iface), m->getLoc()); 1926 } 1927 } else if (auto mod = dyn_cast<ModuleOp>(m)) { 1928 if (DataLayoutSpecInterface spec = mod.getDataLayoutSpec()) { 1929 llvmDataLayout = 1930 translateDataLayout(spec, DataLayout(mod), m->getLoc()); 1931 } 1932 } 1933 if (failed(llvmDataLayout)) 1934 return nullptr; 1935 llvmModule->setDataLayout(*llvmDataLayout); 1936 } 1937 if (auto targetTripleAttr = 1938 m->getDiscardableAttr(LLVM::LLVMDialect::getTargetTripleAttrName())) 1939 llvmModule->setTargetTriple(cast<StringAttr>(targetTripleAttr).getValue()); 1940 1941 return llvmModule; 1942 } 1943 1944 std::unique_ptr<llvm::Module> 1945 mlir::translateModuleToLLVMIR(Operation *module, llvm::LLVMContext &llvmContext, 1946 StringRef name, bool disableVerification) { 1947 if (!satisfiesLLVMModule(module)) { 1948 module->emitOpError("can not be translated to an LLVMIR module"); 1949 return nullptr; 1950 } 1951 1952 std::unique_ptr<llvm::Module> llvmModule = 1953 prepareLLVMModule(module, llvmContext, name); 1954 if (!llvmModule) 1955 return nullptr; 1956 1957 LLVM::ensureDistinctSuccessors(module); 1958 LLVM::legalizeDIExpressionsRecursively(module); 1959 1960 ModuleTranslation translator(module, std::move(llvmModule)); 1961 llvm::IRBuilder<> llvmBuilder(llvmContext); 1962 1963 // Convert module before functions and operations inside, so dialect 1964 // attributes can be used to change dialect-specific global configurations via 1965 // `amendOperation()`. These configurations can then influence the translation 1966 // of operations afterwards. 1967 if (failed(translator.convertOperation(*module, llvmBuilder))) 1968 return nullptr; 1969 1970 if (failed(translator.convertComdats())) 1971 return nullptr; 1972 if (failed(translator.convertFunctionSignatures())) 1973 return nullptr; 1974 if (failed(translator.convertGlobals())) 1975 return nullptr; 1976 if (failed(translator.createTBAAMetadata())) 1977 return nullptr; 1978 if (failed(translator.createIdentMetadata())) 1979 return nullptr; 1980 1981 // Convert other top-level operations if possible. 1982 for (Operation &o : getModuleBody(module).getOperations()) { 1983 if (!isa<LLVM::LLVMFuncOp, LLVM::GlobalOp, LLVM::GlobalCtorsOp, 1984 LLVM::GlobalDtorsOp, LLVM::ComdatOp>(&o) && 1985 !o.hasTrait<OpTrait::IsTerminator>() && 1986 failed(translator.convertOperation(o, llvmBuilder))) { 1987 return nullptr; 1988 } 1989 } 1990 1991 // Operations in function bodies with symbolic references must be converted 1992 // after the top-level operations they refer to are declared, so we do it 1993 // last. 1994 if (failed(translator.convertFunctions())) 1995 return nullptr; 1996 1997 // Once we've finished constructing elements in the module, we should convert 1998 // it to use the debug info format desired by LLVM. 1999 // See https://llvm.org/docs/RemoveDIsDebugInfo.html 2000 translator.llvmModule->setIsNewDbgInfoFormat(UseNewDbgInfoFormat); 2001 2002 if (!disableVerification && 2003 llvm::verifyModule(*translator.llvmModule, &llvm::errs())) 2004 return nullptr; 2005 2006 return std::move(translator.llvmModule); 2007 } 2008