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 globalsMapping.try_emplace(op, var); 441 } 442 443 // Convert global variable bodies. This is done after all global variables 444 // have been created in LLVM IR because a global body may refer to another 445 // global or itself. So all global variables need to be mapped first. 446 for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) { 447 if (Block *initializer = op.getInitializerBlock()) { 448 llvm::IRBuilder<> builder(llvmModule->getContext()); 449 for (auto &op : initializer->without_terminator()) { 450 if (failed(convertOperation(op, builder)) || 451 !isa<llvm::Constant>(lookupValue(op.getResult(0)))) 452 return emitError(op.getLoc(), "unemittable constant value"); 453 } 454 ReturnOp ret = cast<ReturnOp>(initializer->getTerminator()); 455 llvm::Constant *cst = 456 cast<llvm::Constant>(lookupValue(ret.getOperand(0))); 457 auto *global = cast<llvm::GlobalVariable>(lookupGlobal(op)); 458 if (!shouldDropGlobalInitializer(global->getLinkage(), cst)) 459 global->setInitializer(cst); 460 } 461 } 462 463 return success(); 464 } 465 466 /// Attempts to add an attribute identified by `key`, optionally with the given 467 /// `value` to LLVM function `llvmFunc`. Reports errors at `loc` if any. If the 468 /// attribute has a kind known to LLVM IR, create the attribute of this kind, 469 /// otherwise keep it as a string attribute. Performs additional checks for 470 /// attributes known to have or not have a value in order to avoid assertions 471 /// inside LLVM upon construction. 472 static LogicalResult checkedAddLLVMFnAttribute(Location loc, 473 llvm::Function *llvmFunc, 474 StringRef key, 475 StringRef value = StringRef()) { 476 auto kind = llvm::Attribute::getAttrKindFromName(key); 477 if (kind == llvm::Attribute::None) { 478 llvmFunc->addFnAttr(key, value); 479 return success(); 480 } 481 482 if (llvm::Attribute::doesAttrKindHaveArgument(kind)) { 483 if (value.empty()) 484 return emitError(loc) << "LLVM attribute '" << key << "' expects a value"; 485 486 int result; 487 if (!value.getAsInteger(/*Radix=*/0, result)) 488 llvmFunc->addFnAttr( 489 llvm::Attribute::get(llvmFunc->getContext(), kind, result)); 490 else 491 llvmFunc->addFnAttr(key, value); 492 return success(); 493 } 494 495 if (!value.empty()) 496 return emitError(loc) << "LLVM attribute '" << key 497 << "' does not expect a value, found '" << value 498 << "'"; 499 500 llvmFunc->addFnAttr(kind); 501 return success(); 502 } 503 504 /// Attaches the attributes listed in the given array attribute to `llvmFunc`. 505 /// Reports error to `loc` if any and returns immediately. Expects `attributes` 506 /// to be an array attribute containing either string attributes, treated as 507 /// value-less LLVM attributes, or array attributes containing two string 508 /// attributes, with the first string being the name of the corresponding LLVM 509 /// attribute and the second string beings its value. Note that even integer 510 /// attributes are expected to have their values expressed as strings. 511 static LogicalResult 512 forwardPassthroughAttributes(Location loc, Optional<ArrayAttr> attributes, 513 llvm::Function *llvmFunc) { 514 if (!attributes) 515 return success(); 516 517 for (Attribute attr : *attributes) { 518 if (auto stringAttr = attr.dyn_cast<StringAttr>()) { 519 if (failed( 520 checkedAddLLVMFnAttribute(loc, llvmFunc, stringAttr.getValue()))) 521 return failure(); 522 continue; 523 } 524 525 auto arrayAttr = attr.dyn_cast<ArrayAttr>(); 526 if (!arrayAttr || arrayAttr.size() != 2) 527 return emitError(loc) 528 << "expected 'passthrough' to contain string or array attributes"; 529 530 auto keyAttr = arrayAttr[0].dyn_cast<StringAttr>(); 531 auto valueAttr = arrayAttr[1].dyn_cast<StringAttr>(); 532 if (!keyAttr || !valueAttr) 533 return emitError(loc) 534 << "expected arrays within 'passthrough' to contain two strings"; 535 536 if (failed(checkedAddLLVMFnAttribute(loc, llvmFunc, keyAttr.getValue(), 537 valueAttr.getValue()))) 538 return failure(); 539 } 540 return success(); 541 } 542 543 LogicalResult ModuleTranslation::convertOneFunction(LLVMFuncOp func) { 544 // Clear the block, branch value mappings, they are only relevant within one 545 // function. 546 blockMapping.clear(); 547 valueMapping.clear(); 548 branchMapping.clear(); 549 llvm::Function *llvmFunc = lookupFunction(func.getName()); 550 551 // Translate the debug information for this function. 552 debugTranslation->translate(func, *llvmFunc); 553 554 // Add function arguments to the value remapping table. 555 // If there was noalias info then we decorate each argument accordingly. 556 unsigned int argIdx = 0; 557 for (auto kvp : llvm::zip(func.getArguments(), llvmFunc->args())) { 558 llvm::Argument &llvmArg = std::get<1>(kvp); 559 BlockArgument mlirArg = std::get<0>(kvp); 560 561 if (auto attr = func.getArgAttrOfType<BoolAttr>( 562 argIdx, LLVMDialect::getNoAliasAttrName())) { 563 // NB: Attribute already verified to be boolean, so check if we can indeed 564 // attach the attribute to this argument, based on its type. 565 auto argTy = mlirArg.getType(); 566 if (!argTy.isa<LLVM::LLVMPointerType>()) 567 return func.emitError( 568 "llvm.noalias attribute attached to LLVM non-pointer argument"); 569 if (attr.getValue()) 570 llvmArg.addAttr(llvm::Attribute::AttrKind::NoAlias); 571 } 572 573 if (auto attr = func.getArgAttrOfType<IntegerAttr>( 574 argIdx, LLVMDialect::getAlignAttrName())) { 575 // NB: Attribute already verified to be int, so check if we can indeed 576 // attach the attribute to this argument, based on its type. 577 auto argTy = mlirArg.getType(); 578 if (!argTy.isa<LLVM::LLVMPointerType>()) 579 return func.emitError( 580 "llvm.align attribute attached to LLVM non-pointer argument"); 581 llvmArg.addAttrs( 582 llvm::AttrBuilder().addAlignmentAttr(llvm::Align(attr.getInt()))); 583 } 584 585 if (auto attr = func.getArgAttrOfType<UnitAttr>(argIdx, "llvm.sret")) { 586 auto argTy = mlirArg.getType(); 587 if (!argTy.isa<LLVM::LLVMPointerType>()) 588 return func.emitError( 589 "llvm.sret attribute attached to LLVM non-pointer argument"); 590 llvmArg.addAttrs(llvm::AttrBuilder().addStructRetAttr( 591 llvmArg.getType()->getPointerElementType())); 592 } 593 594 if (auto attr = func.getArgAttrOfType<UnitAttr>(argIdx, "llvm.byval")) { 595 auto argTy = mlirArg.getType(); 596 if (!argTy.isa<LLVM::LLVMPointerType>()) 597 return func.emitError( 598 "llvm.byval attribute attached to LLVM non-pointer argument"); 599 llvmArg.addAttrs(llvm::AttrBuilder().addByValAttr( 600 llvmArg.getType()->getPointerElementType())); 601 } 602 603 mapValue(mlirArg, &llvmArg); 604 argIdx++; 605 } 606 607 // Check the personality and set it. 608 if (func.personality().hasValue()) { 609 llvm::Type *ty = llvm::Type::getInt8PtrTy(llvmFunc->getContext()); 610 if (llvm::Constant *pfunc = 611 getLLVMConstant(ty, func.personalityAttr(), func.getLoc(), *this)) 612 llvmFunc->setPersonalityFn(pfunc); 613 } 614 615 // First, create all blocks so we can jump to them. 616 llvm::LLVMContext &llvmContext = llvmFunc->getContext(); 617 for (auto &bb : func) { 618 auto *llvmBB = llvm::BasicBlock::Create(llvmContext); 619 llvmBB->insertInto(llvmFunc); 620 mapBlock(&bb, llvmBB); 621 } 622 623 // Then, convert blocks one by one in topological order to ensure defs are 624 // converted before uses. 625 auto blocks = detail::getTopologicallySortedBlocks(func.getBody()); 626 for (Block *bb : blocks) { 627 llvm::IRBuilder<> builder(llvmContext); 628 if (failed(convertBlock(*bb, bb->isEntryBlock(), builder))) 629 return failure(); 630 } 631 632 // After all blocks have been traversed and values mapped, connect the PHI 633 // nodes to the results of preceding blocks. 634 detail::connectPHINodes(func.getBody(), *this); 635 636 // Finally, convert dialect attributes attached to the function. 637 return convertDialectAttributes(func); 638 } 639 640 LogicalResult ModuleTranslation::convertDialectAttributes(Operation *op) { 641 for (NamedAttribute attribute : op->getDialectAttrs()) 642 if (failed(iface.amendOperation(op, attribute, *this))) 643 return failure(); 644 return success(); 645 } 646 647 /// Check whether the module contains only supported ops directly in its body. 648 static LogicalResult checkSupportedModuleOps(Operation *m) { 649 for (Operation &o : getModuleBody(m).getOperations()) 650 if (!isa<LLVM::LLVMFuncOp, LLVM::GlobalOp, LLVM::MetadataOp>(&o) && 651 !o.hasTrait<OpTrait::IsTerminator>()) 652 return o.emitOpError("unsupported module-level operation"); 653 return success(); 654 } 655 656 LogicalResult ModuleTranslation::convertFunctionSignatures() { 657 // Declare all functions first because there may be function calls that form a 658 // call graph with cycles, or global initializers that reference functions. 659 for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) { 660 llvm::FunctionCallee llvmFuncCst = llvmModule->getOrInsertFunction( 661 function.getName(), 662 cast<llvm::FunctionType>(convertType(function.getType()))); 663 llvm::Function *llvmFunc = cast<llvm::Function>(llvmFuncCst.getCallee()); 664 llvmFunc->setLinkage(convertLinkageToLLVM(function.linkage())); 665 mapFunction(function.getName(), llvmFunc); 666 667 // Forward the pass-through attributes to LLVM. 668 if (failed(forwardPassthroughAttributes(function.getLoc(), 669 function.passthrough(), llvmFunc))) 670 return failure(); 671 } 672 673 return success(); 674 } 675 676 LogicalResult ModuleTranslation::convertFunctions() { 677 // Convert functions. 678 for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) { 679 // Ignore external functions. 680 if (function.isExternal()) 681 continue; 682 683 if (failed(convertOneFunction(function))) 684 return failure(); 685 } 686 687 return success(); 688 } 689 690 llvm::MDNode * 691 ModuleTranslation::getAccessGroup(Operation &opInst, 692 SymbolRefAttr accessGroupRef) const { 693 auto metadataName = accessGroupRef.getRootReference(); 694 auto accessGroupName = accessGroupRef.getLeafReference(); 695 auto metadataOp = SymbolTable::lookupNearestSymbolFrom<LLVM::MetadataOp>( 696 opInst.getParentOp(), metadataName); 697 auto *accessGroupOp = 698 SymbolTable::lookupNearestSymbolFrom(metadataOp, accessGroupName); 699 return accessGroupMetadataMapping.lookup(accessGroupOp); 700 } 701 702 LogicalResult ModuleTranslation::createAccessGroupMetadata() { 703 mlirModule->walk([&](LLVM::MetadataOp metadatas) { 704 metadatas.walk([&](LLVM::AccessGroupMetadataOp op) { 705 llvm::LLVMContext &ctx = llvmModule->getContext(); 706 llvm::MDNode *accessGroup = llvm::MDNode::getDistinct(ctx, {}); 707 accessGroupMetadataMapping.insert({op, accessGroup}); 708 }); 709 }); 710 return success(); 711 } 712 713 void ModuleTranslation::setAccessGroupsMetadata(Operation *op, 714 llvm::Instruction *inst) { 715 auto accessGroups = 716 op->getAttrOfType<ArrayAttr>(LLVMDialect::getAccessGroupsAttrName()); 717 if (accessGroups && !accessGroups.empty()) { 718 llvm::Module *module = inst->getModule(); 719 SmallVector<llvm::Metadata *> metadatas; 720 for (SymbolRefAttr accessGroupRef : 721 accessGroups.getAsRange<SymbolRefAttr>()) 722 metadatas.push_back(getAccessGroup(*op, accessGroupRef)); 723 724 llvm::MDNode *unionMD = nullptr; 725 if (metadatas.size() == 1) 726 unionMD = llvm::cast<llvm::MDNode>(metadatas.front()); 727 else if (metadatas.size() >= 2) 728 unionMD = llvm::MDNode::get(module->getContext(), metadatas); 729 730 inst->setMetadata(module->getMDKindID("llvm.access.group"), unionMD); 731 } 732 } 733 734 llvm::Type *ModuleTranslation::convertType(Type type) { 735 return typeTranslator.translateType(type); 736 } 737 738 /// A helper to look up remapped operands in the value remapping table.` 739 SmallVector<llvm::Value *, 8> 740 ModuleTranslation::lookupValues(ValueRange values) { 741 SmallVector<llvm::Value *, 8> remapped; 742 remapped.reserve(values.size()); 743 for (Value v : values) 744 remapped.push_back(lookupValue(v)); 745 return remapped; 746 } 747 748 const llvm::DILocation * 749 ModuleTranslation::translateLoc(Location loc, llvm::DILocalScope *scope) { 750 return debugTranslation->translateLoc(loc, scope); 751 } 752 753 llvm::NamedMDNode * 754 ModuleTranslation::getOrInsertNamedModuleMetadata(StringRef name) { 755 return llvmModule->getOrInsertNamedMetadata(name); 756 } 757 758 static std::unique_ptr<llvm::Module> 759 prepareLLVMModule(Operation *m, llvm::LLVMContext &llvmContext, 760 StringRef name) { 761 m->getContext()->getOrLoadDialect<LLVM::LLVMDialect>(); 762 auto llvmModule = std::make_unique<llvm::Module>(name, llvmContext); 763 if (auto dataLayoutAttr = 764 m->getAttr(LLVM::LLVMDialect::getDataLayoutAttrName())) 765 llvmModule->setDataLayout(dataLayoutAttr.cast<StringAttr>().getValue()); 766 if (auto targetTripleAttr = 767 m->getAttr(LLVM::LLVMDialect::getTargetTripleAttrName())) 768 llvmModule->setTargetTriple(targetTripleAttr.cast<StringAttr>().getValue()); 769 770 // Inject declarations for `malloc` and `free` functions that can be used in 771 // memref allocation/deallocation coming from standard ops lowering. 772 llvm::IRBuilder<> builder(llvmContext); 773 llvmModule->getOrInsertFunction("malloc", builder.getInt8PtrTy(), 774 builder.getInt64Ty()); 775 llvmModule->getOrInsertFunction("free", builder.getVoidTy(), 776 builder.getInt8PtrTy()); 777 778 return llvmModule; 779 } 780 781 std::unique_ptr<llvm::Module> 782 mlir::translateModuleToLLVMIR(Operation *module, llvm::LLVMContext &llvmContext, 783 StringRef name) { 784 if (!satisfiesLLVMModule(module)) 785 return nullptr; 786 if (failed(checkSupportedModuleOps(module))) 787 return nullptr; 788 std::unique_ptr<llvm::Module> llvmModule = 789 prepareLLVMModule(module, llvmContext, name); 790 791 LLVM::ensureDistinctSuccessors(module); 792 793 ModuleTranslation translator(module, std::move(llvmModule)); 794 if (failed(translator.convertFunctionSignatures())) 795 return nullptr; 796 if (failed(translator.convertGlobals())) 797 return nullptr; 798 if (failed(translator.createAccessGroupMetadata())) 799 return nullptr; 800 if (failed(translator.convertFunctions())) 801 return nullptr; 802 if (llvm::verifyModule(*translator.llvmModule, &llvm::errs())) 803 return nullptr; 804 805 return std::move(translator.llvmModule); 806 } 807