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