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