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