1 //===- ModuleImport.cpp - LLVM to MLIR conversion ---------------*- C++ -*-===// 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 import of an LLVM IR module into an LLVM dialect 10 // module. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "mlir/Target/LLVMIR/ModuleImport.h" 15 #include "mlir/IR/BuiltinAttributes.h" 16 #include "mlir/Target/LLVMIR/Import.h" 17 18 #include "AttrKindDetail.h" 19 #include "DataLayoutImporter.h" 20 #include "DebugImporter.h" 21 #include "LoopAnnotationImporter.h" 22 23 #include "mlir/Dialect/DLTI/DLTI.h" 24 #include "mlir/Dialect/LLVMIR/LLVMDialect.h" 25 #include "mlir/IR/Builders.h" 26 #include "mlir/IR/Matchers.h" 27 #include "mlir/Interfaces/DataLayoutInterfaces.h" 28 #include "mlir/Tools/mlir-translate/Translation.h" 29 30 #include "llvm/ADT/DepthFirstIterator.h" 31 #include "llvm/ADT/PostOrderIterator.h" 32 #include "llvm/ADT/ScopeExit.h" 33 #include "llvm/ADT/StringSet.h" 34 #include "llvm/ADT/TypeSwitch.h" 35 #include "llvm/IR/Comdat.h" 36 #include "llvm/IR/Constants.h" 37 #include "llvm/IR/InlineAsm.h" 38 #include "llvm/IR/InstIterator.h" 39 #include "llvm/IR/Instructions.h" 40 #include "llvm/IR/IntrinsicInst.h" 41 #include "llvm/IR/Metadata.h" 42 #include "llvm/IR/Operator.h" 43 #include "llvm/Support/ModRef.h" 44 45 using namespace mlir; 46 using namespace mlir::LLVM; 47 using namespace mlir::LLVM::detail; 48 49 #include "mlir/Dialect/LLVMIR/LLVMConversionEnumsFromLLVM.inc" 50 51 // Utility to print an LLVM value as a string for passing to emitError(). 52 // FIXME: Diagnostic should be able to natively handle types that have 53 // operator << (raw_ostream&) defined. 54 static std::string diag(const llvm::Value &value) { 55 std::string str; 56 llvm::raw_string_ostream os(str); 57 os << value; 58 return str; 59 } 60 61 // Utility to print an LLVM metadata node as a string for passing 62 // to emitError(). The module argument is needed to print the nodes 63 // canonically numbered. 64 static std::string diagMD(const llvm::Metadata *node, 65 const llvm::Module *module) { 66 std::string str; 67 llvm::raw_string_ostream os(str); 68 node->print(os, module, /*IsForDebug=*/true); 69 return str; 70 } 71 72 /// Returns the name of the global_ctors global variables. 73 static constexpr StringRef getGlobalCtorsVarName() { 74 return "llvm.global_ctors"; 75 } 76 77 /// Prefix used for symbols of nameless llvm globals. 78 static constexpr StringRef getNamelessGlobalPrefix() { 79 return "mlir.llvm.nameless_global"; 80 } 81 82 /// Returns the name of the global_dtors global variables. 83 static constexpr StringRef getGlobalDtorsVarName() { 84 return "llvm.global_dtors"; 85 } 86 87 /// Returns the symbol name for the module-level comdat operation. It must not 88 /// conflict with the user namespace. 89 static constexpr StringRef getGlobalComdatOpName() { 90 return "__llvm_global_comdat"; 91 } 92 93 /// Converts the sync scope identifier of `inst` to the string representation 94 /// necessary to build an atomic LLVM dialect operation. Returns the empty 95 /// string if the operation has either no sync scope or the default system-level 96 /// sync scope attached. The atomic operations only set their sync scope 97 /// attribute if they have a non-default sync scope attached. 98 static StringRef getLLVMSyncScope(llvm::Instruction *inst) { 99 std::optional<llvm::SyncScope::ID> syncScopeID = 100 llvm::getAtomicSyncScopeID(inst); 101 if (!syncScopeID) 102 return ""; 103 104 // Search the sync scope name for the given identifier. The default 105 // system-level sync scope thereby maps to the empty string. 106 SmallVector<StringRef> syncScopeName; 107 llvm::LLVMContext &llvmContext = inst->getContext(); 108 llvmContext.getSyncScopeNames(syncScopeName); 109 auto *it = llvm::find_if(syncScopeName, [&](StringRef name) { 110 return *syncScopeID == llvmContext.getOrInsertSyncScopeID(name); 111 }); 112 if (it != syncScopeName.end()) 113 return *it; 114 llvm_unreachable("incorrect sync scope identifier"); 115 } 116 117 /// Converts an array of unsigned indices to a signed integer position array. 118 static SmallVector<int64_t> getPositionFromIndices(ArrayRef<unsigned> indices) { 119 SmallVector<int64_t> position; 120 llvm::append_range(position, indices); 121 return position; 122 } 123 124 /// Converts the LLVM instructions that have a generated MLIR builder. Using a 125 /// static implementation method called from the module import ensures the 126 /// builders have to use the `moduleImport` argument and cannot directly call 127 /// import methods. As a result, both the intrinsic and the instruction MLIR 128 /// builders have to use the `moduleImport` argument and none of them has direct 129 /// access to the private module import methods. 130 static LogicalResult convertInstructionImpl(OpBuilder &odsBuilder, 131 llvm::Instruction *inst, 132 ModuleImport &moduleImport, 133 LLVMImportInterface &iface) { 134 // Copy the operands to an LLVM operands array reference for conversion. 135 SmallVector<llvm::Value *> operands(inst->operands()); 136 ArrayRef<llvm::Value *> llvmOperands(operands); 137 138 // Convert all instructions that provide an MLIR builder. 139 if (iface.isConvertibleInstruction(inst->getOpcode())) 140 return iface.convertInstruction(odsBuilder, inst, llvmOperands, 141 moduleImport); 142 // TODO: Implement the `convertInstruction` hooks in the 143 // `LLVMDialectLLVMIRImportInterface` and move the following include there. 144 #include "mlir/Dialect/LLVMIR/LLVMOpFromLLVMIRConversions.inc" 145 return failure(); 146 } 147 148 /// Get a topologically sorted list of blocks for the given basic blocks. 149 static SetVector<llvm::BasicBlock *> 150 getTopologicallySortedBlocks(ArrayRef<llvm::BasicBlock *> basicBlocks) { 151 SetVector<llvm::BasicBlock *> blocks; 152 for (llvm::BasicBlock *basicBlock : basicBlocks) { 153 if (!blocks.contains(basicBlock)) { 154 llvm::ReversePostOrderTraversal<llvm::BasicBlock *> traversal(basicBlock); 155 blocks.insert(traversal.begin(), traversal.end()); 156 } 157 } 158 assert(blocks.size() == basicBlocks.size() && "some blocks are not sorted"); 159 return blocks; 160 } 161 162 ModuleImport::ModuleImport(ModuleOp mlirModule, 163 std::unique_ptr<llvm::Module> llvmModule, 164 bool emitExpensiveWarnings, 165 bool importEmptyDICompositeTypes) 166 : builder(mlirModule->getContext()), context(mlirModule->getContext()), 167 mlirModule(mlirModule), llvmModule(std::move(llvmModule)), 168 iface(mlirModule->getContext()), 169 typeTranslator(*mlirModule->getContext()), 170 debugImporter(std::make_unique<DebugImporter>( 171 mlirModule, importEmptyDICompositeTypes)), 172 loopAnnotationImporter( 173 std::make_unique<LoopAnnotationImporter>(*this, builder)), 174 emitExpensiveWarnings(emitExpensiveWarnings) { 175 builder.setInsertionPointToStart(mlirModule.getBody()); 176 } 177 178 ComdatOp ModuleImport::getGlobalComdatOp() { 179 if (globalComdatOp) 180 return globalComdatOp; 181 182 OpBuilder::InsertionGuard guard(builder); 183 builder.setInsertionPointToEnd(mlirModule.getBody()); 184 globalComdatOp = 185 builder.create<ComdatOp>(mlirModule.getLoc(), getGlobalComdatOpName()); 186 globalInsertionOp = globalComdatOp; 187 return globalComdatOp; 188 } 189 190 LogicalResult ModuleImport::processTBAAMetadata(const llvm::MDNode *node) { 191 Location loc = mlirModule.getLoc(); 192 193 // If `node` is a valid TBAA root node, then return its optional identity 194 // string, otherwise return failure. 195 auto getIdentityIfRootNode = 196 [&](const llvm::MDNode *node) -> FailureOr<std::optional<StringRef>> { 197 // Root node, e.g.: 198 // !0 = !{!"Simple C/C++ TBAA"} 199 // !1 = !{} 200 if (node->getNumOperands() > 1) 201 return failure(); 202 // If the operand is MDString, then assume that this is a root node. 203 if (node->getNumOperands() == 1) 204 if (const auto *op0 = dyn_cast<const llvm::MDString>(node->getOperand(0))) 205 return std::optional<StringRef>{op0->getString()}; 206 return std::optional<StringRef>{}; 207 }; 208 209 // If `node` looks like a TBAA type descriptor metadata, 210 // then return true, if it is a valid node, and false otherwise. 211 // If it does not look like a TBAA type descriptor metadata, then 212 // return std::nullopt. 213 // If `identity` and `memberTypes/Offsets` are non-null, then they will 214 // contain the converted metadata operands for a valid TBAA node (i.e. when 215 // true is returned). 216 auto isTypeDescriptorNode = [&](const llvm::MDNode *node, 217 StringRef *identity = nullptr, 218 SmallVectorImpl<TBAAMemberAttr> *members = 219 nullptr) -> std::optional<bool> { 220 unsigned numOperands = node->getNumOperands(); 221 // Type descriptor, e.g.: 222 // !1 = !{!"int", !0, /*optional*/i64 0} /* scalar int type */ 223 // !2 = !{!"agg_t", !1, i64 0} /* struct agg_t { int x; } */ 224 if (numOperands < 2) 225 return std::nullopt; 226 227 // TODO: support "new" format (D41501) for type descriptors, 228 // where the first operand is an MDNode. 229 const auto *identityNode = 230 dyn_cast<const llvm::MDString>(node->getOperand(0)); 231 if (!identityNode) 232 return std::nullopt; 233 234 // This should be a type descriptor node. 235 if (identity) 236 *identity = identityNode->getString(); 237 238 for (unsigned pairNum = 0, e = numOperands / 2; pairNum < e; ++pairNum) { 239 const auto *memberNode = 240 dyn_cast<const llvm::MDNode>(node->getOperand(2 * pairNum + 1)); 241 if (!memberNode) { 242 emitError(loc) << "operand '" << 2 * pairNum + 1 << "' must be MDNode: " 243 << diagMD(node, llvmModule.get()); 244 return false; 245 } 246 int64_t offset = 0; 247 if (2 * pairNum + 2 >= numOperands) { 248 // Allow for optional 0 offset in 2-operand nodes. 249 if (numOperands != 2) { 250 emitError(loc) << "missing member offset: " 251 << diagMD(node, llvmModule.get()); 252 return false; 253 } 254 } else { 255 auto *offsetCI = llvm::mdconst::dyn_extract<llvm::ConstantInt>( 256 node->getOperand(2 * pairNum + 2)); 257 if (!offsetCI) { 258 emitError(loc) << "operand '" << 2 * pairNum + 2 259 << "' must be ConstantInt: " 260 << diagMD(node, llvmModule.get()); 261 return false; 262 } 263 offset = offsetCI->getZExtValue(); 264 } 265 266 if (members) 267 members->push_back(TBAAMemberAttr::get( 268 cast<TBAANodeAttr>(tbaaMapping.lookup(memberNode)), offset)); 269 } 270 271 return true; 272 }; 273 274 // If `node` looks like a TBAA access tag metadata, 275 // then return true, if it is a valid node, and false otherwise. 276 // If it does not look like a TBAA access tag metadata, then 277 // return std::nullopt. 278 // If the other arguments are non-null, then they will contain 279 // the converted metadata operands for a valid TBAA node (i.e. when true is 280 // returned). 281 auto isTagNode = [&](const llvm::MDNode *node, 282 TBAATypeDescriptorAttr *baseAttr = nullptr, 283 TBAATypeDescriptorAttr *accessAttr = nullptr, 284 int64_t *offset = nullptr, 285 bool *isConstant = nullptr) -> std::optional<bool> { 286 // Access tag, e.g.: 287 // !3 = !{!1, !1, i64 0} /* scalar int access */ 288 // !4 = !{!2, !1, i64 0} /* agg_t::x access */ 289 // 290 // Optional 4th argument is ConstantInt 0/1 identifying whether 291 // the location being accessed is "constant" (see for details: 292 // https://llvm.org/docs/LangRef.html#representation). 293 unsigned numOperands = node->getNumOperands(); 294 if (numOperands != 3 && numOperands != 4) 295 return std::nullopt; 296 const auto *baseMD = dyn_cast<const llvm::MDNode>(node->getOperand(0)); 297 const auto *accessMD = dyn_cast<const llvm::MDNode>(node->getOperand(1)); 298 auto *offsetCI = 299 llvm::mdconst::dyn_extract<llvm::ConstantInt>(node->getOperand(2)); 300 if (!baseMD || !accessMD || !offsetCI) 301 return std::nullopt; 302 // TODO: support "new" TBAA format, if needed (see D41501). 303 // In the "old" format the first operand of the access type 304 // metadata is MDString. We have to distinguish the formats, 305 // because access tags have the same structure, but different 306 // meaning for the operands. 307 if (accessMD->getNumOperands() < 1 || 308 !isa<llvm::MDString>(accessMD->getOperand(0))) 309 return std::nullopt; 310 bool isConst = false; 311 if (numOperands == 4) { 312 auto *isConstantCI = 313 llvm::mdconst::dyn_extract<llvm::ConstantInt>(node->getOperand(3)); 314 if (!isConstantCI) { 315 emitError(loc) << "operand '3' must be ConstantInt: " 316 << diagMD(node, llvmModule.get()); 317 return false; 318 } 319 isConst = isConstantCI->getValue()[0]; 320 } 321 if (baseAttr) 322 *baseAttr = cast<TBAATypeDescriptorAttr>(tbaaMapping.lookup(baseMD)); 323 if (accessAttr) 324 *accessAttr = cast<TBAATypeDescriptorAttr>(tbaaMapping.lookup(accessMD)); 325 if (offset) 326 *offset = offsetCI->getZExtValue(); 327 if (isConstant) 328 *isConstant = isConst; 329 return true; 330 }; 331 332 // Do a post-order walk over the TBAA Graph. Since a correct TBAA Graph is a 333 // DAG, a post-order walk guarantees that we convert any metadata node we 334 // depend on, prior to converting the current node. 335 DenseSet<const llvm::MDNode *> seen; 336 SmallVector<const llvm::MDNode *> workList; 337 workList.push_back(node); 338 while (!workList.empty()) { 339 const llvm::MDNode *current = workList.back(); 340 if (tbaaMapping.contains(current)) { 341 // Already converted. Just pop from the worklist. 342 workList.pop_back(); 343 continue; 344 } 345 346 // If any child of this node is not yet converted, don't pop the current 347 // node from the worklist but push the not-yet-converted children in the 348 // front of the worklist. 349 bool anyChildNotConverted = false; 350 for (const llvm::MDOperand &operand : current->operands()) 351 if (auto *childNode = dyn_cast_or_null<const llvm::MDNode>(operand.get())) 352 if (!tbaaMapping.contains(childNode)) { 353 workList.push_back(childNode); 354 anyChildNotConverted = true; 355 } 356 357 if (anyChildNotConverted) { 358 // If this is the second time we failed to convert an element in the 359 // worklist it must be because a child is dependent on it being converted 360 // and we have a cycle in the graph. Cycles are not allowed in TBAA 361 // graphs. 362 if (!seen.insert(current).second) 363 return emitError(loc) << "has cycle in TBAA graph: " 364 << diagMD(current, llvmModule.get()); 365 366 continue; 367 } 368 369 // Otherwise simply import the current node. 370 workList.pop_back(); 371 372 FailureOr<std::optional<StringRef>> rootNodeIdentity = 373 getIdentityIfRootNode(current); 374 if (succeeded(rootNodeIdentity)) { 375 StringAttr stringAttr = *rootNodeIdentity 376 ? builder.getStringAttr(**rootNodeIdentity) 377 : nullptr; 378 // The root nodes do not have operands, so we can create 379 // the TBAARootAttr on the first walk. 380 tbaaMapping.insert({current, builder.getAttr<TBAARootAttr>(stringAttr)}); 381 continue; 382 } 383 384 StringRef identity; 385 SmallVector<TBAAMemberAttr> members; 386 if (std::optional<bool> isValid = 387 isTypeDescriptorNode(current, &identity, &members)) { 388 assert(isValid.value() && "type descriptor node must be valid"); 389 390 tbaaMapping.insert({current, builder.getAttr<TBAATypeDescriptorAttr>( 391 identity, members)}); 392 continue; 393 } 394 395 TBAATypeDescriptorAttr baseAttr, accessAttr; 396 int64_t offset; 397 bool isConstant; 398 if (std::optional<bool> isValid = 399 isTagNode(current, &baseAttr, &accessAttr, &offset, &isConstant)) { 400 assert(isValid.value() && "access tag node must be valid"); 401 tbaaMapping.insert( 402 {current, builder.getAttr<TBAATagAttr>(baseAttr, accessAttr, offset, 403 isConstant)}); 404 continue; 405 } 406 407 return emitError(loc) << "unsupported TBAA node format: " 408 << diagMD(current, llvmModule.get()); 409 } 410 return success(); 411 } 412 413 LogicalResult 414 ModuleImport::processAccessGroupMetadata(const llvm::MDNode *node) { 415 Location loc = mlirModule.getLoc(); 416 if (failed(loopAnnotationImporter->translateAccessGroup(node, loc))) 417 return emitError(loc) << "unsupported access group node: " 418 << diagMD(node, llvmModule.get()); 419 return success(); 420 } 421 422 LogicalResult 423 ModuleImport::processAliasScopeMetadata(const llvm::MDNode *node) { 424 Location loc = mlirModule.getLoc(); 425 // Helper that verifies the node has a self reference operand. 426 auto verifySelfRef = [](const llvm::MDNode *node) { 427 return node->getNumOperands() != 0 && 428 node == dyn_cast<llvm::MDNode>(node->getOperand(0)); 429 }; 430 // Helper that verifies the given operand is a string or does not exist. 431 auto verifyDescription = [](const llvm::MDNode *node, unsigned idx) { 432 return idx >= node->getNumOperands() || 433 isa<llvm::MDString>(node->getOperand(idx)); 434 }; 435 // Helper that creates an alias scope domain attribute. 436 auto createAliasScopeDomainOp = [&](const llvm::MDNode *aliasDomain) { 437 StringAttr description = nullptr; 438 if (aliasDomain->getNumOperands() >= 2) 439 if (auto *operand = dyn_cast<llvm::MDString>(aliasDomain->getOperand(1))) 440 description = builder.getStringAttr(operand->getString()); 441 return builder.getAttr<AliasScopeDomainAttr>( 442 DistinctAttr::create(builder.getUnitAttr()), description); 443 }; 444 445 // Collect the alias scopes and domains to translate them. 446 for (const llvm::MDOperand &operand : node->operands()) { 447 if (const auto *scope = dyn_cast<llvm::MDNode>(operand)) { 448 llvm::AliasScopeNode aliasScope(scope); 449 const llvm::MDNode *domain = aliasScope.getDomain(); 450 451 // Verify the scope node points to valid scope metadata which includes 452 // verifying its domain. Perform the verification before looking it up in 453 // the alias scope mapping since it could have been inserted as a domain 454 // node before. 455 if (!verifySelfRef(scope) || !domain || !verifyDescription(scope, 2)) 456 return emitError(loc) << "unsupported alias scope node: " 457 << diagMD(scope, llvmModule.get()); 458 if (!verifySelfRef(domain) || !verifyDescription(domain, 1)) 459 return emitError(loc) << "unsupported alias domain node: " 460 << diagMD(domain, llvmModule.get()); 461 462 if (aliasScopeMapping.contains(scope)) 463 continue; 464 465 // Convert the domain metadata node if it has not been translated before. 466 auto it = aliasScopeMapping.find(aliasScope.getDomain()); 467 if (it == aliasScopeMapping.end()) { 468 auto aliasScopeDomainOp = createAliasScopeDomainOp(domain); 469 it = aliasScopeMapping.try_emplace(domain, aliasScopeDomainOp).first; 470 } 471 472 // Convert the scope metadata node if it has not been converted before. 473 StringAttr description = nullptr; 474 if (!aliasScope.getName().empty()) 475 description = builder.getStringAttr(aliasScope.getName()); 476 auto aliasScopeOp = builder.getAttr<AliasScopeAttr>( 477 DistinctAttr::create(builder.getUnitAttr()), 478 cast<AliasScopeDomainAttr>(it->second), description); 479 aliasScopeMapping.try_emplace(aliasScope.getNode(), aliasScopeOp); 480 } 481 } 482 return success(); 483 } 484 485 FailureOr<SmallVector<AliasScopeAttr>> 486 ModuleImport::lookupAliasScopeAttrs(const llvm::MDNode *node) const { 487 SmallVector<AliasScopeAttr> aliasScopes; 488 aliasScopes.reserve(node->getNumOperands()); 489 for (const llvm::MDOperand &operand : node->operands()) { 490 auto *node = cast<llvm::MDNode>(operand.get()); 491 aliasScopes.push_back( 492 dyn_cast_or_null<AliasScopeAttr>(aliasScopeMapping.lookup(node))); 493 } 494 // Return failure if one of the alias scope lookups failed. 495 if (llvm::is_contained(aliasScopes, nullptr)) 496 return failure(); 497 return aliasScopes; 498 } 499 500 void ModuleImport::addDebugIntrinsic(llvm::CallInst *intrinsic) { 501 debugIntrinsics.insert(intrinsic); 502 } 503 504 LogicalResult ModuleImport::convertLinkerOptionsMetadata() { 505 for (const llvm::NamedMDNode &named : llvmModule->named_metadata()) { 506 if (named.getName() != "llvm.linker.options") 507 continue; 508 // llvm.linker.options operands are lists of strings. 509 for (const llvm::MDNode *node : named.operands()) { 510 SmallVector<StringRef> options; 511 options.reserve(node->getNumOperands()); 512 for (const llvm::MDOperand &option : node->operands()) 513 options.push_back(cast<llvm::MDString>(option)->getString()); 514 builder.create<LLVM::LinkerOptionsOp>(mlirModule.getLoc(), 515 builder.getStrArrayAttr(options)); 516 } 517 } 518 return success(); 519 } 520 521 LogicalResult ModuleImport::convertIdentMetadata() { 522 for (const llvm::NamedMDNode &named : llvmModule->named_metadata()) { 523 // llvm.ident should have a single operand. That operand is itself an 524 // MDNode with a single string operand. 525 if (named.getName() != LLVMDialect::getIdentAttrName()) 526 continue; 527 528 if (named.getNumOperands() == 1) 529 if (auto *md = dyn_cast<llvm::MDNode>(named.getOperand(0))) 530 if (md->getNumOperands() == 1) 531 if (auto *mdStr = dyn_cast<llvm::MDString>(md->getOperand(0))) 532 mlirModule->setAttr(LLVMDialect::getIdentAttrName(), 533 builder.getStringAttr(mdStr->getString())); 534 } 535 return success(); 536 } 537 538 LogicalResult ModuleImport::convertCommandlineMetadata() { 539 for (const llvm::NamedMDNode &nmd : llvmModule->named_metadata()) { 540 // llvm.commandline should have a single operand. That operand is itself an 541 // MDNode with a single string operand. 542 if (nmd.getName() != LLVMDialect::getCommandlineAttrName()) 543 continue; 544 545 if (nmd.getNumOperands() == 1) 546 if (auto *md = dyn_cast<llvm::MDNode>(nmd.getOperand(0))) 547 if (md->getNumOperands() == 1) 548 if (auto *mdStr = dyn_cast<llvm::MDString>(md->getOperand(0))) 549 mlirModule->setAttr(LLVMDialect::getCommandlineAttrName(), 550 builder.getStringAttr(mdStr->getString())); 551 } 552 return success(); 553 } 554 555 LogicalResult ModuleImport::convertMetadata() { 556 OpBuilder::InsertionGuard guard(builder); 557 builder.setInsertionPointToEnd(mlirModule.getBody()); 558 for (const llvm::Function &func : llvmModule->functions()) { 559 for (const llvm::Instruction &inst : llvm::instructions(func)) { 560 // Convert access group metadata nodes. 561 if (llvm::MDNode *node = 562 inst.getMetadata(llvm::LLVMContext::MD_access_group)) 563 if (failed(processAccessGroupMetadata(node))) 564 return failure(); 565 566 // Convert alias analysis metadata nodes. 567 llvm::AAMDNodes aliasAnalysisNodes = inst.getAAMetadata(); 568 if (!aliasAnalysisNodes) 569 continue; 570 if (aliasAnalysisNodes.TBAA) 571 if (failed(processTBAAMetadata(aliasAnalysisNodes.TBAA))) 572 return failure(); 573 if (aliasAnalysisNodes.Scope) 574 if (failed(processAliasScopeMetadata(aliasAnalysisNodes.Scope))) 575 return failure(); 576 if (aliasAnalysisNodes.NoAlias) 577 if (failed(processAliasScopeMetadata(aliasAnalysisNodes.NoAlias))) 578 return failure(); 579 } 580 } 581 if (failed(convertLinkerOptionsMetadata())) 582 return failure(); 583 if (failed(convertIdentMetadata())) 584 return failure(); 585 if (failed(convertCommandlineMetadata())) 586 return failure(); 587 return success(); 588 } 589 590 void ModuleImport::processComdat(const llvm::Comdat *comdat) { 591 if (comdatMapping.contains(comdat)) 592 return; 593 594 ComdatOp comdatOp = getGlobalComdatOp(); 595 OpBuilder::InsertionGuard guard(builder); 596 builder.setInsertionPointToEnd(&comdatOp.getBody().back()); 597 auto selectorOp = builder.create<ComdatSelectorOp>( 598 mlirModule.getLoc(), comdat->getName(), 599 convertComdatFromLLVM(comdat->getSelectionKind())); 600 auto symbolRef = 601 SymbolRefAttr::get(builder.getContext(), getGlobalComdatOpName(), 602 FlatSymbolRefAttr::get(selectorOp.getSymNameAttr())); 603 comdatMapping.try_emplace(comdat, symbolRef); 604 } 605 606 LogicalResult ModuleImport::convertComdats() { 607 for (llvm::GlobalVariable &globalVar : llvmModule->globals()) 608 if (globalVar.hasComdat()) 609 processComdat(globalVar.getComdat()); 610 for (llvm::Function &func : llvmModule->functions()) 611 if (func.hasComdat()) 612 processComdat(func.getComdat()); 613 return success(); 614 } 615 616 LogicalResult ModuleImport::convertGlobals() { 617 for (llvm::GlobalVariable &globalVar : llvmModule->globals()) { 618 if (globalVar.getName() == getGlobalCtorsVarName() || 619 globalVar.getName() == getGlobalDtorsVarName()) { 620 if (failed(convertGlobalCtorsAndDtors(&globalVar))) { 621 return emitError(UnknownLoc::get(context)) 622 << "unhandled global variable: " << diag(globalVar); 623 } 624 continue; 625 } 626 if (failed(convertGlobal(&globalVar))) { 627 return emitError(UnknownLoc::get(context)) 628 << "unhandled global variable: " << diag(globalVar); 629 } 630 } 631 return success(); 632 } 633 634 LogicalResult ModuleImport::convertDataLayout() { 635 Location loc = mlirModule.getLoc(); 636 DataLayoutImporter dataLayoutImporter(context, llvmModule->getDataLayout()); 637 if (!dataLayoutImporter.getDataLayout()) 638 return emitError(loc, "cannot translate data layout: ") 639 << dataLayoutImporter.getLastToken(); 640 641 for (StringRef token : dataLayoutImporter.getUnhandledTokens()) 642 emitWarning(loc, "unhandled data layout token: ") << token; 643 644 mlirModule->setAttr(DLTIDialect::kDataLayoutAttrName, 645 dataLayoutImporter.getDataLayout()); 646 return success(); 647 } 648 649 LogicalResult ModuleImport::convertFunctions() { 650 for (llvm::Function &func : llvmModule->functions()) 651 if (failed(processFunction(&func))) 652 return failure(); 653 return success(); 654 } 655 656 void ModuleImport::setNonDebugMetadataAttrs(llvm::Instruction *inst, 657 Operation *op) { 658 SmallVector<std::pair<unsigned, llvm::MDNode *>> allMetadata; 659 inst->getAllMetadataOtherThanDebugLoc(allMetadata); 660 for (auto &[kind, node] : allMetadata) { 661 if (!iface.isConvertibleMetadata(kind)) 662 continue; 663 if (failed(iface.setMetadataAttrs(builder, kind, node, op, *this))) { 664 if (emitExpensiveWarnings) { 665 Location loc = debugImporter->translateLoc(inst->getDebugLoc()); 666 emitWarning(loc) << "unhandled metadata: " 667 << diagMD(node, llvmModule.get()) << " on " 668 << diag(*inst); 669 } 670 } 671 } 672 } 673 674 void ModuleImport::setIntegerOverflowFlags(llvm::Instruction *inst, 675 Operation *op) const { 676 auto iface = cast<IntegerOverflowFlagsInterface>(op); 677 678 IntegerOverflowFlags value = {}; 679 value = bitEnumSet(value, IntegerOverflowFlags::nsw, inst->hasNoSignedWrap()); 680 value = 681 bitEnumSet(value, IntegerOverflowFlags::nuw, inst->hasNoUnsignedWrap()); 682 683 iface.setOverflowFlags(value); 684 } 685 686 void ModuleImport::setFastmathFlagsAttr(llvm::Instruction *inst, 687 Operation *op) const { 688 auto iface = cast<FastmathFlagsInterface>(op); 689 690 // Even if the imported operation implements the fastmath interface, the 691 // original instruction may not have fastmath flags set. Exit if an 692 // instruction, such as a non floating-point function call, does not have 693 // fastmath flags. 694 if (!isa<llvm::FPMathOperator>(inst)) 695 return; 696 llvm::FastMathFlags flags = inst->getFastMathFlags(); 697 698 // Set the fastmath bits flag-by-flag. 699 FastmathFlags value = {}; 700 value = bitEnumSet(value, FastmathFlags::nnan, flags.noNaNs()); 701 value = bitEnumSet(value, FastmathFlags::ninf, flags.noInfs()); 702 value = bitEnumSet(value, FastmathFlags::nsz, flags.noSignedZeros()); 703 value = bitEnumSet(value, FastmathFlags::arcp, flags.allowReciprocal()); 704 value = bitEnumSet(value, FastmathFlags::contract, flags.allowContract()); 705 value = bitEnumSet(value, FastmathFlags::afn, flags.approxFunc()); 706 value = bitEnumSet(value, FastmathFlags::reassoc, flags.allowReassoc()); 707 FastmathFlagsAttr attr = FastmathFlagsAttr::get(builder.getContext(), value); 708 iface->setAttr(iface.getFastmathAttrName(), attr); 709 } 710 711 /// Returns if `type` is a scalar integer or floating-point type. 712 static bool isScalarType(Type type) { 713 return isa<IntegerType, FloatType>(type); 714 } 715 716 /// Returns `type` if it is a builtin integer or floating-point vector type that 717 /// can be used to create an attribute or nullptr otherwise. If provided, 718 /// `arrayShape` is added to the shape of the vector to create an attribute that 719 /// matches an array of vectors. 720 static Type getVectorTypeForAttr(Type type, ArrayRef<int64_t> arrayShape = {}) { 721 if (!LLVM::isCompatibleVectorType(type)) 722 return {}; 723 724 llvm::ElementCount numElements = LLVM::getVectorNumElements(type); 725 if (numElements.isScalable()) { 726 emitError(UnknownLoc::get(type.getContext())) 727 << "scalable vectors not supported"; 728 return {}; 729 } 730 731 // An LLVM dialect vector can only contain scalars. 732 Type elementType = LLVM::getVectorElementType(type); 733 if (!isScalarType(elementType)) 734 return {}; 735 736 SmallVector<int64_t> shape(arrayShape); 737 shape.push_back(numElements.getKnownMinValue()); 738 return VectorType::get(shape, elementType); 739 } 740 741 Type ModuleImport::getBuiltinTypeForAttr(Type type) { 742 if (!type) 743 return {}; 744 745 // Return builtin integer and floating-point types as is. 746 if (isScalarType(type)) 747 return type; 748 749 // Return builtin vectors of integer and floating-point types as is. 750 if (Type vectorType = getVectorTypeForAttr(type)) 751 return vectorType; 752 753 // Multi-dimensional array types are converted to tensors or vectors, 754 // depending on the innermost type being a scalar or a vector. 755 SmallVector<int64_t> arrayShape; 756 while (auto arrayType = dyn_cast<LLVMArrayType>(type)) { 757 arrayShape.push_back(arrayType.getNumElements()); 758 type = arrayType.getElementType(); 759 } 760 if (isScalarType(type)) 761 return RankedTensorType::get(arrayShape, type); 762 return getVectorTypeForAttr(type, arrayShape); 763 } 764 765 /// Returns an integer or float attribute for the provided scalar constant 766 /// `constScalar` or nullptr if the conversion fails. 767 static TypedAttr getScalarConstantAsAttr(OpBuilder &builder, 768 llvm::Constant *constScalar) { 769 MLIRContext *context = builder.getContext(); 770 771 // Convert scalar intergers. 772 if (auto *constInt = dyn_cast<llvm::ConstantInt>(constScalar)) { 773 return builder.getIntegerAttr( 774 IntegerType::get(context, constInt->getBitWidth()), 775 constInt->getValue()); 776 } 777 778 // Convert scalar floats. 779 if (auto *constFloat = dyn_cast<llvm::ConstantFP>(constScalar)) { 780 llvm::Type *type = constFloat->getType(); 781 FloatType floatType = 782 type->isBFloatTy() 783 ? FloatType::getBF16(context) 784 : LLVM::detail::getFloatType(context, type->getScalarSizeInBits()); 785 if (!floatType) { 786 emitError(UnknownLoc::get(builder.getContext())) 787 << "unexpected floating-point type"; 788 return {}; 789 } 790 return builder.getFloatAttr(floatType, constFloat->getValueAPF()); 791 } 792 return {}; 793 } 794 795 /// Returns an integer or float attribute array for the provided constant 796 /// sequence `constSequence` or nullptr if the conversion fails. 797 static SmallVector<Attribute> 798 getSequenceConstantAsAttrs(OpBuilder &builder, 799 llvm::ConstantDataSequential *constSequence) { 800 SmallVector<Attribute> elementAttrs; 801 elementAttrs.reserve(constSequence->getNumElements()); 802 for (auto idx : llvm::seq<int64_t>(0, constSequence->getNumElements())) { 803 llvm::Constant *constElement = constSequence->getElementAsConstant(idx); 804 elementAttrs.push_back(getScalarConstantAsAttr(builder, constElement)); 805 } 806 return elementAttrs; 807 } 808 809 Attribute ModuleImport::getConstantAsAttr(llvm::Constant *constant) { 810 // Convert scalar constants. 811 if (Attribute scalarAttr = getScalarConstantAsAttr(builder, constant)) 812 return scalarAttr; 813 814 // Convert function references. 815 if (auto *func = dyn_cast<llvm::Function>(constant)) 816 return SymbolRefAttr::get(builder.getContext(), func->getName()); 817 818 // Returns the static shape of the provided type if possible. 819 auto getConstantShape = [&](llvm::Type *type) { 820 return llvm::dyn_cast_if_present<ShapedType>( 821 getBuiltinTypeForAttr(convertType(type))); 822 }; 823 824 // Convert one-dimensional constant arrays or vectors that store 1/2/4/8-byte 825 // integer or half/bfloat/float/double values. 826 if (auto *constArray = dyn_cast<llvm::ConstantDataSequential>(constant)) { 827 if (constArray->isString()) 828 return builder.getStringAttr(constArray->getAsString()); 829 auto shape = getConstantShape(constArray->getType()); 830 if (!shape) 831 return {}; 832 // Convert splat constants to splat elements attributes. 833 auto *constVector = dyn_cast<llvm::ConstantDataVector>(constant); 834 if (constVector && constVector->isSplat()) { 835 // A vector is guaranteed to have at least size one. 836 Attribute splatAttr = getScalarConstantAsAttr( 837 builder, constVector->getElementAsConstant(0)); 838 return SplatElementsAttr::get(shape, splatAttr); 839 } 840 // Convert non-splat constants to dense elements attributes. 841 SmallVector<Attribute> elementAttrs = 842 getSequenceConstantAsAttrs(builder, constArray); 843 return DenseElementsAttr::get(shape, elementAttrs); 844 } 845 846 // Convert multi-dimensional constant aggregates that store all kinds of 847 // integer and floating-point types. 848 if (auto *constAggregate = dyn_cast<llvm::ConstantAggregate>(constant)) { 849 auto shape = getConstantShape(constAggregate->getType()); 850 if (!shape) 851 return {}; 852 // Collect the aggregate elements in depths first order. 853 SmallVector<Attribute> elementAttrs; 854 SmallVector<llvm::Constant *> workList = {constAggregate}; 855 while (!workList.empty()) { 856 llvm::Constant *current = workList.pop_back_val(); 857 // Append any nested aggregates in reverse order to ensure the head 858 // element of the nested aggregates is at the back of the work list. 859 if (auto *constAggregate = dyn_cast<llvm::ConstantAggregate>(current)) { 860 for (auto idx : 861 reverse(llvm::seq<int64_t>(0, constAggregate->getNumOperands()))) 862 workList.push_back(constAggregate->getAggregateElement(idx)); 863 continue; 864 } 865 // Append the elements of nested constant arrays or vectors that store 866 // 1/2/4/8-byte integer or half/bfloat/float/double values. 867 if (auto *constArray = dyn_cast<llvm::ConstantDataSequential>(current)) { 868 SmallVector<Attribute> attrs = 869 getSequenceConstantAsAttrs(builder, constArray); 870 elementAttrs.append(attrs.begin(), attrs.end()); 871 continue; 872 } 873 // Append nested scalar constants that store all kinds of integer and 874 // floating-point types. 875 if (Attribute scalarAttr = getScalarConstantAsAttr(builder, current)) { 876 elementAttrs.push_back(scalarAttr); 877 continue; 878 } 879 // Bail if the aggregate contains a unsupported constant type such as a 880 // constant expression. 881 return {}; 882 } 883 return DenseElementsAttr::get(shape, elementAttrs); 884 } 885 886 // Convert zero aggregates. 887 if (auto *constZero = dyn_cast<llvm::ConstantAggregateZero>(constant)) { 888 auto shape = llvm::dyn_cast_if_present<ShapedType>( 889 getBuiltinTypeForAttr(convertType(constZero->getType()))); 890 if (!shape) 891 return {}; 892 // Convert zero aggregates with a static shape to splat elements attributes. 893 Attribute splatAttr = builder.getZeroAttr(shape.getElementType()); 894 assert(splatAttr && "expected non-null zero attribute for scalar types"); 895 return SplatElementsAttr::get(shape, splatAttr); 896 } 897 return {}; 898 } 899 900 LogicalResult ModuleImport::convertGlobal(llvm::GlobalVariable *globalVar) { 901 // Insert the global after the last one or at the start of the module. 902 OpBuilder::InsertionGuard guard(builder); 903 if (!globalInsertionOp) 904 builder.setInsertionPointToStart(mlirModule.getBody()); 905 else 906 builder.setInsertionPointAfter(globalInsertionOp); 907 908 Attribute valueAttr; 909 if (globalVar->hasInitializer()) 910 valueAttr = getConstantAsAttr(globalVar->getInitializer()); 911 Type type = convertType(globalVar->getValueType()); 912 913 uint64_t alignment = 0; 914 llvm::MaybeAlign maybeAlign = globalVar->getAlign(); 915 if (maybeAlign.has_value()) { 916 llvm::Align align = *maybeAlign; 917 alignment = align.value(); 918 } 919 920 // Get the global expression associated with this global variable and convert 921 // it. 922 DIGlobalVariableExpressionAttr globalExpressionAttr; 923 SmallVector<llvm::DIGlobalVariableExpression *> globalExpressions; 924 globalVar->getDebugInfo(globalExpressions); 925 926 // There should only be a single global expression. 927 if (!globalExpressions.empty()) 928 globalExpressionAttr = 929 debugImporter->translateGlobalVariableExpression(globalExpressions[0]); 930 931 // Workaround to support LLVM's nameless globals. MLIR, in contrast to LLVM, 932 // always requires a symbol name. 933 SmallString<128> globalName(globalVar->getName()); 934 if (globalName.empty()) { 935 // Make sure the symbol name does not clash with an existing symbol. 936 globalName = SymbolTable::generateSymbolName<128>( 937 getNamelessGlobalPrefix(), 938 [this](StringRef newName) { 939 return llvmModule->getNamedValue(newName); 940 }, 941 namelessGlobalId); 942 namelessGlobals[globalVar] = FlatSymbolRefAttr::get(context, globalName); 943 } 944 GlobalOp globalOp = builder.create<GlobalOp>( 945 mlirModule.getLoc(), type, globalVar->isConstant(), 946 convertLinkageFromLLVM(globalVar->getLinkage()), StringRef(globalName), 947 valueAttr, alignment, /*addr_space=*/globalVar->getAddressSpace(), 948 /*dso_local=*/globalVar->isDSOLocal(), 949 /*thread_local=*/globalVar->isThreadLocal(), /*comdat=*/SymbolRefAttr(), 950 /*attrs=*/ArrayRef<NamedAttribute>(), /*dbgExpr=*/globalExpressionAttr); 951 globalInsertionOp = globalOp; 952 953 if (globalVar->hasInitializer() && !valueAttr) { 954 clearRegionState(); 955 Block *block = builder.createBlock(&globalOp.getInitializerRegion()); 956 setConstantInsertionPointToStart(block); 957 FailureOr<Value> initializer = 958 convertConstantExpr(globalVar->getInitializer()); 959 if (failed(initializer)) 960 return failure(); 961 builder.create<ReturnOp>(globalOp.getLoc(), *initializer); 962 } 963 if (globalVar->hasAtLeastLocalUnnamedAddr()) { 964 globalOp.setUnnamedAddr( 965 convertUnnamedAddrFromLLVM(globalVar->getUnnamedAddr())); 966 } 967 if (globalVar->hasSection()) 968 globalOp.setSection(globalVar->getSection()); 969 globalOp.setVisibility_( 970 convertVisibilityFromLLVM(globalVar->getVisibility())); 971 972 if (globalVar->hasComdat()) 973 globalOp.setComdatAttr(comdatMapping.lookup(globalVar->getComdat())); 974 975 return success(); 976 } 977 978 LogicalResult 979 ModuleImport::convertGlobalCtorsAndDtors(llvm::GlobalVariable *globalVar) { 980 if (!globalVar->hasInitializer() || !globalVar->hasAppendingLinkage()) 981 return failure(); 982 auto *initializer = 983 dyn_cast<llvm::ConstantArray>(globalVar->getInitializer()); 984 if (!initializer) 985 return failure(); 986 987 SmallVector<Attribute> funcs; 988 SmallVector<int32_t> priorities; 989 for (llvm::Value *operand : initializer->operands()) { 990 auto *aggregate = dyn_cast<llvm::ConstantAggregate>(operand); 991 if (!aggregate || aggregate->getNumOperands() != 3) 992 return failure(); 993 994 auto *priority = dyn_cast<llvm::ConstantInt>(aggregate->getOperand(0)); 995 auto *func = dyn_cast<llvm::Function>(aggregate->getOperand(1)); 996 auto *data = dyn_cast<llvm::Constant>(aggregate->getOperand(2)); 997 if (!priority || !func || !data) 998 return failure(); 999 1000 // GlobalCtorsOps and GlobalDtorsOps do not support non-null data fields. 1001 if (!data->isNullValue()) 1002 return failure(); 1003 1004 funcs.push_back(FlatSymbolRefAttr::get(context, func->getName())); 1005 priorities.push_back(priority->getValue().getZExtValue()); 1006 } 1007 1008 OpBuilder::InsertionGuard guard(builder); 1009 if (!globalInsertionOp) 1010 builder.setInsertionPointToStart(mlirModule.getBody()); 1011 else 1012 builder.setInsertionPointAfter(globalInsertionOp); 1013 1014 if (globalVar->getName() == getGlobalCtorsVarName()) { 1015 globalInsertionOp = builder.create<LLVM::GlobalCtorsOp>( 1016 mlirModule.getLoc(), builder.getArrayAttr(funcs), 1017 builder.getI32ArrayAttr(priorities)); 1018 return success(); 1019 } 1020 globalInsertionOp = builder.create<LLVM::GlobalDtorsOp>( 1021 mlirModule.getLoc(), builder.getArrayAttr(funcs), 1022 builder.getI32ArrayAttr(priorities)); 1023 return success(); 1024 } 1025 1026 SetVector<llvm::Constant *> 1027 ModuleImport::getConstantsToConvert(llvm::Constant *constant) { 1028 // Return the empty set if the constant has been translated before. 1029 if (valueMapping.contains(constant)) 1030 return {}; 1031 1032 // Traverse the constants in post-order and stop the traversal if a constant 1033 // already has a `valueMapping` from an earlier constant translation or if the 1034 // constant is traversed a second time. 1035 SetVector<llvm::Constant *> orderedSet; 1036 SetVector<llvm::Constant *> workList; 1037 DenseMap<llvm::Constant *, SmallVector<llvm::Constant *>> adjacencyLists; 1038 workList.insert(constant); 1039 while (!workList.empty()) { 1040 llvm::Constant *current = workList.back(); 1041 // Collect all dependencies of the current constant and add them to the 1042 // adjacency list if none has been computed before. 1043 auto [adjacencyIt, inserted] = adjacencyLists.try_emplace(current); 1044 if (inserted) { 1045 // Add all constant operands to the adjacency list and skip any other 1046 // values such as basic block addresses. 1047 for (llvm::Value *operand : current->operands()) 1048 if (auto *constDependency = dyn_cast<llvm::Constant>(operand)) 1049 adjacencyIt->getSecond().push_back(constDependency); 1050 // Use the getElementValue method to add the dependencies of zero 1051 // initialized aggregate constants since they do not take any operands. 1052 if (auto *constAgg = dyn_cast<llvm::ConstantAggregateZero>(current)) { 1053 unsigned numElements = constAgg->getElementCount().getFixedValue(); 1054 for (unsigned i = 0, e = numElements; i != e; ++i) 1055 adjacencyIt->getSecond().push_back(constAgg->getElementValue(i)); 1056 } 1057 } 1058 // Add the current constant to the `orderedSet` of the traversed nodes if 1059 // all its dependencies have been traversed before. Additionally, remove the 1060 // constant from the `workList` and continue the traversal. 1061 if (adjacencyIt->getSecond().empty()) { 1062 orderedSet.insert(current); 1063 workList.pop_back(); 1064 continue; 1065 } 1066 // Add the next dependency from the adjacency list to the `workList` and 1067 // continue the traversal. Remove the dependency from the adjacency list to 1068 // mark that it has been processed. Only enqueue the dependency if it has no 1069 // `valueMapping` from an earlier translation and if it has not been 1070 // enqueued before. 1071 llvm::Constant *dependency = adjacencyIt->getSecond().pop_back_val(); 1072 if (valueMapping.contains(dependency) || workList.contains(dependency) || 1073 orderedSet.contains(dependency)) 1074 continue; 1075 workList.insert(dependency); 1076 } 1077 1078 return orderedSet; 1079 } 1080 1081 FailureOr<Value> ModuleImport::convertConstant(llvm::Constant *constant) { 1082 Location loc = UnknownLoc::get(context); 1083 1084 // Convert constants that can be represented as attributes. 1085 if (Attribute attr = getConstantAsAttr(constant)) { 1086 Type type = convertType(constant->getType()); 1087 if (auto symbolRef = dyn_cast<FlatSymbolRefAttr>(attr)) { 1088 return builder.create<AddressOfOp>(loc, type, symbolRef.getValue()) 1089 .getResult(); 1090 } 1091 return builder.create<ConstantOp>(loc, type, attr).getResult(); 1092 } 1093 1094 // Convert null pointer constants. 1095 if (auto *nullPtr = dyn_cast<llvm::ConstantPointerNull>(constant)) { 1096 Type type = convertType(nullPtr->getType()); 1097 return builder.create<ZeroOp>(loc, type).getResult(); 1098 } 1099 1100 // Convert none token constants. 1101 if (isa<llvm::ConstantTokenNone>(constant)) { 1102 return builder.create<NoneTokenOp>(loc).getResult(); 1103 } 1104 1105 // Convert poison. 1106 if (auto *poisonVal = dyn_cast<llvm::PoisonValue>(constant)) { 1107 Type type = convertType(poisonVal->getType()); 1108 return builder.create<PoisonOp>(loc, type).getResult(); 1109 } 1110 1111 // Convert undef. 1112 if (auto *undefVal = dyn_cast<llvm::UndefValue>(constant)) { 1113 Type type = convertType(undefVal->getType()); 1114 return builder.create<UndefOp>(loc, type).getResult(); 1115 } 1116 1117 // Convert global variable accesses. 1118 if (auto *globalVar = dyn_cast<llvm::GlobalVariable>(constant)) { 1119 Type type = convertType(globalVar->getType()); 1120 StringRef globalName = globalVar->getName(); 1121 FlatSymbolRefAttr symbolRef; 1122 if (globalName.empty()) 1123 symbolRef = namelessGlobals[globalVar]; 1124 else 1125 symbolRef = FlatSymbolRefAttr::get(context, globalName); 1126 return builder.create<AddressOfOp>(loc, type, symbolRef).getResult(); 1127 } 1128 1129 // Convert constant expressions. 1130 if (auto *constExpr = dyn_cast<llvm::ConstantExpr>(constant)) { 1131 // Convert the constant expression to a temporary LLVM instruction and 1132 // translate it using the `processInstruction` method. Delete the 1133 // instruction after the translation and remove it from `valueMapping`, 1134 // since later calls to `getAsInstruction` may return the same address 1135 // resulting in a conflicting `valueMapping` entry. 1136 llvm::Instruction *inst = constExpr->getAsInstruction(); 1137 auto guard = llvm::make_scope_exit([&]() { 1138 assert(!noResultOpMapping.contains(inst) && 1139 "expected constant expression to return a result"); 1140 valueMapping.erase(inst); 1141 inst->deleteValue(); 1142 }); 1143 // Note: `processInstruction` does not call `convertConstant` recursively 1144 // since all constant dependencies have been converted before. 1145 assert(llvm::all_of(inst->operands(), [&](llvm::Value *value) { 1146 return valueMapping.contains(value); 1147 })); 1148 if (failed(processInstruction(inst))) 1149 return failure(); 1150 return lookupValue(inst); 1151 } 1152 1153 // Convert aggregate constants. 1154 if (isa<llvm::ConstantAggregate>(constant) || 1155 isa<llvm::ConstantAggregateZero>(constant)) { 1156 // Lookup the aggregate elements that have been converted before. 1157 SmallVector<Value> elementValues; 1158 if (auto *constAgg = dyn_cast<llvm::ConstantAggregate>(constant)) { 1159 elementValues.reserve(constAgg->getNumOperands()); 1160 for (llvm::Value *operand : constAgg->operands()) 1161 elementValues.push_back(lookupValue(operand)); 1162 } 1163 if (auto *constAgg = dyn_cast<llvm::ConstantAggregateZero>(constant)) { 1164 unsigned numElements = constAgg->getElementCount().getFixedValue(); 1165 elementValues.reserve(numElements); 1166 for (unsigned i = 0, e = numElements; i != e; ++i) 1167 elementValues.push_back(lookupValue(constAgg->getElementValue(i))); 1168 } 1169 assert(llvm::count(elementValues, nullptr) == 0 && 1170 "expected all elements have been converted before"); 1171 1172 // Generate an UndefOp as root value and insert the aggregate elements. 1173 Type rootType = convertType(constant->getType()); 1174 bool isArrayOrStruct = isa<LLVMArrayType, LLVMStructType>(rootType); 1175 assert((isArrayOrStruct || LLVM::isCompatibleVectorType(rootType)) && 1176 "unrecognized aggregate type"); 1177 Value root = builder.create<UndefOp>(loc, rootType); 1178 for (const auto &it : llvm::enumerate(elementValues)) { 1179 if (isArrayOrStruct) { 1180 root = builder.create<InsertValueOp>(loc, root, it.value(), it.index()); 1181 } else { 1182 Attribute indexAttr = builder.getI32IntegerAttr(it.index()); 1183 Value indexValue = 1184 builder.create<ConstantOp>(loc, builder.getI32Type(), indexAttr); 1185 root = builder.create<InsertElementOp>(loc, rootType, root, it.value(), 1186 indexValue); 1187 } 1188 } 1189 return root; 1190 } 1191 1192 if (auto *constTargetNone = dyn_cast<llvm::ConstantTargetNone>(constant)) { 1193 LLVMTargetExtType targetExtType = 1194 cast<LLVMTargetExtType>(convertType(constTargetNone->getType())); 1195 assert(targetExtType.hasProperty(LLVMTargetExtType::HasZeroInit) && 1196 "target extension type does not support zero-initialization"); 1197 // Create llvm.mlir.zero operation to represent zero-initialization of 1198 // target extension type. 1199 return builder.create<LLVM::ZeroOp>(loc, targetExtType).getRes(); 1200 } 1201 1202 StringRef error = ""; 1203 if (isa<llvm::BlockAddress>(constant)) 1204 error = " since blockaddress(...) is unsupported"; 1205 1206 return emitError(loc) << "unhandled constant: " << diag(*constant) << error; 1207 } 1208 1209 FailureOr<Value> ModuleImport::convertConstantExpr(llvm::Constant *constant) { 1210 // Only call the function for constants that have not been translated before 1211 // since it updates the constant insertion point assuming the converted 1212 // constant has been introduced at the end of the constant section. 1213 assert(!valueMapping.contains(constant) && 1214 "expected constant has not been converted before"); 1215 assert(constantInsertionBlock && 1216 "expected the constant insertion block to be non-null"); 1217 1218 // Insert the constant after the last one or at the start of the entry block. 1219 OpBuilder::InsertionGuard guard(builder); 1220 if (!constantInsertionOp) 1221 builder.setInsertionPointToStart(constantInsertionBlock); 1222 else 1223 builder.setInsertionPointAfter(constantInsertionOp); 1224 1225 // Convert all constants of the expression and add them to `valueMapping`. 1226 SetVector<llvm::Constant *> constantsToConvert = 1227 getConstantsToConvert(constant); 1228 for (llvm::Constant *constantToConvert : constantsToConvert) { 1229 FailureOr<Value> converted = convertConstant(constantToConvert); 1230 if (failed(converted)) 1231 return failure(); 1232 mapValue(constantToConvert, *converted); 1233 } 1234 1235 // Update the constant insertion point and return the converted constant. 1236 Value result = lookupValue(constant); 1237 constantInsertionOp = result.getDefiningOp(); 1238 return result; 1239 } 1240 1241 FailureOr<Value> ModuleImport::convertValue(llvm::Value *value) { 1242 assert(!isa<llvm::MetadataAsValue>(value) && 1243 "expected value to not be metadata"); 1244 1245 // Return the mapped value if it has been converted before. 1246 auto it = valueMapping.find(value); 1247 if (it != valueMapping.end()) 1248 return it->getSecond(); 1249 1250 // Convert constants such as immediate values that have no mapping yet. 1251 if (auto *constant = dyn_cast<llvm::Constant>(value)) 1252 return convertConstantExpr(constant); 1253 1254 Location loc = UnknownLoc::get(context); 1255 if (auto *inst = dyn_cast<llvm::Instruction>(value)) 1256 loc = translateLoc(inst->getDebugLoc()); 1257 return emitError(loc) << "unhandled value: " << diag(*value); 1258 } 1259 1260 FailureOr<Value> ModuleImport::convertMetadataValue(llvm::Value *value) { 1261 // A value may be wrapped as metadata, for example, when passed to a debug 1262 // intrinsic. Unwrap these values before the conversion. 1263 auto *nodeAsVal = dyn_cast<llvm::MetadataAsValue>(value); 1264 if (!nodeAsVal) 1265 return failure(); 1266 auto *node = dyn_cast<llvm::ValueAsMetadata>(nodeAsVal->getMetadata()); 1267 if (!node) 1268 return failure(); 1269 value = node->getValue(); 1270 1271 // Return the mapped value if it has been converted before. 1272 auto it = valueMapping.find(value); 1273 if (it != valueMapping.end()) 1274 return it->getSecond(); 1275 1276 // Convert constants such as immediate values that have no mapping yet. 1277 if (auto *constant = dyn_cast<llvm::Constant>(value)) 1278 return convertConstantExpr(constant); 1279 return failure(); 1280 } 1281 1282 FailureOr<SmallVector<Value>> 1283 ModuleImport::convertValues(ArrayRef<llvm::Value *> values) { 1284 SmallVector<Value> remapped; 1285 remapped.reserve(values.size()); 1286 for (llvm::Value *value : values) { 1287 FailureOr<Value> converted = convertValue(value); 1288 if (failed(converted)) 1289 return failure(); 1290 remapped.push_back(*converted); 1291 } 1292 return remapped; 1293 } 1294 1295 LogicalResult ModuleImport::convertIntrinsicArguments( 1296 ArrayRef<llvm::Value *> values, ArrayRef<unsigned> immArgPositions, 1297 ArrayRef<StringLiteral> immArgAttrNames, SmallVectorImpl<Value> &valuesOut, 1298 SmallVectorImpl<NamedAttribute> &attrsOut) { 1299 assert(immArgPositions.size() == immArgAttrNames.size() && 1300 "LLVM `immArgPositions` and MLIR `immArgAttrNames` should have equal " 1301 "length"); 1302 1303 SmallVector<llvm::Value *> operands(values); 1304 for (auto [immArgPos, immArgName] : 1305 llvm::zip(immArgPositions, immArgAttrNames)) { 1306 auto &value = operands[immArgPos]; 1307 auto *constant = llvm::cast<llvm::Constant>(value); 1308 auto attr = getScalarConstantAsAttr(builder, constant); 1309 assert(attr && attr.getType().isIntOrFloat() && 1310 "expected immarg to be float or integer constant"); 1311 auto nameAttr = StringAttr::get(attr.getContext(), immArgName); 1312 attrsOut.push_back({nameAttr, attr}); 1313 // Mark matched attribute values as null (so they can be removed below). 1314 value = nullptr; 1315 } 1316 1317 for (llvm::Value *value : operands) { 1318 if (!value) 1319 continue; 1320 auto mlirValue = convertValue(value); 1321 if (failed(mlirValue)) 1322 return failure(); 1323 valuesOut.push_back(*mlirValue); 1324 } 1325 1326 return success(); 1327 } 1328 1329 IntegerAttr ModuleImport::matchIntegerAttr(llvm::Value *value) { 1330 IntegerAttr integerAttr; 1331 FailureOr<Value> converted = convertValue(value); 1332 bool success = succeeded(converted) && 1333 matchPattern(*converted, m_Constant(&integerAttr)); 1334 assert(success && "expected a constant integer value"); 1335 (void)success; 1336 return integerAttr; 1337 } 1338 1339 FloatAttr ModuleImport::matchFloatAttr(llvm::Value *value) { 1340 FloatAttr floatAttr; 1341 FailureOr<Value> converted = convertValue(value); 1342 bool success = 1343 succeeded(converted) && matchPattern(*converted, m_Constant(&floatAttr)); 1344 assert(success && "expected a constant float value"); 1345 (void)success; 1346 return floatAttr; 1347 } 1348 1349 DILocalVariableAttr ModuleImport::matchLocalVariableAttr(llvm::Value *value) { 1350 auto *nodeAsVal = cast<llvm::MetadataAsValue>(value); 1351 auto *node = cast<llvm::DILocalVariable>(nodeAsVal->getMetadata()); 1352 return debugImporter->translate(node); 1353 } 1354 1355 DILabelAttr ModuleImport::matchLabelAttr(llvm::Value *value) { 1356 auto *nodeAsVal = cast<llvm::MetadataAsValue>(value); 1357 auto *node = cast<llvm::DILabel>(nodeAsVal->getMetadata()); 1358 return debugImporter->translate(node); 1359 } 1360 1361 FPExceptionBehaviorAttr 1362 ModuleImport::matchFPExceptionBehaviorAttr(llvm::Value *value) { 1363 auto *metadata = cast<llvm::MetadataAsValue>(value); 1364 auto *mdstr = cast<llvm::MDString>(metadata->getMetadata()); 1365 std::optional<llvm::fp::ExceptionBehavior> optLLVM = 1366 llvm::convertStrToExceptionBehavior(mdstr->getString()); 1367 assert(optLLVM && "Expecting FP exception behavior"); 1368 return builder.getAttr<FPExceptionBehaviorAttr>( 1369 convertFPExceptionBehaviorFromLLVM(*optLLVM)); 1370 } 1371 1372 RoundingModeAttr ModuleImport::matchRoundingModeAttr(llvm::Value *value) { 1373 auto *metadata = cast<llvm::MetadataAsValue>(value); 1374 auto *mdstr = cast<llvm::MDString>(metadata->getMetadata()); 1375 std::optional<llvm::RoundingMode> optLLVM = 1376 llvm::convertStrToRoundingMode(mdstr->getString()); 1377 assert(optLLVM && "Expecting rounding mode"); 1378 return builder.getAttr<RoundingModeAttr>( 1379 convertRoundingModeFromLLVM(*optLLVM)); 1380 } 1381 1382 FailureOr<SmallVector<AliasScopeAttr>> 1383 ModuleImport::matchAliasScopeAttrs(llvm::Value *value) { 1384 auto *nodeAsVal = cast<llvm::MetadataAsValue>(value); 1385 auto *node = cast<llvm::MDNode>(nodeAsVal->getMetadata()); 1386 return lookupAliasScopeAttrs(node); 1387 } 1388 1389 Location ModuleImport::translateLoc(llvm::DILocation *loc) { 1390 return debugImporter->translateLoc(loc); 1391 } 1392 1393 LogicalResult 1394 ModuleImport::convertBranchArgs(llvm::Instruction *branch, 1395 llvm::BasicBlock *target, 1396 SmallVectorImpl<Value> &blockArguments) { 1397 for (auto inst = target->begin(); isa<llvm::PHINode>(inst); ++inst) { 1398 auto *phiInst = cast<llvm::PHINode>(&*inst); 1399 llvm::Value *value = phiInst->getIncomingValueForBlock(branch->getParent()); 1400 FailureOr<Value> converted = convertValue(value); 1401 if (failed(converted)) 1402 return failure(); 1403 blockArguments.push_back(*converted); 1404 } 1405 return success(); 1406 } 1407 1408 LogicalResult 1409 ModuleImport::convertCallTypeAndOperands(llvm::CallBase *callInst, 1410 SmallVectorImpl<Type> &types, 1411 SmallVectorImpl<Value> &operands) { 1412 if (!callInst->getType()->isVoidTy()) 1413 types.push_back(convertType(callInst->getType())); 1414 1415 if (!callInst->getCalledFunction()) { 1416 FailureOr<Value> called = convertValue(callInst->getCalledOperand()); 1417 if (failed(called)) 1418 return failure(); 1419 operands.push_back(*called); 1420 } 1421 SmallVector<llvm::Value *> args(callInst->args()); 1422 FailureOr<SmallVector<Value>> arguments = convertValues(args); 1423 if (failed(arguments)) 1424 return failure(); 1425 llvm::append_range(operands, *arguments); 1426 return success(); 1427 } 1428 1429 LogicalResult ModuleImport::convertIntrinsic(llvm::CallInst *inst) { 1430 if (succeeded(iface.convertIntrinsic(builder, inst, *this))) 1431 return success(); 1432 1433 Location loc = translateLoc(inst->getDebugLoc()); 1434 return emitError(loc) << "unhandled intrinsic: " << diag(*inst); 1435 } 1436 1437 LogicalResult ModuleImport::convertInstruction(llvm::Instruction *inst) { 1438 // Convert all instructions that do not provide an MLIR builder. 1439 Location loc = translateLoc(inst->getDebugLoc()); 1440 if (inst->getOpcode() == llvm::Instruction::Br) { 1441 auto *brInst = cast<llvm::BranchInst>(inst); 1442 1443 SmallVector<Block *> succBlocks; 1444 SmallVector<SmallVector<Value>> succBlockArgs; 1445 for (auto i : llvm::seq<unsigned>(0, brInst->getNumSuccessors())) { 1446 llvm::BasicBlock *succ = brInst->getSuccessor(i); 1447 SmallVector<Value> blockArgs; 1448 if (failed(convertBranchArgs(brInst, succ, blockArgs))) 1449 return failure(); 1450 succBlocks.push_back(lookupBlock(succ)); 1451 succBlockArgs.push_back(blockArgs); 1452 } 1453 1454 if (!brInst->isConditional()) { 1455 auto brOp = builder.create<LLVM::BrOp>(loc, succBlockArgs.front(), 1456 succBlocks.front()); 1457 mapNoResultOp(inst, brOp); 1458 return success(); 1459 } 1460 FailureOr<Value> condition = convertValue(brInst->getCondition()); 1461 if (failed(condition)) 1462 return failure(); 1463 auto condBrOp = builder.create<LLVM::CondBrOp>( 1464 loc, *condition, succBlocks.front(), succBlockArgs.front(), 1465 succBlocks.back(), succBlockArgs.back()); 1466 mapNoResultOp(inst, condBrOp); 1467 return success(); 1468 } 1469 if (inst->getOpcode() == llvm::Instruction::Switch) { 1470 auto *swInst = cast<llvm::SwitchInst>(inst); 1471 // Process the condition value. 1472 FailureOr<Value> condition = convertValue(swInst->getCondition()); 1473 if (failed(condition)) 1474 return failure(); 1475 SmallVector<Value> defaultBlockArgs; 1476 // Process the default case. 1477 llvm::BasicBlock *defaultBB = swInst->getDefaultDest(); 1478 if (failed(convertBranchArgs(swInst, defaultBB, defaultBlockArgs))) 1479 return failure(); 1480 1481 // Process the cases. 1482 unsigned numCases = swInst->getNumCases(); 1483 SmallVector<SmallVector<Value>> caseOperands(numCases); 1484 SmallVector<ValueRange> caseOperandRefs(numCases); 1485 SmallVector<APInt> caseValues(numCases); 1486 SmallVector<Block *> caseBlocks(numCases); 1487 for (const auto &it : llvm::enumerate(swInst->cases())) { 1488 const llvm::SwitchInst::CaseHandle &caseHandle = it.value(); 1489 llvm::BasicBlock *succBB = caseHandle.getCaseSuccessor(); 1490 if (failed(convertBranchArgs(swInst, succBB, caseOperands[it.index()]))) 1491 return failure(); 1492 caseOperandRefs[it.index()] = caseOperands[it.index()]; 1493 caseValues[it.index()] = caseHandle.getCaseValue()->getValue(); 1494 caseBlocks[it.index()] = lookupBlock(succBB); 1495 } 1496 1497 auto switchOp = builder.create<SwitchOp>( 1498 loc, *condition, lookupBlock(defaultBB), defaultBlockArgs, caseValues, 1499 caseBlocks, caseOperandRefs); 1500 mapNoResultOp(inst, switchOp); 1501 return success(); 1502 } 1503 if (inst->getOpcode() == llvm::Instruction::PHI) { 1504 Type type = convertType(inst->getType()); 1505 mapValue(inst, builder.getInsertionBlock()->addArgument( 1506 type, translateLoc(inst->getDebugLoc()))); 1507 return success(); 1508 } 1509 if (inst->getOpcode() == llvm::Instruction::Call) { 1510 auto *callInst = cast<llvm::CallInst>(inst); 1511 1512 SmallVector<Type> types; 1513 SmallVector<Value> operands; 1514 if (failed(convertCallTypeAndOperands(callInst, types, operands))) 1515 return failure(); 1516 1517 auto funcTy = 1518 dyn_cast<LLVMFunctionType>(convertType(callInst->getFunctionType())); 1519 if (!funcTy) 1520 return failure(); 1521 1522 CallOp callOp; 1523 1524 if (llvm::Function *callee = callInst->getCalledFunction()) { 1525 callOp = builder.create<CallOp>( 1526 loc, funcTy, SymbolRefAttr::get(context, callee->getName()), 1527 operands); 1528 } else { 1529 callOp = builder.create<CallOp>(loc, funcTy, operands); 1530 } 1531 callOp.setCConv(convertCConvFromLLVM(callInst->getCallingConv())); 1532 callOp.setTailCallKind( 1533 convertTailCallKindFromLLVM(callInst->getTailCallKind())); 1534 setFastmathFlagsAttr(inst, callOp); 1535 1536 // Handle function attributes. 1537 if (callInst->hasFnAttr(llvm::Attribute::Convergent)) 1538 callOp.setConvergent(true); 1539 if (callInst->hasFnAttr(llvm::Attribute::NoUnwind)) 1540 callOp.setNoUnwind(true); 1541 if (callInst->hasFnAttr(llvm::Attribute::WillReturn)) 1542 callOp.setWillReturn(true); 1543 1544 llvm::MemoryEffects memEffects = callInst->getMemoryEffects(); 1545 ModRefInfo othermem = convertModRefInfoFromLLVM( 1546 memEffects.getModRef(llvm::MemoryEffects::Location::Other)); 1547 ModRefInfo argMem = convertModRefInfoFromLLVM( 1548 memEffects.getModRef(llvm::MemoryEffects::Location::ArgMem)); 1549 ModRefInfo inaccessibleMem = convertModRefInfoFromLLVM( 1550 memEffects.getModRef(llvm::MemoryEffects::Location::InaccessibleMem)); 1551 auto memAttr = MemoryEffectsAttr::get(callOp.getContext(), othermem, argMem, 1552 inaccessibleMem); 1553 // Only set the attribute when it does not match the default value. 1554 if (!memAttr.isReadWrite()) 1555 callOp.setMemoryEffectsAttr(memAttr); 1556 1557 if (!callInst->getType()->isVoidTy()) 1558 mapValue(inst, callOp.getResult()); 1559 else 1560 mapNoResultOp(inst, callOp); 1561 return success(); 1562 } 1563 if (inst->getOpcode() == llvm::Instruction::LandingPad) { 1564 auto *lpInst = cast<llvm::LandingPadInst>(inst); 1565 1566 SmallVector<Value> operands; 1567 operands.reserve(lpInst->getNumClauses()); 1568 for (auto i : llvm::seq<unsigned>(0, lpInst->getNumClauses())) { 1569 FailureOr<Value> operand = convertValue(lpInst->getClause(i)); 1570 if (failed(operand)) 1571 return failure(); 1572 operands.push_back(*operand); 1573 } 1574 1575 Type type = convertType(lpInst->getType()); 1576 auto lpOp = 1577 builder.create<LandingpadOp>(loc, type, lpInst->isCleanup(), operands); 1578 mapValue(inst, lpOp); 1579 return success(); 1580 } 1581 if (inst->getOpcode() == llvm::Instruction::Invoke) { 1582 auto *invokeInst = cast<llvm::InvokeInst>(inst); 1583 1584 SmallVector<Type> types; 1585 SmallVector<Value> operands; 1586 if (failed(convertCallTypeAndOperands(invokeInst, types, operands))) 1587 return failure(); 1588 1589 // Check whether the invoke result is an argument to the normal destination 1590 // block. 1591 bool invokeResultUsedInPhi = llvm::any_of( 1592 invokeInst->getNormalDest()->phis(), [&](const llvm::PHINode &phi) { 1593 return phi.getIncomingValueForBlock(invokeInst->getParent()) == 1594 invokeInst; 1595 }); 1596 1597 Block *normalDest = lookupBlock(invokeInst->getNormalDest()); 1598 Block *directNormalDest = normalDest; 1599 if (invokeResultUsedInPhi) { 1600 // The invoke result cannot be an argument to the normal destination 1601 // block, as that would imply using the invoke operation result in its 1602 // definition, so we need to create a dummy block to serve as an 1603 // intermediate destination. 1604 OpBuilder::InsertionGuard g(builder); 1605 directNormalDest = builder.createBlock(normalDest); 1606 } 1607 1608 SmallVector<Value> unwindArgs; 1609 if (failed(convertBranchArgs(invokeInst, invokeInst->getUnwindDest(), 1610 unwindArgs))) 1611 return failure(); 1612 1613 auto funcTy = 1614 dyn_cast<LLVMFunctionType>(convertType(invokeInst->getFunctionType())); 1615 if (!funcTy) 1616 return failure(); 1617 1618 // Create the invoke operation. Normal destination block arguments will be 1619 // added later on to handle the case in which the operation result is 1620 // included in this list. 1621 InvokeOp invokeOp; 1622 if (llvm::Function *callee = invokeInst->getCalledFunction()) { 1623 invokeOp = builder.create<InvokeOp>( 1624 loc, funcTy, 1625 SymbolRefAttr::get(builder.getContext(), callee->getName()), operands, 1626 directNormalDest, ValueRange(), 1627 lookupBlock(invokeInst->getUnwindDest()), unwindArgs); 1628 } else { 1629 invokeOp = builder.create<InvokeOp>( 1630 loc, funcTy, /*callee=*/nullptr, operands, directNormalDest, 1631 ValueRange(), lookupBlock(invokeInst->getUnwindDest()), unwindArgs); 1632 } 1633 invokeOp.setCConv(convertCConvFromLLVM(invokeInst->getCallingConv())); 1634 if (!invokeInst->getType()->isVoidTy()) 1635 mapValue(inst, invokeOp.getResults().front()); 1636 else 1637 mapNoResultOp(inst, invokeOp); 1638 1639 SmallVector<Value> normalArgs; 1640 if (failed(convertBranchArgs(invokeInst, invokeInst->getNormalDest(), 1641 normalArgs))) 1642 return failure(); 1643 1644 if (invokeResultUsedInPhi) { 1645 // The dummy normal dest block will just host an unconditional branch 1646 // instruction to the normal destination block passing the required block 1647 // arguments (including the invoke operation's result). 1648 OpBuilder::InsertionGuard g(builder); 1649 builder.setInsertionPointToStart(directNormalDest); 1650 builder.create<LLVM::BrOp>(loc, normalArgs, normalDest); 1651 } else { 1652 // If the invoke operation's result is not a block argument to the normal 1653 // destination block, just add the block arguments as usual. 1654 assert(llvm::none_of( 1655 normalArgs, 1656 [&](Value val) { return val.getDefiningOp() == invokeOp; }) && 1657 "An llvm.invoke operation cannot pass its result as a block " 1658 "argument."); 1659 invokeOp.getNormalDestOperandsMutable().append(normalArgs); 1660 } 1661 1662 return success(); 1663 } 1664 if (inst->getOpcode() == llvm::Instruction::GetElementPtr) { 1665 auto *gepInst = cast<llvm::GetElementPtrInst>(inst); 1666 Type sourceElementType = convertType(gepInst->getSourceElementType()); 1667 FailureOr<Value> basePtr = convertValue(gepInst->getOperand(0)); 1668 if (failed(basePtr)) 1669 return failure(); 1670 1671 // Treat every indices as dynamic since GEPOp::build will refine those 1672 // indices into static attributes later. One small downside of this 1673 // approach is that many unused `llvm.mlir.constant` would be emitted 1674 // at first place. 1675 SmallVector<GEPArg> indices; 1676 for (llvm::Value *operand : llvm::drop_begin(gepInst->operand_values())) { 1677 FailureOr<Value> index = convertValue(operand); 1678 if (failed(index)) 1679 return failure(); 1680 indices.push_back(*index); 1681 } 1682 1683 Type type = convertType(inst->getType()); 1684 auto gepOp = builder.create<GEPOp>(loc, type, sourceElementType, *basePtr, 1685 indices, gepInst->isInBounds()); 1686 mapValue(inst, gepOp); 1687 return success(); 1688 } 1689 1690 // Convert all instructions that have an mlirBuilder. 1691 if (succeeded(convertInstructionImpl(builder, inst, *this, iface))) 1692 return success(); 1693 1694 return emitError(loc) << "unhandled instruction: " << diag(*inst); 1695 } 1696 1697 LogicalResult ModuleImport::processInstruction(llvm::Instruction *inst) { 1698 // FIXME: Support uses of SubtargetData. 1699 // FIXME: Add support for call / operand attributes. 1700 // FIXME: Add support for the indirectbr, cleanupret, catchret, catchswitch, 1701 // callbr, vaarg, catchpad, cleanuppad instructions. 1702 1703 // Convert LLVM intrinsics calls to MLIR intrinsics. 1704 if (auto *intrinsic = dyn_cast<llvm::IntrinsicInst>(inst)) 1705 return convertIntrinsic(intrinsic); 1706 1707 // Convert all remaining LLVM instructions to MLIR operations. 1708 return convertInstruction(inst); 1709 } 1710 1711 FlatSymbolRefAttr ModuleImport::getPersonalityAsAttr(llvm::Function *f) { 1712 if (!f->hasPersonalityFn()) 1713 return nullptr; 1714 1715 llvm::Constant *pf = f->getPersonalityFn(); 1716 1717 // If it directly has a name, we can use it. 1718 if (pf->hasName()) 1719 return SymbolRefAttr::get(builder.getContext(), pf->getName()); 1720 1721 // If it doesn't have a name, currently, only function pointers that are 1722 // bitcast to i8* are parsed. 1723 if (auto *ce = dyn_cast<llvm::ConstantExpr>(pf)) { 1724 if (ce->getOpcode() == llvm::Instruction::BitCast && 1725 ce->getType() == llvm::PointerType::getUnqual(f->getContext())) { 1726 if (auto *func = dyn_cast<llvm::Function>(ce->getOperand(0))) 1727 return SymbolRefAttr::get(builder.getContext(), func->getName()); 1728 } 1729 } 1730 return FlatSymbolRefAttr(); 1731 } 1732 1733 static void processMemoryEffects(llvm::Function *func, LLVMFuncOp funcOp) { 1734 llvm::MemoryEffects memEffects = func->getMemoryEffects(); 1735 1736 auto othermem = convertModRefInfoFromLLVM( 1737 memEffects.getModRef(llvm::MemoryEffects::Location::Other)); 1738 auto argMem = convertModRefInfoFromLLVM( 1739 memEffects.getModRef(llvm::MemoryEffects::Location::ArgMem)); 1740 auto inaccessibleMem = convertModRefInfoFromLLVM( 1741 memEffects.getModRef(llvm::MemoryEffects::Location::InaccessibleMem)); 1742 auto memAttr = MemoryEffectsAttr::get(funcOp.getContext(), othermem, argMem, 1743 inaccessibleMem); 1744 // Only set the attr when it does not match the default value. 1745 if (memAttr.isReadWrite()) 1746 return; 1747 funcOp.setMemoryEffectsAttr(memAttr); 1748 } 1749 1750 // List of LLVM IR attributes that map to an explicit attribute on the MLIR 1751 // LLVMFuncOp. 1752 static constexpr std::array kExplicitAttributes{ 1753 StringLiteral("aarch64_in_za"), 1754 StringLiteral("aarch64_inout_za"), 1755 StringLiteral("aarch64_new_za"), 1756 StringLiteral("aarch64_out_za"), 1757 StringLiteral("aarch64_preserves_za"), 1758 StringLiteral("aarch64_pstate_sm_body"), 1759 StringLiteral("aarch64_pstate_sm_compatible"), 1760 StringLiteral("aarch64_pstate_sm_enabled"), 1761 StringLiteral("alwaysinline"), 1762 StringLiteral("approx-func-fp-math"), 1763 StringLiteral("convergent"), 1764 StringLiteral("denormal-fp-math"), 1765 StringLiteral("denormal-fp-math-f32"), 1766 StringLiteral("fp-contract"), 1767 StringLiteral("frame-pointer"), 1768 StringLiteral("no-infs-fp-math"), 1769 StringLiteral("no-nans-fp-math"), 1770 StringLiteral("no-signed-zeros-fp-math"), 1771 StringLiteral("noinline"), 1772 StringLiteral("nounwind"), 1773 StringLiteral("optnone"), 1774 StringLiteral("target-features"), 1775 StringLiteral("tune-cpu"), 1776 StringLiteral("unsafe-fp-math"), 1777 StringLiteral("vscale_range"), 1778 StringLiteral("willreturn"), 1779 }; 1780 1781 static void processPassthroughAttrs(llvm::Function *func, LLVMFuncOp funcOp) { 1782 MLIRContext *context = funcOp.getContext(); 1783 SmallVector<Attribute> passthroughs; 1784 llvm::AttributeSet funcAttrs = func->getAttributes().getAttributes( 1785 llvm::AttributeList::AttrIndex::FunctionIndex); 1786 for (llvm::Attribute attr : funcAttrs) { 1787 // Skip the memory attribute since the LLVMFuncOp has an explicit memory 1788 // attribute. 1789 if (attr.hasAttribute(llvm::Attribute::Memory)) 1790 continue; 1791 1792 // Skip invalid type attributes. 1793 if (attr.isTypeAttribute()) { 1794 emitWarning(funcOp.getLoc(), 1795 "type attributes on a function are invalid, skipping it"); 1796 continue; 1797 } 1798 1799 StringRef attrName; 1800 if (attr.isStringAttribute()) 1801 attrName = attr.getKindAsString(); 1802 else 1803 attrName = llvm::Attribute::getNameFromAttrKind(attr.getKindAsEnum()); 1804 auto keyAttr = StringAttr::get(context, attrName); 1805 1806 // Skip attributes that map to an explicit attribute on the LLVMFuncOp. 1807 if (llvm::is_contained(kExplicitAttributes, attrName)) 1808 continue; 1809 1810 if (attr.isStringAttribute()) { 1811 StringRef val = attr.getValueAsString(); 1812 if (val.empty()) { 1813 passthroughs.push_back(keyAttr); 1814 continue; 1815 } 1816 passthroughs.push_back( 1817 ArrayAttr::get(context, {keyAttr, StringAttr::get(context, val)})); 1818 continue; 1819 } 1820 if (attr.isIntAttribute()) { 1821 auto val = std::to_string(attr.getValueAsInt()); 1822 passthroughs.push_back( 1823 ArrayAttr::get(context, {keyAttr, StringAttr::get(context, val)})); 1824 continue; 1825 } 1826 if (attr.isEnumAttribute()) { 1827 passthroughs.push_back(keyAttr); 1828 continue; 1829 } 1830 1831 llvm_unreachable("unexpected attribute kind"); 1832 } 1833 1834 if (!passthroughs.empty()) 1835 funcOp.setPassthroughAttr(ArrayAttr::get(context, passthroughs)); 1836 } 1837 1838 void ModuleImport::processFunctionAttributes(llvm::Function *func, 1839 LLVMFuncOp funcOp) { 1840 processMemoryEffects(func, funcOp); 1841 processPassthroughAttrs(func, funcOp); 1842 1843 if (func->hasFnAttribute(llvm::Attribute::NoInline)) 1844 funcOp.setNoInline(true); 1845 if (func->hasFnAttribute(llvm::Attribute::AlwaysInline)) 1846 funcOp.setAlwaysInline(true); 1847 if (func->hasFnAttribute(llvm::Attribute::OptimizeNone)) 1848 funcOp.setOptimizeNone(true); 1849 if (func->hasFnAttribute(llvm::Attribute::Convergent)) 1850 funcOp.setConvergent(true); 1851 if (func->hasFnAttribute(llvm::Attribute::NoUnwind)) 1852 funcOp.setNoUnwind(true); 1853 if (func->hasFnAttribute(llvm::Attribute::WillReturn)) 1854 funcOp.setWillReturn(true); 1855 1856 if (func->hasFnAttribute("aarch64_pstate_sm_enabled")) 1857 funcOp.setArmStreaming(true); 1858 else if (func->hasFnAttribute("aarch64_pstate_sm_body")) 1859 funcOp.setArmLocallyStreaming(true); 1860 else if (func->hasFnAttribute("aarch64_pstate_sm_compatible")) 1861 funcOp.setArmStreamingCompatible(true); 1862 1863 if (func->hasFnAttribute("aarch64_new_za")) 1864 funcOp.setArmNewZa(true); 1865 else if (func->hasFnAttribute("aarch64_in_za")) 1866 funcOp.setArmInZa(true); 1867 else if (func->hasFnAttribute("aarch64_out_za")) 1868 funcOp.setArmOutZa(true); 1869 else if (func->hasFnAttribute("aarch64_inout_za")) 1870 funcOp.setArmInoutZa(true); 1871 else if (func->hasFnAttribute("aarch64_preserves_za")) 1872 funcOp.setArmPreservesZa(true); 1873 1874 llvm::Attribute attr = func->getFnAttribute(llvm::Attribute::VScaleRange); 1875 if (attr.isValid()) { 1876 MLIRContext *context = funcOp.getContext(); 1877 auto intTy = IntegerType::get(context, 32); 1878 funcOp.setVscaleRangeAttr(LLVM::VScaleRangeAttr::get( 1879 context, IntegerAttr::get(intTy, attr.getVScaleRangeMin()), 1880 IntegerAttr::get(intTy, attr.getVScaleRangeMax().value_or(0)))); 1881 } 1882 1883 // Process frame-pointer attribute. 1884 if (func->hasFnAttribute("frame-pointer")) { 1885 StringRef stringRefFramePointerKind = 1886 func->getFnAttribute("frame-pointer").getValueAsString(); 1887 funcOp.setFramePointerAttr(LLVM::FramePointerKindAttr::get( 1888 funcOp.getContext(), LLVM::framePointerKind::symbolizeFramePointerKind( 1889 stringRefFramePointerKind) 1890 .value())); 1891 } 1892 1893 if (llvm::Attribute attr = func->getFnAttribute("target-cpu"); 1894 attr.isStringAttribute()) 1895 funcOp.setTargetCpuAttr(StringAttr::get(context, attr.getValueAsString())); 1896 1897 if (llvm::Attribute attr = func->getFnAttribute("tune-cpu"); 1898 attr.isStringAttribute()) 1899 funcOp.setTuneCpuAttr(StringAttr::get(context, attr.getValueAsString())); 1900 1901 if (llvm::Attribute attr = func->getFnAttribute("target-features"); 1902 attr.isStringAttribute()) 1903 funcOp.setTargetFeaturesAttr( 1904 LLVM::TargetFeaturesAttr::get(context, attr.getValueAsString())); 1905 1906 if (llvm::Attribute attr = func->getFnAttribute("unsafe-fp-math"); 1907 attr.isStringAttribute()) 1908 funcOp.setUnsafeFpMath(attr.getValueAsBool()); 1909 1910 if (llvm::Attribute attr = func->getFnAttribute("no-infs-fp-math"); 1911 attr.isStringAttribute()) 1912 funcOp.setNoInfsFpMath(attr.getValueAsBool()); 1913 1914 if (llvm::Attribute attr = func->getFnAttribute("no-nans-fp-math"); 1915 attr.isStringAttribute()) 1916 funcOp.setNoNansFpMath(attr.getValueAsBool()); 1917 1918 if (llvm::Attribute attr = func->getFnAttribute("approx-func-fp-math"); 1919 attr.isStringAttribute()) 1920 funcOp.setApproxFuncFpMath(attr.getValueAsBool()); 1921 1922 if (llvm::Attribute attr = func->getFnAttribute("no-signed-zeros-fp-math"); 1923 attr.isStringAttribute()) 1924 funcOp.setNoSignedZerosFpMath(attr.getValueAsBool()); 1925 1926 if (llvm::Attribute attr = func->getFnAttribute("denormal-fp-math"); 1927 attr.isStringAttribute()) 1928 funcOp.setDenormalFpMathAttr( 1929 StringAttr::get(context, attr.getValueAsString())); 1930 1931 if (llvm::Attribute attr = func->getFnAttribute("denormal-fp-math-f32"); 1932 attr.isStringAttribute()) 1933 funcOp.setDenormalFpMathF32Attr( 1934 StringAttr::get(context, attr.getValueAsString())); 1935 1936 if (llvm::Attribute attr = func->getFnAttribute("fp-contract"); 1937 attr.isStringAttribute()) 1938 funcOp.setFpContractAttr(StringAttr::get(context, attr.getValueAsString())); 1939 } 1940 1941 DictionaryAttr 1942 ModuleImport::convertParameterAttribute(llvm::AttributeSet llvmParamAttrs, 1943 OpBuilder &builder) { 1944 SmallVector<NamedAttribute> paramAttrs; 1945 for (auto [llvmKind, mlirName] : getAttrKindToNameMapping()) { 1946 auto llvmAttr = llvmParamAttrs.getAttribute(llvmKind); 1947 // Skip attributes that are not attached. 1948 if (!llvmAttr.isValid()) 1949 continue; 1950 Attribute mlirAttr; 1951 if (llvmAttr.isTypeAttribute()) 1952 mlirAttr = TypeAttr::get(convertType(llvmAttr.getValueAsType())); 1953 else if (llvmAttr.isIntAttribute()) 1954 mlirAttr = builder.getI64IntegerAttr(llvmAttr.getValueAsInt()); 1955 else if (llvmAttr.isEnumAttribute()) 1956 mlirAttr = builder.getUnitAttr(); 1957 else 1958 llvm_unreachable("unexpected parameter attribute kind"); 1959 paramAttrs.push_back(builder.getNamedAttr(mlirName, mlirAttr)); 1960 } 1961 1962 return builder.getDictionaryAttr(paramAttrs); 1963 } 1964 1965 void ModuleImport::convertParameterAttributes(llvm::Function *func, 1966 LLVMFuncOp funcOp, 1967 OpBuilder &builder) { 1968 auto llvmAttrs = func->getAttributes(); 1969 for (size_t i = 0, e = funcOp.getNumArguments(); i < e; ++i) { 1970 llvm::AttributeSet llvmArgAttrs = llvmAttrs.getParamAttrs(i); 1971 funcOp.setArgAttrs(i, convertParameterAttribute(llvmArgAttrs, builder)); 1972 } 1973 // Convert the result attributes and attach them wrapped in an ArrayAttribute 1974 // to the funcOp. 1975 llvm::AttributeSet llvmResAttr = llvmAttrs.getRetAttrs(); 1976 if (!llvmResAttr.hasAttributes()) 1977 return; 1978 funcOp.setResAttrsAttr( 1979 builder.getArrayAttr(convertParameterAttribute(llvmResAttr, builder))); 1980 } 1981 1982 LogicalResult ModuleImport::processFunction(llvm::Function *func) { 1983 clearRegionState(); 1984 1985 auto functionType = 1986 dyn_cast<LLVMFunctionType>(convertType(func->getFunctionType())); 1987 if (func->isIntrinsic() && 1988 iface.isConvertibleIntrinsic(func->getIntrinsicID())) 1989 return success(); 1990 1991 bool dsoLocal = func->hasLocalLinkage(); 1992 CConv cconv = convertCConvFromLLVM(func->getCallingConv()); 1993 1994 // Insert the function at the end of the module. 1995 OpBuilder::InsertionGuard guard(builder); 1996 builder.setInsertionPoint(mlirModule.getBody(), mlirModule.getBody()->end()); 1997 1998 Location loc = debugImporter->translateFuncLocation(func); 1999 LLVMFuncOp funcOp = builder.create<LLVMFuncOp>( 2000 loc, func->getName(), functionType, 2001 convertLinkageFromLLVM(func->getLinkage()), dsoLocal, cconv); 2002 2003 convertParameterAttributes(func, funcOp, builder); 2004 2005 if (FlatSymbolRefAttr personality = getPersonalityAsAttr(func)) 2006 funcOp.setPersonalityAttr(personality); 2007 else if (func->hasPersonalityFn()) 2008 emitWarning(funcOp.getLoc(), "could not deduce personality, skipping it"); 2009 2010 if (func->hasGC()) 2011 funcOp.setGarbageCollector(StringRef(func->getGC())); 2012 2013 if (func->hasAtLeastLocalUnnamedAddr()) 2014 funcOp.setUnnamedAddr(convertUnnamedAddrFromLLVM(func->getUnnamedAddr())); 2015 2016 if (func->hasSection()) 2017 funcOp.setSection(StringRef(func->getSection())); 2018 2019 funcOp.setVisibility_(convertVisibilityFromLLVM(func->getVisibility())); 2020 2021 if (func->hasComdat()) 2022 funcOp.setComdatAttr(comdatMapping.lookup(func->getComdat())); 2023 2024 if (llvm::MaybeAlign maybeAlign = func->getAlign()) 2025 funcOp.setAlignment(maybeAlign->value()); 2026 2027 // Handle Function attributes. 2028 processFunctionAttributes(func, funcOp); 2029 2030 // Convert non-debug metadata by using the dialect interface. 2031 SmallVector<std::pair<unsigned, llvm::MDNode *>> allMetadata; 2032 func->getAllMetadata(allMetadata); 2033 for (auto &[kind, node] : allMetadata) { 2034 if (!iface.isConvertibleMetadata(kind)) 2035 continue; 2036 if (failed(iface.setMetadataAttrs(builder, kind, node, funcOp, *this))) { 2037 emitWarning(funcOp.getLoc()) 2038 << "unhandled function metadata: " << diagMD(node, llvmModule.get()) 2039 << " on " << diag(*func); 2040 } 2041 } 2042 2043 if (func->isDeclaration()) 2044 return success(); 2045 2046 // Collect the set of basic blocks reachable from the function's entry block. 2047 // This step is crucial as LLVM IR can contain unreachable blocks that 2048 // self-dominate. As a result, an operation might utilize a variable it 2049 // defines, which the import does not support. Given that MLIR lacks block 2050 // label support, we can safely remove unreachable blocks, as there are no 2051 // indirect branch instructions that could potentially target these blocks. 2052 llvm::df_iterator_default_set<llvm::BasicBlock *> reachable; 2053 for (llvm::BasicBlock *basicBlock : llvm::depth_first_ext(func, reachable)) 2054 (void)basicBlock; 2055 2056 // Eagerly create all reachable blocks. 2057 SmallVector<llvm::BasicBlock *> reachableBasicBlocks; 2058 for (llvm::BasicBlock &basicBlock : *func) { 2059 // Skip unreachable blocks. 2060 if (!reachable.contains(&basicBlock)) 2061 continue; 2062 Region &body = funcOp.getBody(); 2063 Block *block = builder.createBlock(&body, body.end()); 2064 mapBlock(&basicBlock, block); 2065 reachableBasicBlocks.push_back(&basicBlock); 2066 } 2067 2068 // Add function arguments to the entry block. 2069 for (const auto &it : llvm::enumerate(func->args())) { 2070 BlockArgument blockArg = funcOp.getFunctionBody().addArgument( 2071 functionType.getParamType(it.index()), funcOp.getLoc()); 2072 mapValue(&it.value(), blockArg); 2073 } 2074 2075 // Process the blocks in topological order. The ordered traversal ensures 2076 // operands defined in a dominating block have a valid mapping to an MLIR 2077 // value once a block is translated. 2078 SetVector<llvm::BasicBlock *> blocks = 2079 getTopologicallySortedBlocks(reachableBasicBlocks); 2080 setConstantInsertionPointToStart(lookupBlock(blocks.front())); 2081 for (llvm::BasicBlock *basicBlock : blocks) 2082 if (failed(processBasicBlock(basicBlock, lookupBlock(basicBlock)))) 2083 return failure(); 2084 2085 // Process the debug intrinsics that require a delayed conversion after 2086 // everything else was converted. 2087 if (failed(processDebugIntrinsics())) 2088 return failure(); 2089 2090 return success(); 2091 } 2092 2093 /// Checks if `dbgIntr` is a kill location that holds metadata instead of an SSA 2094 /// value. 2095 static bool isMetadataKillLocation(llvm::DbgVariableIntrinsic *dbgIntr) { 2096 if (!dbgIntr->isKillLocation()) 2097 return false; 2098 llvm::Value *value = dbgIntr->getArgOperand(0); 2099 auto *nodeAsVal = dyn_cast<llvm::MetadataAsValue>(value); 2100 if (!nodeAsVal) 2101 return false; 2102 return !isa<llvm::ValueAsMetadata>(nodeAsVal->getMetadata()); 2103 } 2104 2105 LogicalResult 2106 ModuleImport::processDebugIntrinsic(llvm::DbgVariableIntrinsic *dbgIntr, 2107 DominanceInfo &domInfo) { 2108 Location loc = translateLoc(dbgIntr->getDebugLoc()); 2109 auto emitUnsupportedWarning = [&]() { 2110 if (emitExpensiveWarnings) 2111 emitWarning(loc) << "dropped intrinsic: " << diag(*dbgIntr); 2112 return success(); 2113 }; 2114 // Drop debug intrinsics with arg lists. 2115 // TODO: Support debug intrinsics that have arg lists. 2116 if (dbgIntr->hasArgList()) 2117 return emitUnsupportedWarning(); 2118 // Kill locations can have metadata nodes as location operand. This 2119 // cannot be converted to poison as the type cannot be reconstructed. 2120 // TODO: find a way to support this case. 2121 if (isMetadataKillLocation(dbgIntr)) 2122 return emitUnsupportedWarning(); 2123 // Drop debug intrinsics if the associated variable information cannot be 2124 // translated due to cyclic debug metadata. 2125 // TODO: Support cyclic debug metadata. 2126 DILocalVariableAttr localVariableAttr = 2127 matchLocalVariableAttr(dbgIntr->getArgOperand(1)); 2128 if (!localVariableAttr) 2129 return emitUnsupportedWarning(); 2130 FailureOr<Value> argOperand = convertMetadataValue(dbgIntr->getArgOperand(0)); 2131 if (failed(argOperand)) 2132 return emitError(loc) << "failed to convert a debug intrinsic operand: " 2133 << diag(*dbgIntr); 2134 2135 // Ensure that the debug instrinsic is inserted right after its operand is 2136 // defined. Otherwise, the operand might not necessarily dominate the 2137 // intrinsic. If the defining operation is a terminator, insert the intrinsic 2138 // into a dominated block. 2139 OpBuilder::InsertionGuard guard(builder); 2140 if (Operation *op = argOperand->getDefiningOp(); 2141 op && op->hasTrait<OpTrait::IsTerminator>()) { 2142 // Find a dominated block that can hold the debug intrinsic. 2143 auto dominatedBlocks = domInfo.getNode(op->getBlock())->children(); 2144 // If no block is dominated by the terminator, this intrinisc cannot be 2145 // converted. 2146 if (dominatedBlocks.empty()) 2147 return emitUnsupportedWarning(); 2148 // Set insertion point before the terminator, to avoid inserting something 2149 // before landingpads. 2150 Block *dominatedBlock = (*dominatedBlocks.begin())->getBlock(); 2151 builder.setInsertionPoint(dominatedBlock->getTerminator()); 2152 } else { 2153 builder.setInsertionPointAfterValue(*argOperand); 2154 } 2155 auto locationExprAttr = 2156 debugImporter->translateExpression(dbgIntr->getExpression()); 2157 Operation *op = 2158 llvm::TypeSwitch<llvm::DbgVariableIntrinsic *, Operation *>(dbgIntr) 2159 .Case([&](llvm::DbgDeclareInst *) { 2160 return builder.create<LLVM::DbgDeclareOp>( 2161 loc, *argOperand, localVariableAttr, locationExprAttr); 2162 }) 2163 .Case([&](llvm::DbgValueInst *) { 2164 return builder.create<LLVM::DbgValueOp>( 2165 loc, *argOperand, localVariableAttr, locationExprAttr); 2166 }); 2167 mapNoResultOp(dbgIntr, op); 2168 setNonDebugMetadataAttrs(dbgIntr, op); 2169 return success(); 2170 } 2171 2172 LogicalResult ModuleImport::processDebugIntrinsics() { 2173 DominanceInfo domInfo; 2174 for (llvm::Instruction *inst : debugIntrinsics) { 2175 auto *intrCall = cast<llvm::DbgVariableIntrinsic>(inst); 2176 if (failed(processDebugIntrinsic(intrCall, domInfo))) 2177 return failure(); 2178 } 2179 return success(); 2180 } 2181 2182 LogicalResult ModuleImport::processBasicBlock(llvm::BasicBlock *bb, 2183 Block *block) { 2184 builder.setInsertionPointToStart(block); 2185 for (llvm::Instruction &inst : *bb) { 2186 if (failed(processInstruction(&inst))) 2187 return failure(); 2188 2189 // Skip additional processing when the instructions is a debug intrinsics 2190 // that was not yet converted. 2191 if (debugIntrinsics.contains(&inst)) 2192 continue; 2193 2194 // Set the non-debug metadata attributes on the imported operation and emit 2195 // a warning if an instruction other than a phi instruction is dropped 2196 // during the import. 2197 if (Operation *op = lookupOperation(&inst)) { 2198 setNonDebugMetadataAttrs(&inst, op); 2199 } else if (inst.getOpcode() != llvm::Instruction::PHI) { 2200 if (emitExpensiveWarnings) { 2201 Location loc = debugImporter->translateLoc(inst.getDebugLoc()); 2202 emitWarning(loc) << "dropped instruction: " << diag(inst); 2203 } 2204 } 2205 } 2206 return success(); 2207 } 2208 2209 FailureOr<SmallVector<AccessGroupAttr>> 2210 ModuleImport::lookupAccessGroupAttrs(const llvm::MDNode *node) const { 2211 return loopAnnotationImporter->lookupAccessGroupAttrs(node); 2212 } 2213 2214 LoopAnnotationAttr 2215 ModuleImport::translateLoopAnnotationAttr(const llvm::MDNode *node, 2216 Location loc) const { 2217 return loopAnnotationImporter->translateLoopAnnotation(node, loc); 2218 } 2219 2220 OwningOpRef<ModuleOp> 2221 mlir::translateLLVMIRToModule(std::unique_ptr<llvm::Module> llvmModule, 2222 MLIRContext *context, bool emitExpensiveWarnings, 2223 bool dropDICompositeTypeElements) { 2224 // Preload all registered dialects to allow the import to iterate the 2225 // registered LLVMImportDialectInterface implementations and query the 2226 // supported LLVM IR constructs before starting the translation. Assumes the 2227 // LLVM and DLTI dialects that convert the core LLVM IR constructs have been 2228 // registered before. 2229 assert(llvm::is_contained(context->getAvailableDialects(), 2230 LLVMDialect::getDialectNamespace())); 2231 assert(llvm::is_contained(context->getAvailableDialects(), 2232 DLTIDialect::getDialectNamespace())); 2233 context->loadAllAvailableDialects(); 2234 OwningOpRef<ModuleOp> module(ModuleOp::create(FileLineColLoc::get( 2235 StringAttr::get(context, llvmModule->getSourceFileName()), /*line=*/0, 2236 /*column=*/0))); 2237 2238 ModuleImport moduleImport(module.get(), std::move(llvmModule), 2239 emitExpensiveWarnings, dropDICompositeTypeElements); 2240 if (failed(moduleImport.initializeImportInterface())) 2241 return {}; 2242 if (failed(moduleImport.convertDataLayout())) 2243 return {}; 2244 if (failed(moduleImport.convertComdats())) 2245 return {}; 2246 if (failed(moduleImport.convertMetadata())) 2247 return {}; 2248 if (failed(moduleImport.convertGlobals())) 2249 return {}; 2250 if (failed(moduleImport.convertFunctions())) 2251 return {}; 2252 2253 return module; 2254 } 2255