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 "DebugTranslation.h" 17 #include "mlir/Dialect/LLVMIR/LLVMDialect.h" 18 #include "mlir/Dialect/LLVMIR/Transforms/LegalizeForExport.h" 19 #include "mlir/Dialect/OpenMP/OpenMPDialect.h" 20 #include "mlir/IR/Attributes.h" 21 #include "mlir/IR/BuiltinOps.h" 22 #include "mlir/IR/BuiltinTypes.h" 23 #include "mlir/IR/RegionGraphTraits.h" 24 #include "mlir/Support/LLVM.h" 25 #include "mlir/Target/LLVMIR/LLVMTranslationInterface.h" 26 #include "mlir/Target/LLVMIR/TypeTranslation.h" 27 #include "llvm/ADT/TypeSwitch.h" 28 29 #include "llvm/ADT/PostOrderIterator.h" 30 #include "llvm/ADT/SetVector.h" 31 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h" 32 #include "llvm/IR/BasicBlock.h" 33 #include "llvm/IR/CFG.h" 34 #include "llvm/IR/Constants.h" 35 #include "llvm/IR/DerivedTypes.h" 36 #include "llvm/IR/IRBuilder.h" 37 #include "llvm/IR/InlineAsm.h" 38 #include "llvm/IR/IntrinsicsNVPTX.h" 39 #include "llvm/IR/LLVMContext.h" 40 #include "llvm/IR/MDBuilder.h" 41 #include "llvm/IR/Module.h" 42 #include "llvm/IR/Verifier.h" 43 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 44 #include "llvm/Transforms/Utils/Cloning.h" 45 46 using namespace mlir; 47 using namespace mlir::LLVM; 48 using namespace mlir::LLVM::detail; 49 50 #include "mlir/Dialect/LLVMIR/LLVMConversionEnumsToLLVM.inc" 51 52 /// Builds a constant of a sequential LLVM type `type`, potentially containing 53 /// other sequential types recursively, from the individual constant values 54 /// provided in `constants`. `shape` contains the number of elements in nested 55 /// sequential types. Reports errors at `loc` and returns nullptr on error. 56 static llvm::Constant * 57 buildSequentialConstant(ArrayRef<llvm::Constant *> &constants, 58 ArrayRef<int64_t> shape, llvm::Type *type, 59 Location loc) { 60 if (shape.empty()) { 61 llvm::Constant *result = constants.front(); 62 constants = constants.drop_front(); 63 return result; 64 } 65 66 llvm::Type *elementType; 67 if (auto *arrayTy = dyn_cast<llvm::ArrayType>(type)) { 68 elementType = arrayTy->getElementType(); 69 } else if (auto *vectorTy = dyn_cast<llvm::VectorType>(type)) { 70 elementType = vectorTy->getElementType(); 71 } else { 72 emitError(loc) << "expected sequential LLVM types wrapping a scalar"; 73 return nullptr; 74 } 75 76 SmallVector<llvm::Constant *, 8> nested; 77 nested.reserve(shape.front()); 78 for (int64_t i = 0; i < shape.front(); ++i) { 79 nested.push_back(buildSequentialConstant(constants, shape.drop_front(), 80 elementType, loc)); 81 if (!nested.back()) 82 return nullptr; 83 } 84 85 if (shape.size() == 1 && type->isVectorTy()) 86 return llvm::ConstantVector::get(nested); 87 return llvm::ConstantArray::get( 88 llvm::ArrayType::get(elementType, shape.front()), nested); 89 } 90 91 /// Returns the first non-sequential type nested in sequential types. 92 static llvm::Type *getInnermostElementType(llvm::Type *type) { 93 do { 94 if (auto *arrayTy = dyn_cast<llvm::ArrayType>(type)) { 95 type = arrayTy->getElementType(); 96 } else if (auto *vectorTy = dyn_cast<llvm::VectorType>(type)) { 97 type = vectorTy->getElementType(); 98 } else { 99 return type; 100 } 101 } while (true); 102 } 103 104 /// Create an LLVM IR constant of `llvmType` from the MLIR attribute `attr`. 105 /// This currently supports integer, floating point, splat and dense element 106 /// attributes and combinations thereof. In case of error, report it to `loc` 107 /// and return nullptr. 108 llvm::Constant *mlir::LLVM::detail::getLLVMConstant( 109 llvm::Type *llvmType, Attribute attr, Location loc, 110 const ModuleTranslation &moduleTranslation) { 111 if (!attr) 112 return llvm::UndefValue::get(llvmType); 113 if (llvmType->isStructTy()) { 114 emitError(loc, "struct types are not supported in constants"); 115 return nullptr; 116 } 117 // For integer types, we allow a mismatch in sizes as the index type in 118 // MLIR might have a different size than the index type in the LLVM module. 119 if (auto intAttr = attr.dyn_cast<IntegerAttr>()) 120 return llvm::ConstantInt::get( 121 llvmType, 122 intAttr.getValue().sextOrTrunc(llvmType->getIntegerBitWidth())); 123 if (auto floatAttr = attr.dyn_cast<FloatAttr>()) 124 return llvm::ConstantFP::get(llvmType, floatAttr.getValue()); 125 if (auto funcAttr = attr.dyn_cast<FlatSymbolRefAttr>()) 126 return llvm::ConstantExpr::getBitCast( 127 moduleTranslation.lookupFunction(funcAttr.getValue()), llvmType); 128 if (auto splatAttr = attr.dyn_cast<SplatElementsAttr>()) { 129 llvm::Type *elementType; 130 uint64_t numElements; 131 if (auto *arrayTy = dyn_cast<llvm::ArrayType>(llvmType)) { 132 elementType = arrayTy->getElementType(); 133 numElements = arrayTy->getNumElements(); 134 } else { 135 auto *vectorTy = cast<llvm::FixedVectorType>(llvmType); 136 elementType = vectorTy->getElementType(); 137 numElements = vectorTy->getNumElements(); 138 } 139 // Splat value is a scalar. Extract it only if the element type is not 140 // another sequence type. The recursion terminates because each step removes 141 // one outer sequential type. 142 bool elementTypeSequential = 143 isa<llvm::ArrayType, llvm::VectorType>(elementType); 144 llvm::Constant *child = getLLVMConstant( 145 elementType, 146 elementTypeSequential ? splatAttr : splatAttr.getSplatValue(), loc, 147 moduleTranslation); 148 if (!child) 149 return nullptr; 150 if (llvmType->isVectorTy()) 151 return llvm::ConstantVector::getSplat( 152 llvm::ElementCount::get(numElements, /*Scalable=*/false), child); 153 if (llvmType->isArrayTy()) { 154 auto *arrayType = llvm::ArrayType::get(elementType, numElements); 155 SmallVector<llvm::Constant *, 8> constants(numElements, child); 156 return llvm::ConstantArray::get(arrayType, constants); 157 } 158 } 159 160 if (auto elementsAttr = attr.dyn_cast<ElementsAttr>()) { 161 assert(elementsAttr.getType().hasStaticShape()); 162 assert(elementsAttr.getNumElements() != 0 && 163 "unexpected empty elements attribute"); 164 assert(!elementsAttr.getType().getShape().empty() && 165 "unexpected empty elements attribute shape"); 166 167 SmallVector<llvm::Constant *, 8> constants; 168 constants.reserve(elementsAttr.getNumElements()); 169 llvm::Type *innermostType = getInnermostElementType(llvmType); 170 for (auto n : elementsAttr.getValues<Attribute>()) { 171 constants.push_back( 172 getLLVMConstant(innermostType, n, loc, moduleTranslation)); 173 if (!constants.back()) 174 return nullptr; 175 } 176 ArrayRef<llvm::Constant *> constantsRef = constants; 177 llvm::Constant *result = buildSequentialConstant( 178 constantsRef, elementsAttr.getType().getShape(), llvmType, loc); 179 assert(constantsRef.empty() && "did not consume all elemental constants"); 180 return result; 181 } 182 183 if (auto stringAttr = attr.dyn_cast<StringAttr>()) { 184 return llvm::ConstantDataArray::get( 185 moduleTranslation.getLLVMContext(), 186 ArrayRef<char>{stringAttr.getValue().data(), 187 stringAttr.getValue().size()}); 188 } 189 emitError(loc, "unsupported constant value"); 190 return nullptr; 191 } 192 193 ModuleTranslation::ModuleTranslation(Operation *module, 194 std::unique_ptr<llvm::Module> llvmModule) 195 : mlirModule(module), llvmModule(std::move(llvmModule)), 196 debugTranslation( 197 std::make_unique<DebugTranslation>(module, *this->llvmModule)), 198 typeTranslator(this->llvmModule->getContext()), 199 iface(module->getContext()) { 200 assert(satisfiesLLVMModule(mlirModule) && 201 "mlirModule should honor LLVM's module semantics."); 202 } 203 ModuleTranslation::~ModuleTranslation() { 204 if (ompBuilder) 205 ompBuilder->finalize(); 206 } 207 208 /// Get the SSA value passed to the current block from the terminator operation 209 /// of its predecessor. 210 static Value getPHISourceValue(Block *current, Block *pred, 211 unsigned numArguments, unsigned index) { 212 Operation &terminator = *pred->getTerminator(); 213 if (isa<LLVM::BrOp>(terminator)) 214 return terminator.getOperand(index); 215 216 SuccessorRange successors = terminator.getSuccessors(); 217 assert(std::adjacent_find(successors.begin(), successors.end()) == 218 successors.end() && 219 "successors with arguments in LLVM branches must be different blocks"); 220 (void)successors; 221 222 // For instructions that branch based on a condition value, we need to take 223 // the operands for the branch that was taken. 224 if (auto condBranchOp = dyn_cast<LLVM::CondBrOp>(terminator)) { 225 // For conditional branches, we take the operands from either the "true" or 226 // the "false" branch. 227 return condBranchOp.getSuccessor(0) == current 228 ? condBranchOp.trueDestOperands()[index] 229 : condBranchOp.falseDestOperands()[index]; 230 } 231 232 if (auto switchOp = dyn_cast<LLVM::SwitchOp>(terminator)) { 233 // For switches, we take the operands from either the default case, or from 234 // the case branch that was taken. 235 if (switchOp.defaultDestination() == current) 236 return switchOp.defaultOperands()[index]; 237 for (auto i : llvm::enumerate(switchOp.caseDestinations())) 238 if (i.value() == current) 239 return switchOp.getCaseOperands(i.index())[index]; 240 } 241 242 llvm_unreachable("only branch or switch operations can be terminators of a " 243 "block that has successors"); 244 } 245 246 /// Connect the PHI nodes to the results of preceding blocks. 247 void mlir::LLVM::detail::connectPHINodes(Region ®ion, 248 const ModuleTranslation &state) { 249 // Skip the first block, it cannot be branched to and its arguments correspond 250 // to the arguments of the LLVM function. 251 for (auto it = std::next(region.begin()), eit = region.end(); it != eit; 252 ++it) { 253 Block *bb = &*it; 254 llvm::BasicBlock *llvmBB = state.lookupBlock(bb); 255 auto phis = llvmBB->phis(); 256 auto numArguments = bb->getNumArguments(); 257 assert(numArguments == std::distance(phis.begin(), phis.end())); 258 for (auto &numberedPhiNode : llvm::enumerate(phis)) { 259 auto &phiNode = numberedPhiNode.value(); 260 unsigned index = numberedPhiNode.index(); 261 for (auto *pred : bb->getPredecessors()) { 262 // Find the LLVM IR block that contains the converted terminator 263 // instruction and use it in the PHI node. Note that this block is not 264 // necessarily the same as state.lookupBlock(pred), some operations 265 // (in particular, OpenMP operations using OpenMPIRBuilder) may have 266 // split the blocks. 267 llvm::Instruction *terminator = 268 state.lookupBranch(pred->getTerminator()); 269 assert(terminator && "missing the mapping for a terminator"); 270 phiNode.addIncoming( 271 state.lookupValue(getPHISourceValue(bb, pred, numArguments, index)), 272 terminator->getParent()); 273 } 274 } 275 } 276 } 277 278 /// Sort function blocks topologically. 279 SetVector<Block *> 280 mlir::LLVM::detail::getTopologicallySortedBlocks(Region ®ion) { 281 // For each block that has not been visited yet (i.e. that has no 282 // predecessors), add it to the list as well as its successors. 283 SetVector<Block *> blocks; 284 for (Block &b : region) { 285 if (blocks.count(&b) == 0) { 286 llvm::ReversePostOrderTraversal<Block *> traversal(&b); 287 blocks.insert(traversal.begin(), traversal.end()); 288 } 289 } 290 assert(blocks.size() == region.getBlocks().size() && 291 "some blocks are not sorted"); 292 293 return blocks; 294 } 295 296 llvm::Value *mlir::LLVM::detail::createIntrinsicCall( 297 llvm::IRBuilderBase &builder, llvm::Intrinsic::ID intrinsic, 298 ArrayRef<llvm::Value *> args, ArrayRef<llvm::Type *> tys) { 299 llvm::Module *module = builder.GetInsertBlock()->getModule(); 300 llvm::Function *fn = llvm::Intrinsic::getDeclaration(module, intrinsic, tys); 301 return builder.CreateCall(fn, args); 302 } 303 304 llvm::Value * 305 mlir::LLVM::detail::createNvvmIntrinsicCall(llvm::IRBuilderBase &builder, 306 llvm::Intrinsic::ID intrinsic, 307 ArrayRef<llvm::Value *> args) { 308 llvm::Module *module = builder.GetInsertBlock()->getModule(); 309 llvm::Function *fn; 310 if (llvm::Intrinsic::isOverloaded(intrinsic)) { 311 if (intrinsic != llvm::Intrinsic::nvvm_wmma_m16n16k16_mma_row_row_f16_f16 && 312 intrinsic != llvm::Intrinsic::nvvm_wmma_m16n16k16_mma_row_row_f32_f32) { 313 // NVVM load and store instrinsic names are overloaded on the 314 // source/destination pointer type. Pointer is the first argument in the 315 // corresponding NVVM Op. 316 fn = llvm::Intrinsic::getDeclaration(module, intrinsic, 317 {args[0]->getType()}); 318 } else { 319 fn = llvm::Intrinsic::getDeclaration(module, intrinsic, {}); 320 } 321 } else { 322 fn = llvm::Intrinsic::getDeclaration(module, intrinsic); 323 } 324 return builder.CreateCall(fn, args); 325 } 326 327 /// Given a single MLIR operation, create the corresponding LLVM IR operation 328 /// using the `builder`. 329 LogicalResult 330 ModuleTranslation::convertOperation(Operation &op, 331 llvm::IRBuilderBase &builder) { 332 const LLVMTranslationDialectInterface *opIface = iface.getInterfaceFor(&op); 333 if (!opIface) 334 return op.emitError("cannot be converted to LLVM IR: missing " 335 "`LLVMTranslationDialectInterface` registration for " 336 "dialect for op: ") 337 << op.getName(); 338 339 if (failed(opIface->convertOperation(&op, builder, *this))) 340 return op.emitError("LLVM Translation failed for operation: ") 341 << op.getName(); 342 343 return convertDialectAttributes(&op); 344 } 345 346 /// Convert block to LLVM IR. Unless `ignoreArguments` is set, emit PHI nodes 347 /// to define values corresponding to the MLIR block arguments. These nodes 348 /// are not connected to the source basic blocks, which may not exist yet. Uses 349 /// `builder` to construct the LLVM IR. Expects the LLVM IR basic block to have 350 /// been created for `bb` and included in the block mapping. Inserts new 351 /// instructions at the end of the block and leaves `builder` in a state 352 /// suitable for further insertion into the end of the block. 353 LogicalResult ModuleTranslation::convertBlock(Block &bb, bool ignoreArguments, 354 llvm::IRBuilderBase &builder) { 355 builder.SetInsertPoint(lookupBlock(&bb)); 356 auto *subprogram = builder.GetInsertBlock()->getParent()->getSubprogram(); 357 358 // Before traversing operations, make block arguments available through 359 // value remapping and PHI nodes, but do not add incoming edges for the PHI 360 // nodes just yet: those values may be defined by this or following blocks. 361 // This step is omitted if "ignoreArguments" is set. The arguments of the 362 // first block have been already made available through the remapping of 363 // LLVM function arguments. 364 if (!ignoreArguments) { 365 auto predecessors = bb.getPredecessors(); 366 unsigned numPredecessors = 367 std::distance(predecessors.begin(), predecessors.end()); 368 for (auto arg : bb.getArguments()) { 369 auto wrappedType = arg.getType(); 370 if (!isCompatibleType(wrappedType)) 371 return emitError(bb.front().getLoc(), 372 "block argument does not have an LLVM type"); 373 llvm::Type *type = convertType(wrappedType); 374 llvm::PHINode *phi = builder.CreatePHI(type, numPredecessors); 375 mapValue(arg, phi); 376 } 377 } 378 379 // Traverse operations. 380 for (auto &op : bb) { 381 // Set the current debug location within the builder. 382 builder.SetCurrentDebugLocation( 383 debugTranslation->translateLoc(op.getLoc(), subprogram)); 384 385 if (failed(convertOperation(op, builder))) 386 return failure(); 387 } 388 389 return success(); 390 } 391 392 /// A helper method to get the single Block in an operation honoring LLVM's 393 /// module requirements. 394 static Block &getModuleBody(Operation *module) { 395 return module->getRegion(0).front(); 396 } 397 398 /// A helper method to decide if a constant must not be set as a global variable 399 /// initializer. 400 static bool shouldDropGlobalInitializer(llvm::GlobalValue::LinkageTypes linkage, 401 llvm::Constant *cst) { 402 return (linkage == llvm::GlobalVariable::ExternalLinkage && 403 isa<llvm::UndefValue>(cst)) || 404 linkage == llvm::GlobalVariable::ExternalWeakLinkage; 405 } 406 407 /// Create named global variables that correspond to llvm.mlir.global 408 /// definitions. 409 LogicalResult ModuleTranslation::convertGlobals() { 410 for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) { 411 llvm::Type *type = convertType(op.getType()); 412 llvm::Constant *cst = llvm::UndefValue::get(type); 413 if (op.getValueOrNull()) { 414 // String attributes are treated separately because they cannot appear as 415 // in-function constants and are thus not supported by getLLVMConstant. 416 if (auto strAttr = op.getValueOrNull().dyn_cast_or_null<StringAttr>()) { 417 cst = llvm::ConstantDataArray::getString( 418 llvmModule->getContext(), strAttr.getValue(), /*AddNull=*/false); 419 type = cst->getType(); 420 } else if (!(cst = getLLVMConstant(type, op.getValueOrNull(), op.getLoc(), 421 *this))) { 422 return failure(); 423 } 424 } 425 426 auto linkage = convertLinkageToLLVM(op.linkage()); 427 auto addrSpace = op.addr_space(); 428 auto *var = new llvm::GlobalVariable( 429 *llvmModule, type, op.constant(), linkage, 430 shouldDropGlobalInitializer(linkage, cst) ? nullptr : cst, 431 op.sym_name(), 432 /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal, addrSpace); 433 434 if (op.unnamed_addr().hasValue()) 435 var->setUnnamedAddr(convertUnnamedAddrToLLVM(*op.unnamed_addr())); 436 437 if (op.section().hasValue()) 438 var->setSection(*op.section()); 439 440 Optional<uint64_t> alignment = op.alignment(); 441 if (alignment.hasValue()) 442 var->setAlignment(llvm::MaybeAlign(alignment.getValue())); 443 444 globalsMapping.try_emplace(op, var); 445 } 446 447 // Convert global variable bodies. This is done after all global variables 448 // have been created in LLVM IR because a global body may refer to another 449 // global or itself. So all global variables need to be mapped first. 450 for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) { 451 if (Block *initializer = op.getInitializerBlock()) { 452 llvm::IRBuilder<> builder(llvmModule->getContext()); 453 for (auto &op : initializer->without_terminator()) { 454 if (failed(convertOperation(op, builder)) || 455 !isa<llvm::Constant>(lookupValue(op.getResult(0)))) 456 return emitError(op.getLoc(), "unemittable constant value"); 457 } 458 ReturnOp ret = cast<ReturnOp>(initializer->getTerminator()); 459 llvm::Constant *cst = 460 cast<llvm::Constant>(lookupValue(ret.getOperand(0))); 461 auto *global = cast<llvm::GlobalVariable>(lookupGlobal(op)); 462 if (!shouldDropGlobalInitializer(global->getLinkage(), cst)) 463 global->setInitializer(cst); 464 } 465 } 466 467 return success(); 468 } 469 470 /// Attempts to add an attribute identified by `key`, optionally with the given 471 /// `value` to LLVM function `llvmFunc`. Reports errors at `loc` if any. If the 472 /// attribute has a kind known to LLVM IR, create the attribute of this kind, 473 /// otherwise keep it as a string attribute. Performs additional checks for 474 /// attributes known to have or not have a value in order to avoid assertions 475 /// inside LLVM upon construction. 476 static LogicalResult checkedAddLLVMFnAttribute(Location loc, 477 llvm::Function *llvmFunc, 478 StringRef key, 479 StringRef value = StringRef()) { 480 auto kind = llvm::Attribute::getAttrKindFromName(key); 481 if (kind == llvm::Attribute::None) { 482 llvmFunc->addFnAttr(key, value); 483 return success(); 484 } 485 486 if (llvm::Attribute::doesAttrKindHaveArgument(kind)) { 487 if (value.empty()) 488 return emitError(loc) << "LLVM attribute '" << key << "' expects a value"; 489 490 int result; 491 if (!value.getAsInteger(/*Radix=*/0, result)) 492 llvmFunc->addFnAttr( 493 llvm::Attribute::get(llvmFunc->getContext(), kind, result)); 494 else 495 llvmFunc->addFnAttr(key, value); 496 return success(); 497 } 498 499 if (!value.empty()) 500 return emitError(loc) << "LLVM attribute '" << key 501 << "' does not expect a value, found '" << value 502 << "'"; 503 504 llvmFunc->addFnAttr(kind); 505 return success(); 506 } 507 508 /// Attaches the attributes listed in the given array attribute to `llvmFunc`. 509 /// Reports error to `loc` if any and returns immediately. Expects `attributes` 510 /// to be an array attribute containing either string attributes, treated as 511 /// value-less LLVM attributes, or array attributes containing two string 512 /// attributes, with the first string being the name of the corresponding LLVM 513 /// attribute and the second string beings its value. Note that even integer 514 /// attributes are expected to have their values expressed as strings. 515 static LogicalResult 516 forwardPassthroughAttributes(Location loc, Optional<ArrayAttr> attributes, 517 llvm::Function *llvmFunc) { 518 if (!attributes) 519 return success(); 520 521 for (Attribute attr : *attributes) { 522 if (auto stringAttr = attr.dyn_cast<StringAttr>()) { 523 if (failed( 524 checkedAddLLVMFnAttribute(loc, llvmFunc, stringAttr.getValue()))) 525 return failure(); 526 continue; 527 } 528 529 auto arrayAttr = attr.dyn_cast<ArrayAttr>(); 530 if (!arrayAttr || arrayAttr.size() != 2) 531 return emitError(loc) 532 << "expected 'passthrough' to contain string or array attributes"; 533 534 auto keyAttr = arrayAttr[0].dyn_cast<StringAttr>(); 535 auto valueAttr = arrayAttr[1].dyn_cast<StringAttr>(); 536 if (!keyAttr || !valueAttr) 537 return emitError(loc) 538 << "expected arrays within 'passthrough' to contain two strings"; 539 540 if (failed(checkedAddLLVMFnAttribute(loc, llvmFunc, keyAttr.getValue(), 541 valueAttr.getValue()))) 542 return failure(); 543 } 544 return success(); 545 } 546 547 LogicalResult ModuleTranslation::convertOneFunction(LLVMFuncOp func) { 548 // Clear the block, branch value mappings, they are only relevant within one 549 // function. 550 blockMapping.clear(); 551 valueMapping.clear(); 552 branchMapping.clear(); 553 llvm::Function *llvmFunc = lookupFunction(func.getName()); 554 555 // Translate the debug information for this function. 556 debugTranslation->translate(func, *llvmFunc); 557 558 // Add function arguments to the value remapping table. 559 // If there was noalias info then we decorate each argument accordingly. 560 unsigned int argIdx = 0; 561 for (auto kvp : llvm::zip(func.getArguments(), llvmFunc->args())) { 562 llvm::Argument &llvmArg = std::get<1>(kvp); 563 BlockArgument mlirArg = std::get<0>(kvp); 564 565 if (auto attr = func.getArgAttrOfType<UnitAttr>( 566 argIdx, LLVMDialect::getNoAliasAttrName())) { 567 // NB: Attribute already verified to be boolean, so check if we can indeed 568 // attach the attribute to this argument, based on its type. 569 auto argTy = mlirArg.getType(); 570 if (!argTy.isa<LLVM::LLVMPointerType>()) 571 return func.emitError( 572 "llvm.noalias attribute attached to LLVM non-pointer argument"); 573 llvmArg.addAttr(llvm::Attribute::AttrKind::NoAlias); 574 } 575 576 if (auto attr = func.getArgAttrOfType<IntegerAttr>( 577 argIdx, LLVMDialect::getAlignAttrName())) { 578 // NB: Attribute already verified to be int, so check if we can indeed 579 // attach the attribute to this argument, based on its type. 580 auto argTy = mlirArg.getType(); 581 if (!argTy.isa<LLVM::LLVMPointerType>()) 582 return func.emitError( 583 "llvm.align attribute attached to LLVM non-pointer argument"); 584 llvmArg.addAttrs( 585 llvm::AttrBuilder().addAlignmentAttr(llvm::Align(attr.getInt()))); 586 } 587 588 if (auto attr = func.getArgAttrOfType<UnitAttr>(argIdx, "llvm.sret")) { 589 auto argTy = mlirArg.getType(); 590 if (!argTy.isa<LLVM::LLVMPointerType>()) 591 return func.emitError( 592 "llvm.sret attribute attached to LLVM non-pointer argument"); 593 llvmArg.addAttrs(llvm::AttrBuilder().addStructRetAttr( 594 llvmArg.getType()->getPointerElementType())); 595 } 596 597 if (auto attr = func.getArgAttrOfType<UnitAttr>(argIdx, "llvm.byval")) { 598 auto argTy = mlirArg.getType(); 599 if (!argTy.isa<LLVM::LLVMPointerType>()) 600 return func.emitError( 601 "llvm.byval attribute attached to LLVM non-pointer argument"); 602 llvmArg.addAttrs(llvm::AttrBuilder().addByValAttr( 603 llvmArg.getType()->getPointerElementType())); 604 } 605 606 mapValue(mlirArg, &llvmArg); 607 argIdx++; 608 } 609 610 // Check the personality and set it. 611 if (func.personality().hasValue()) { 612 llvm::Type *ty = llvm::Type::getInt8PtrTy(llvmFunc->getContext()); 613 if (llvm::Constant *pfunc = 614 getLLVMConstant(ty, func.personalityAttr(), func.getLoc(), *this)) 615 llvmFunc->setPersonalityFn(pfunc); 616 } 617 618 // First, create all blocks so we can jump to them. 619 llvm::LLVMContext &llvmContext = llvmFunc->getContext(); 620 for (auto &bb : func) { 621 auto *llvmBB = llvm::BasicBlock::Create(llvmContext); 622 llvmBB->insertInto(llvmFunc); 623 mapBlock(&bb, llvmBB); 624 } 625 626 // Then, convert blocks one by one in topological order to ensure defs are 627 // converted before uses. 628 auto blocks = detail::getTopologicallySortedBlocks(func.getBody()); 629 for (Block *bb : blocks) { 630 llvm::IRBuilder<> builder(llvmContext); 631 if (failed(convertBlock(*bb, bb->isEntryBlock(), builder))) 632 return failure(); 633 } 634 635 // After all blocks have been traversed and values mapped, connect the PHI 636 // nodes to the results of preceding blocks. 637 detail::connectPHINodes(func.getBody(), *this); 638 639 // Finally, convert dialect attributes attached to the function. 640 return convertDialectAttributes(func); 641 } 642 643 LogicalResult ModuleTranslation::convertDialectAttributes(Operation *op) { 644 for (NamedAttribute attribute : op->getDialectAttrs()) 645 if (failed(iface.amendOperation(op, attribute, *this))) 646 return failure(); 647 return success(); 648 } 649 650 /// Check whether the module contains only supported ops directly in its body. 651 static LogicalResult checkSupportedModuleOps(Operation *m) { 652 for (Operation &o : getModuleBody(m).getOperations()) 653 if (!isa<LLVM::LLVMFuncOp, LLVM::GlobalOp, LLVM::MetadataOp>(&o) && 654 !o.hasTrait<OpTrait::IsTerminator>()) 655 return o.emitOpError("unsupported module-level operation"); 656 return success(); 657 } 658 659 LogicalResult ModuleTranslation::convertFunctionSignatures() { 660 // Declare all functions first because there may be function calls that form a 661 // call graph with cycles, or global initializers that reference functions. 662 for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) { 663 llvm::FunctionCallee llvmFuncCst = llvmModule->getOrInsertFunction( 664 function.getName(), 665 cast<llvm::FunctionType>(convertType(function.getType()))); 666 llvm::Function *llvmFunc = cast<llvm::Function>(llvmFuncCst.getCallee()); 667 llvmFunc->setLinkage(convertLinkageToLLVM(function.linkage())); 668 mapFunction(function.getName(), llvmFunc); 669 670 // Forward the pass-through attributes to LLVM. 671 if (failed(forwardPassthroughAttributes(function.getLoc(), 672 function.passthrough(), llvmFunc))) 673 return failure(); 674 } 675 676 return success(); 677 } 678 679 LogicalResult ModuleTranslation::convertFunctions() { 680 // Convert functions. 681 for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) { 682 // Ignore external functions. 683 if (function.isExternal()) 684 continue; 685 686 if (failed(convertOneFunction(function))) 687 return failure(); 688 } 689 690 return success(); 691 } 692 693 llvm::MDNode * 694 ModuleTranslation::getAccessGroup(Operation &opInst, 695 SymbolRefAttr accessGroupRef) const { 696 auto metadataName = accessGroupRef.getRootReference(); 697 auto accessGroupName = accessGroupRef.getLeafReference(); 698 auto metadataOp = SymbolTable::lookupNearestSymbolFrom<LLVM::MetadataOp>( 699 opInst.getParentOp(), metadataName); 700 auto *accessGroupOp = 701 SymbolTable::lookupNearestSymbolFrom(metadataOp, accessGroupName); 702 return accessGroupMetadataMapping.lookup(accessGroupOp); 703 } 704 705 LogicalResult ModuleTranslation::createAccessGroupMetadata() { 706 mlirModule->walk([&](LLVM::MetadataOp metadatas) { 707 metadatas.walk([&](LLVM::AccessGroupMetadataOp op) { 708 llvm::LLVMContext &ctx = llvmModule->getContext(); 709 llvm::MDNode *accessGroup = llvm::MDNode::getDistinct(ctx, {}); 710 accessGroupMetadataMapping.insert({op, accessGroup}); 711 }); 712 }); 713 return success(); 714 } 715 716 void ModuleTranslation::setAccessGroupsMetadata(Operation *op, 717 llvm::Instruction *inst) { 718 auto accessGroups = 719 op->getAttrOfType<ArrayAttr>(LLVMDialect::getAccessGroupsAttrName()); 720 if (accessGroups && !accessGroups.empty()) { 721 llvm::Module *module = inst->getModule(); 722 SmallVector<llvm::Metadata *> metadatas; 723 for (SymbolRefAttr accessGroupRef : 724 accessGroups.getAsRange<SymbolRefAttr>()) 725 metadatas.push_back(getAccessGroup(*op, accessGroupRef)); 726 727 llvm::MDNode *unionMD = nullptr; 728 if (metadatas.size() == 1) 729 unionMD = llvm::cast<llvm::MDNode>(metadatas.front()); 730 else if (metadatas.size() >= 2) 731 unionMD = llvm::MDNode::get(module->getContext(), metadatas); 732 733 inst->setMetadata(module->getMDKindID("llvm.access.group"), unionMD); 734 } 735 } 736 737 llvm::Type *ModuleTranslation::convertType(Type type) { 738 return typeTranslator.translateType(type); 739 } 740 741 /// A helper to look up remapped operands in the value remapping table.` 742 SmallVector<llvm::Value *, 8> 743 ModuleTranslation::lookupValues(ValueRange values) { 744 SmallVector<llvm::Value *, 8> remapped; 745 remapped.reserve(values.size()); 746 for (Value v : values) 747 remapped.push_back(lookupValue(v)); 748 return remapped; 749 } 750 751 const llvm::DILocation * 752 ModuleTranslation::translateLoc(Location loc, llvm::DILocalScope *scope) { 753 return debugTranslation->translateLoc(loc, scope); 754 } 755 756 llvm::NamedMDNode * 757 ModuleTranslation::getOrInsertNamedModuleMetadata(StringRef name) { 758 return llvmModule->getOrInsertNamedMetadata(name); 759 } 760 761 void ModuleTranslation::StackFrame::anchor() {} 762 763 static std::unique_ptr<llvm::Module> 764 prepareLLVMModule(Operation *m, llvm::LLVMContext &llvmContext, 765 StringRef name) { 766 m->getContext()->getOrLoadDialect<LLVM::LLVMDialect>(); 767 auto llvmModule = std::make_unique<llvm::Module>(name, llvmContext); 768 if (auto dataLayoutAttr = 769 m->getAttr(LLVM::LLVMDialect::getDataLayoutAttrName())) 770 llvmModule->setDataLayout(dataLayoutAttr.cast<StringAttr>().getValue()); 771 if (auto targetTripleAttr = 772 m->getAttr(LLVM::LLVMDialect::getTargetTripleAttrName())) 773 llvmModule->setTargetTriple(targetTripleAttr.cast<StringAttr>().getValue()); 774 775 // Inject declarations for `malloc` and `free` functions that can be used in 776 // memref allocation/deallocation coming from standard ops lowering. 777 llvm::IRBuilder<> builder(llvmContext); 778 llvmModule->getOrInsertFunction("malloc", builder.getInt8PtrTy(), 779 builder.getInt64Ty()); 780 llvmModule->getOrInsertFunction("free", builder.getVoidTy(), 781 builder.getInt8PtrTy()); 782 783 return llvmModule; 784 } 785 786 std::unique_ptr<llvm::Module> 787 mlir::translateModuleToLLVMIR(Operation *module, llvm::LLVMContext &llvmContext, 788 StringRef name) { 789 if (!satisfiesLLVMModule(module)) 790 return nullptr; 791 if (failed(checkSupportedModuleOps(module))) 792 return nullptr; 793 std::unique_ptr<llvm::Module> llvmModule = 794 prepareLLVMModule(module, llvmContext, name); 795 796 LLVM::ensureDistinctSuccessors(module); 797 798 ModuleTranslation translator(module, std::move(llvmModule)); 799 if (failed(translator.convertFunctionSignatures())) 800 return nullptr; 801 if (failed(translator.convertGlobals())) 802 return nullptr; 803 if (failed(translator.createAccessGroupMetadata())) 804 return nullptr; 805 if (failed(translator.convertFunctions())) 806 return nullptr; 807 if (llvm::verifyModule(*translator.llvmModule, &llvm::errs())) 808 return nullptr; 809 810 return std::move(translator.llvmModule); 811 } 812